<?php
/* =================================================
   TRASH PAGE WITH RBAC, AJAX, RESTORE, DELETE
   Soft deletes via `deleted_at` column
================================================= */
ini_set('display_errors',1);
error_reporting(E_ALL);

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

// Roles
$role = $_SESSION['admin_role'] ?? 'viewer';
$user = $_SESSION['admin_user'] ?? 'Unknown';

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

    $action = $_POST['action'] ?? '';
    $id = isset($_POST['id']) ? (int)$_POST['id'] : null;

    if ($action === 'restore' && $id) {
        if (!in_array($role, ['superadmin','manager'])) {
            echo json_encode(['success'=>false,'error'=>'Permission denied']); exit;
        }
        $stmt = $pdo->prepare("UPDATE mpesa_payments SET deleted_at=NULL WHERE id=?");
        $stmt->execute([$id]);
        echo json_encode(['success'=>true]); exit;
    }

    if ($action === 'restore_all') {
        if (!in_array($role, ['superadmin','manager'])) {
            echo json_encode(['success'=>false,'error'=>'Permission denied']); exit;
        }
        $stmt = $pdo->prepare("UPDATE mpesa_payments SET deleted_at=NULL WHERE deleted_at IS NOT NULL");
        $stmt->execute();
        echo json_encode(['success'=>true]); exit;
    }

    if ($action === 'force_delete' && $id) {
        if ($role !== 'superadmin') {
            echo json_encode(['success'=>false,'error'=>'Permission denied']); exit;
        }
        $stmt = $pdo->prepare("DELETE FROM mpesa_payments WHERE id=?");
        $stmt->execute([$id]);
        echo json_encode(['success'=>true]); exit;
    }

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

// FILTERS
$q      = trim($_GET['q'] ?? '');
$status = $_GET['status'] ?? '';
$from   = $_GET['from'] ?? '';
$to     = $_GET['to'] ?? '';

$where = ['deleted_at IS NOT NULL'];
$params = [];

if ($q !== '') {
    $where[] = "(phone LIKE :q OR mpesa_receipt LIKE :q OR entity LIKE :q OR id LIKE :q)";
    $params['q'] = "%$q%";
}
if ($status !== '') {
    $where[] = "status = :status";
    $params['status'] = $status;
}
if ($from !== '') {
    $where[] = "created_at >= :from";
    $params['from'] = "$from 00:00:00";
}
if ($to !== '') {
    $where[] = "created_at <= :to";
    $params['to'] = "$to 23:59:59";
}

$whereSQL = 'WHERE '.implode(' AND ',$where);

// FETCH ROWS
$stmt = $pdo->prepare("SELECT * FROM mpesa_payments $whereSQL ORDER BY created_at DESC LIMIT 100");
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

