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

/* ===============================
   INPUTS
================================ */
$search       = trim($_GET['search'] ?? '');
$statusFilter = $_GET['status'] ?? '';
$entityFilter = $_GET['entity'] ?? '';
$page         = max(1, (int)($_GET['page'] ?? 1));
$perPage      = 25;
$offset       = ($page - 1) * $perPage;

/* ===============================
   BUILD WHERE CLAUSE
================================ */
$conditions = [];
$params = [];

/* SOFT DELETE FILTER */
$conditions[] = "deleted_at IS NULL";

/* TEXT SEARCH */
if ($search !== '') {
    $conditions[] = "(
        mpesa_receipt LIKE :q
        OR phone LIKE :q
        OR id LIKE :q
    )";
    $params['q'] = "%$search%";
}

/* ENTITY FILTER */
if ($entityFilter !== '') {
    $conditions[] = "entity = :entity";
    $params['entity'] = $entityFilter;
}

/* STATUS FILTER */
if ($statusFilter !== '') {
    $conditions[] = "status = :status";
    $params['status'] = $statusFilter;
}

$where = $conditions ? 'WHERE ' . implode(' AND ', $conditions) : '';

/* ===============================
   TOTALS
================================ */
$totalStmt = $pdo->prepare("
    SELECT
        COUNT(*) AS total_rows,
        COALESCE(SUM(CASE WHEN status='paid' THEN amount END),0) AS total_paid,
        COALESCE(SUM(CASE WHEN status='failed' THEN amount END),0) AS total_failed,
        COALESCE(SUM(CASE WHEN status='pending' THEN amount END),0) AS total_pending
    FROM mpesa_payments
    $where
");
$totalStmt->execute($params);
$totals = $totalStmt->fetch(PDO::FETCH_ASSOC);

/* ===============================
   PAGINATED DATA
================================ */
$stmt = $pdo->prepare("
    SELECT *
    FROM mpesa_payments
    $where
    ORDER BY created_at DESC
    LIMIT :limit OFFSET :offset
");

foreach ($params as $k => $v) {
    $stmt->bindValue(":$k", $v);
}

$stmt->bindValue(':limit', $perPage, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();

$txns = $stmt->fetchAll(PDO::FETCH_ASSOC);
$totalPages = max(1, ceil($totals['total_rows'] / $perPage));

/* ===============================
   HELPERS
================================ */
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>Payment Receipts</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

<style>
body{font-family:Arial;background:#f4f6f8;padding:30px}
.container{max-width:1200px;margin:auto;background:#fff;padding:25px;border-radius:6px}
.search-box{display:grid;grid-template-columns:1fr 180px 180px auto;gap:10px;margin-bottom:15px}
input,select,button{padding:8px}
table{width:100%;border-collapse:collapse}
th,td{padding:10px;border-bottom:1px solid #ddd}
th{background:#f1f1f1}
.paid{color:#2e7d32;font-weight:bold}
.failed{color:#c62828;font-weight:bold}
.pending{color:#f57c00;font-weight:bold}
.totals{display:flex;gap:20px;margin-bottom:15px;font-weight:bold}
.pagination{text-align:center;margin-top:20px}
.pagination a{margin:0 6px;text-decoration:none}
.pagination strong{margin:0 6px}
.action a{
    padding:6px 10px;
    background:#455a64;
    color:#fff;
    text-decoration:none;
    border-radius:4px;
    font-size:13px;
}
.export-box{margin-bottom:15px}
.export-box button{
    padding:8px 14px;
    background:#1b5e20;
    color:#fff;
    border:none;
    border-radius:4px;
    cursor:pointer;
    font-weight:bold;
}
</style>
</head>

<body>

<a href="/admin/logout.php" style="float:right;color:#c62828;text-decoration:none;">Logout</a>

<div class="container">
<h2>Payment Receipts</h2>

<!-- FILTERS -->
<form class="search-box" method="get">
<input type="text" name="search" placeholder="Mpesa / Phone / ID" value="<?= htmlspecialchars($search) ?>">

<select name="entity">
<option value="">All Entities</option>
<option value="Tanidot" <?= $entityFilter==='Tanidot'?'selected':'' ?>>Tanidot</option>
<option value="Swingtide" <?= $entityFilter==='Swingtide'?'selected':'' ?>>Swingtide</option>
<option value="Hamotel" <?= $entityFilter==='Hamotel'?'selected':'' ?>>Hamotel</option>
</select>

<select name="status">
<option value="">All Statuses</option>
<option value="paid" <?= $statusFilter==='paid'?'selected':'' ?>>PAID</option>
<option value="pending" <?= $statusFilter==='pending'?'selected':'' ?>>PENDING</option>
<option value="failed" <?= $statusFilter==='failed'?'selected':'' ?>>FAILED</option>
</select>

<button type="submit">Search</button>
</form>

<?php if (!empty($txns)): ?>
<div class="export-box">
<form method="post" action="export_receipts_pdf.php" id="exportForm">
<?php foreach ($_GET as $k => $v): ?>
<input type="hidden" name="<?= htmlspecialchars($k) ?>" value="<?= htmlspecialchars($v) ?>">
<?php endforeach; ?>
<button type="submit">Export PDF</button>
<?php endif; ?>

<div class="totals">
<span class="paid">Paid: KES <?= number_format($totals['total_paid'],2) ?></span>
<span class="failed">Failed: KES <?= number_format($totals['total_failed'],2) ?></span>
<span class="pending">Pending: KES <?= number_format($totals['total_pending'],2) ?></span>
</div>

<?php if (empty($txns)): ?>
<p style="color:#c62828;font-weight:bold">No transactions found.</p>
<?php else: ?>

<table>
<thead>
<tr>
<th><input type="checkbox" onclick="document.querySelectorAll('.row-check').forEach(c=>c.checked=this.checked)"></th>
<th>Date</th>
<th>ID</th>
<th>Entity</th>
<th>Mpesa Receipt</th>
<th>Phone</th>
<th>Amount</th>
<th>Status</th>
<th>Result Desc</th>
<th>Action</th>
</tr>
</thead>
<tbody>

<?php foreach ($txns as $t): ?>
<?php $status = strtolower($t['status'] ?? 'pending'); ?>
<tr>
<td><input type="checkbox" class="row-check" name="ids[]" value="<?= (int)$t['id'] ?>"></td>
<td><?= htmlspecialchars($t['created_at']) ?></td>
<td><?= htmlspecialchars($t['id']) ?></td>
<td><?= htmlspecialchars($t['entity']) ?></td>
<td><?= htmlspecialchars($t['mpesa_receipt'] ?? '-') ?></td>
<td><?= htmlspecialchars(formatPhoneDisplay($t['phone'] ?? '')) ?></td>
<td><?= number_format($t['amount'],2) ?></td>
<td class="<?= $status ?>"><?= strtoupper($status) ?></td>
<td><?= htmlspecialchars((string)($t['result_desc'] ?? '')) ?></td>
<td class="action">
<?php if ($status === 'paid'): ?>
<a href="receipt_pdf.php?id=<?= urlencode($t['id']) ?>">PDF</a>
<?php else: ?>
—
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>

</tbody>
</table>

</form>

<div class="pagination">
<?php for ($i=1;$i<=$totalPages;$i++): ?>
<?php if ($i === $page): ?>
<strong><?= $i ?></strong>
<?php else: ?>
<a href="?<?= http_build_query(array_merge($_GET,['page'=>$i])) ?>"><?= $i ?></a>
<?php endif; ?>
<?php endfor; ?>
</div>

<?php endif; ?>

</div>

<script>
document.getElementById('exportForm')?.addEventListener('submit', function () {
    const checked = document.querySelectorAll('.row-check:checked');
    if (checked.length > 0) {
        this.querySelectorAll('input[type=hidden]').forEach(e => e.remove());
    }
});
</script>

</body>
</html>
