<?php
require_once __DIR__ . '/../admin/auth.php';
require_once __DIR__ . '/config.php';

/* ---------------------------------------------
   HELPERS
--------------------------------------------- */
function kes($amount) {
    return 'KES ' . number_format((float)$amount, 2);
}

/* ---------------------------------------------
   AJAX HANDLERS
--------------------------------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax'])) {
    header('Content-Type: application/json');

    // Restore single
    if ($_POST['action'] === 'restore' && isset($_POST['id'])) {
        $stmt = $pdo->prepare(
            "UPDATE mpesa_payments SET deleted_at = NULL WHERE id = ?"
        );
        $stmt->execute([(int)$_POST['id']]);
        echo json_encode(['success' => true]);
        exit;
    }

    // Restore all
    if ($_POST['action'] === 'restore_all') {
        $stmt = $pdo->prepare(
            "UPDATE mpesa_payments SET deleted_at = NULL WHERE deleted_at IS NOT NULL"
        );
        $stmt->execute();
        echo json_encode(['success' => true]);
        exit;
    }

    // Permanent delete
    if ($_POST['action'] === 'force_delete' && isset($_POST['id'])) {
        $stmt = $pdo->prepare(
            "DELETE FROM mpesa_payments WHERE id = ?"
        );
        $stmt->execute([(int)$_POST['id']]);
        echo json_encode(['success' => true]);
        exit;
    }

    echo json_encode(['success' => false]);
    exit;
}

/* ---------------------------------------------
   LOAD TRASH DATA
--------------------------------------------- */
$stmt = $pdo->query("
    SELECT *
    FROM mpesa_payments
    WHERE deleted_at IS NOT NULL
    ORDER BY deleted_at DESC
");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Trash – M-Pesa Payments</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<style>
body{
    font-family:Segoe UI,system-ui,sans-serif;
    background:#eef1f5;
    padding:30px;
}
.container{
    background:#fff;
    padding:25px;
    border-radius:12px;
    max-width:1200px;
    margin:auto;
    box-shadow:0 10px 30px rgba(0,0,0,.08);
}
.topbar{
    display:flex;
    justify-content:space-between;
    align-items:center;
    margin-bottom:15px;
}
h2{margin:0}
.btn{
    padding:6px 12px;
    border-radius:6px;
    border:none;
    cursor:pointer;
    font-weight:600;
}
.btn-success{background:#198754;color:#fff}
.btn-danger{background:#dc3545;color:#fff}
.btn-secondary{background:#6c757d;color:#fff}
table{
    width:100%;
    border-collapse:collapse;
    margin-top:10px;
}
th,td{
    padding:10px;
    border-bottom:1px solid #ddd;
}
thead{
    background:#343a40;
    color:#fff;
}
.actions button{
    margin-right:6px;
}
.empty{
    text-align:center;
    padding:30px;
    color:#6c757d;
    font-weight:600;
}
</style>
</head>

<body>

<div class="container">

    <div class="topbar">
        <h2>🗑️ Trash (Soft Deleted Transactions)</h2>
        <div>
            <a href="manage.php" class="btn btn-secondary">← Back</a>
            <?php if (!empty($rows)): ?>
                <button id="restoreAllBtn" class="btn btn-success">♻️ Restore All</button>
            <?php endif; ?>
        </div>
    </div>

    <?php if (empty($rows)): ?>
        <div class="empty">Trash is empty.</div>
    <?php else: ?>

    <table>
        <thead>
            <tr>
                <th>Date</th>
                <th>ID</th>
                <th>Entity</th>
                <th>Amount</th>
                <th>Status</th>
                <th>Deleted At</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($rows as $r): ?>
            <tr id="row<?= (int)$r['id'] ?>">
                <td><?= htmlspecialchars($r['created_at'] ?? '-') ?></td>
                <td><?= (int)$r['id'] ?></td>
                <td><?= htmlspecialchars($r['entity'] ?? '-') ?></td>
                <td><?= kes($r['amount'] ?? 0) ?></td>
                <td><?= ucfirst($r['status'] ?? '-') ?></td>
                <td><?= htmlspecialchars($r['deleted_at']) ?></td>
                <td class="actions">
                    <button class="btn btn-success restore"
                            data-id="<?= (int)$r['id'] ?>">
                        Restore
                    </button>
                    <button class="btn btn-danger forceDelete"
                            data-id="<?= (int)$r['id'] ?>">
                        Delete
                    </button>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>

    <?php endif; ?>

</div>

<script>
/* Restore single */
document.querySelectorAll('.restore').forEach(btn => {
    btn.onclick = () => {
        fetch('', {
            method:'POST',
            headers:{'Content-Type':'application/x-www-form-urlencoded'},
            body:`ajax=1&action=restore&id=${btn.dataset.id}`
        })
        .then(r => r.json())
        .then(d => {
            if (d.success) {
                document.getElementById('row'+btn.dataset.id)?.remove();
            }
        });
    };
});

/* Permanent delete */
document.querySelectorAll('.forceDelete').forEach(btn => {
    btn.onclick = () => {
        if (!confirm('Permanently delete this record?')) return;
        fetch('', {
            method:'POST',
            headers:{'Content-Type':'application/x-www-form-urlencoded'},
            body:`ajax=1&action=force_delete&id=${btn.dataset.id}`
        })
        .then(r => r.json())
        .then(d => {
            if (d.success) {
                document.getElementById('row'+btn.dataset.id)?.remove();
            }
        });
    };
});

/* Restore all */
document.getElementById('restoreAllBtn')?.addEventListener('click', () => {
    if (!confirm('Restore ALL deleted transactions?')) return;

    fetch('', {
        method:'POST',
        headers:{'Content-Type':'application/x-www-form-urlencoded'},
        body:'ajax=1&action=restore_all'
    })
    .then(r => r.json())
    .then(d => {
        if (d.success) location.reload();
    });
});
</script>

</body>
</html>