// TOTALS PANEL
$stmtTotals = $pdo->prepare("
    SELECT 
        SUM(CASE WHEN status='paid' THEN amount ELSE 0 END) AS paid,
        SUM(CASE WHEN status='failed' THEN amount ELSE 0 END) AS failed,
        SUM(CASE WHEN status='pending' THEN amount ELSE 0 END) AS pending
    FROM mpesa_payments
    $whereSQL
");
$stmtTotals->execute($params);
$totals = $stmtTotals->fetch(PDO::FETCH_ASSOC);

// HELPER
function kes($amount){ return 'KES '.number_format((float)$amount,2); }
function formatPhoneDisplay(?string $phone): string {
    if (!$phone) return '-';
    $phone = preg_replace('/\s+/','',$phone);
    if(preg_match('/^254(7\d{8}|1\d{8})$/',$phone,$m)) return '0'.$m[1];
    return $phone;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Trash - M-Pesa Payments</title>
<style>
body{font-family:Segoe UI;background:#eef1f5;padding:20px}
.container{background:#fff;padding:25px;border-radius:10px}
h2{margin-bottom:10px}
.filters input, .filters select, .filters button{padding:6px 10px;margin-right:6px}
table{width:100%;border-collapse:collapse;margin-top:10px}
th, td{padding:8px;border-bottom:1px solid #ddd;text-align:center}
thead{background:#0d6efd;color:#fff}
.btn{padding:5px 10px;border:none;border-radius:6px;cursor:pointer}
.btn-success{background:#198754;color:#fff}
.btn-danger{background:#dc3545;color:#fff}
.btn-info{background:#0dcaf0;color:#fff}
.badge{padding:3px 8px;border-radius:12px;color:#fff}
.badge-paid{background:#198754}
.badge-failed{background:#dc3545}
.badge-pending{background:#fd7e14}
.actions button{margin:2px}
.totals{display:flex;gap:15px;margin:10px 0}
.totals div{padding:8px 12px;border-radius:8px;background:#f0f0f0;font-weight:bold}
</style>
<script>
function ajaxAction(action,id=null){
    let formData = new FormData();
    formData.append('ajax',1);
    formData.append('action',action);
    if(id) formData.append('id',id);

    fetch('', {method:'POST', body: formData})
    .then(r=>r.json())
    .then(d=>{
        if(d.success) location.reload();
        else alert(d.error || 'Action failed');
    });
}

function toggleBulkDelete() {
    const checkboxes = document.querySelectorAll('.chk');
    const btn = document.getElementById('bulkDeleteBtn');
    btn.disabled = ![...checkboxes].some(c=>c.checked);
}
</script>
</head>
<body>

<div class="container">
<h2>🗑️ Trash - M-Pesa Payments</h2>
<div>Logged in as <strong><?=htmlspecialchars($user)?></strong> (Role: <?=htmlspecialchars($role)?>)</div>

<!-- FILTERS -->
<form class="filters" method="get">
<input type="text" name="q" placeholder="Search" value="<?=htmlspecialchars($q)?>">
<input type="date" name="from" value="<?=$from?>">
<input type="date" name="to" value="<?=$to?>">
<select name="status">
<option value="">All</option>
<?php foreach(['paid','failed','pending'] as $s): ?>
<option value="<?=$s?>" <?=$status===$s?'selected':''?>><?=ucfirst($s)?></option>
<?php endforeach; ?>
</select>
<button type="submit" class="btn btn-info">Filter</button>
</form>

<!-- TOTALS PANEL -->
<div class="totals">
<div>Paid: <?=kes($totals['paid'])?></div>
<div>Failed: <?=kes($totals['failed'])?></div>
<div>Pending: <?=kes($totals['pending'])?></div>
</div>

<!-- ACTION BUTTONS -->
<?php if(in_array($role,['superadmin','manager'])): ?>
<button class="btn btn-success" onclick="ajaxAction('restore_all')">♻️ Restore All</button>
<?php endif; ?>

<form method="post" id="trashForm">
<table>
<thead>
<tr>
<th><input type="checkbox" onclick="document.querySelectorAll('.chk').forEach(c=>c.checked=this.checked); toggleBulkDelete();"></th>
<th>Date</th><th>ID</th><th>Entity</th><th>Receipt</th><th>Phone</th><th>Amount</th><th>Status</th><th>Actions</th>
</tr>
</thead>
<tbody>
<?php foreach($rows as $r): ?>
<tr>
<td><input type="checkbox" class="chk" name="ids[]" value="<?=$r['id']?>" onclick="toggleBulkDelete()"></td>
<td><?=$r['created_at']?></td>
<td><?=$r['id']?></td>
<td><?=$r['entity']?></td>
<td><?=$r['mpesa_receipt']?></td>
<td><?=formatPhoneDisplay($r['phone'])?></td>
<td><?=kes($r['amount'])?></td>
<td><span class="badge badge-<?=$r['status']?>"><?=ucfirst($r['status'])?></span></td>
<td class="actions">
<?php if(in_array($role,['superadmin','manager'])): ?>
<button type="button" class="btn btn-success" onclick="ajaxAction('restore',<?=$r['id']?>)">Restore</button>
<?php else: ?>
<button type="button" class="btn btn-success" disabled>Restore</button>
<?php endif; ?>

<?php if($role==='superadmin'): ?>
<button type="button" class="btn btn-danger" onclick="ajaxAction('force_delete',<?=$r['id']?>)">Delete</button>
<?php else: ?>
<button type="button" class="btn btn-danger" disabled>Delete</button>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</form>
</div>

</body>
</html>
