<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

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

$trashCount = $pdo->query(
    "SELECT COUNT(*) FROM mpesa_payments WHERE deleted_at IS NOT NULL"
)->fetchColumn();

/* ---------------------------------------------
   HELPERS
--------------------------------------------- */
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([71]\d{8})$/', $phone, $m)) return '0'.$m[1];
    return $phone;
}

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

$where  = ["deleted_at IS 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);

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

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

    if ($_POST['action'] === 'bulk' && !empty($_POST['ids'])) {
        $ids = array_map('intval', $_POST['ids']);
        $in  = implode(',', array_fill(0,count($ids),'?'));
        $stmt = $pdo->prepare(
            "UPDATE mpesa_payments SET deleted_at=NOW() WHERE id IN ($in)"
        );
        $stmt->execute($ids);
        echo json_encode(['success'=>true]);
        exit;
    }

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

/* ---------------------------------------------
   EXPORT PDF
--------------------------------------------- */
if (isset($_POST['export_pdf'])) {

    if (!empty($_POST['ids'])) {
        $ids = array_map('intval', $_POST['ids']);
        $in  = implode(',', array_fill(0,count($ids),'?'));
        $stmt = $pdo->prepare(
            "SELECT * FROM mpesa_payments 
             WHERE deleted_at IS NULL AND id IN ($in)
             ORDER BY created_at DESC"
        );
        $stmt->execute($ids);
    } else {
        $stmt = $pdo->prepare(
            "SELECT * FROM mpesa_payments $whereSQL ORDER BY created_at DESC"
        );
        $stmt->execute($params);
    }

    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    class PDF extends FPDF {
        function Footer() {
            $this->SetY(-15);
            $this->SetFont('Arial','I',8);
            $this->Cell(0,10,'Page '.$this->PageNo().'/{nb}',0,0,'C');
        }
    }

    $pdf = new PDF();
    $pdf->AliasNbPages();
    $pdf->AddPage();
    $pdf->SetFont('Arial','B',14);
    $pdf->Cell(0,10,'M-Pesa Payments Report',0,1,'C');
    $pdf->Ln(4);

    $pdf->SetFont('Arial','B',9);
    foreach (['Date','ID','Entity','Receipt','Phone','Amount','Status'] as $h) {
        $pdf->Cell(28,7,$h,1);
    }
    $pdf->Ln();

    $pdf->SetFont('Arial','',9);
    foreach ($rows as $r) {
        $pdf->Cell(30,7,$r['created_at'],1);
        $pdf->Cell(26,7,$r['id'],1);
        $pdf->Cell(28,7,$r['entity'],1);
        $pdf->Cell(28,7,$r['mpesa_receipt'] ?: '-',1);
        $pdf->Cell(28,7,formatPhoneDisplay($r['phone']),1);
        $pdf->Cell(28,7,kes($r['amount']),1,0,'R');
        $pdf->Cell(28,7,ucfirst($r['status']),1);
        $pdf->Ln();
    }

    header('Content-Type: application/pdf');
    header('Content-Disposition: inline; filename=mpesa_report.pdf');
    $pdf->Output();
    exit;
}

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

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>M-Pesa Payments</title>
<style>
body{font-family:Segoe UI;background:#eef1f5;padding:30px}
.container{background:#fff;padding:25px;border-radius:10px}
.btn{padding:6px 10px;border-radius:6px;border:none;cursor:pointer}
.btn-danger{background:#dc3545;color:#fff}
.btn-success{background:#198754;color:#fff}
.btn-info{background:#0dcaf0;color:#fff}
.btn-search{background:#0d6efd;color:#fff}
.badge{padding:4px 10px;border-radius:20px;color:#fff}
.badge-paid{background:#198754}
.badge-failed{background:#dc3545}
.badge-pending{background:#fd7e14}
table{width:100%;border-collapse:collapse;margin-top:10px}
th,td{padding:8px;border-bottom:1px solid #ddd}
thead{background:#0d6efd;color:#fff}
.btn-warning{
    background:#ffc107;
    color:#000;
    text-decoration:none;
    padding:6px 12px;
    border-radius:6px;
    font-weight:600;
}
.btn-warning:hover{
    background:#ffca2c;
}

</style>
</head>

<body>

<div class="container">
<h2>📊 M-Pesa Payments</h2>

<form method="get">
<input name="q" placeholder="Search" value="<?=htmlspecialchars($q)?>">
<input type="date" name="from" value="<?=htmlspecialchars($from)?>">
<input type="date" name="to" value="<?=htmlspecialchars($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 class="btn btn-search">Search</button>
</form>

<form method="post" id="bulkForm">
<br>
<button name="export_pdf" class="btn btn-success">Export PDF</button>
<button type="button" id="bulkDelete" class="btn btn-danger" disabled>
Delete Selected
</button>
<a href="trash.php" class="btn btn-warning" style="margin-left:8px;">
    🗑️ Trash(<?= (int)$trashCount ?>)
</a>

<table>
<thead>
<tr>
<th><input type="checkbox" id="checkAll"></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 id="row<?=$r['id']?>">
<td><input class="chk" type="checkbox" value="<?=$r['id']?>"></td>
<td><?=htmlspecialchars($r['created_at'])?></td>
<td><?=$r['id']?></td>
<td><?=htmlspecialchars($r['entity'])?></td>
<td><?=htmlspecialchars($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>
<button type="button" class="btn btn-danger singleDelete" data-id="<?=$r['id']?>">Delete</button>
<a class="btn btn-info" target="_blank" href="receipt_pdf.php?id=<?=$r['id']?>">Receipt</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</form>
</div>

<script>
const checkAll = document.getElementById('checkAll');
const bulkBtn  = document.getElementById('bulkDelete');

function updateBulkState() {
    bulkBtn.disabled = !document.querySelectorAll('.chk:checked').length;
}

checkAll?.addEventListener('change', e => {
    document.querySelectorAll('.chk').forEach(c => c.checked = e.target.checked);
    updateBulkState();
});

document.querySelectorAll('.chk').forEach(c =>
    c.addEventListener('change', updateBulkState)
);

// SINGLE DELETE
document.querySelectorAll('.singleDelete').forEach(btn => {
    btn.onclick = () => {
        if (!confirm('Delete this transaction?')) return;
        fetch('', {
            method:'POST',
            headers:{'Content-Type':'application/x-www-form-urlencoded'},
            body:`ajax=1&action=single&id=${btn.dataset.id}`
        }).then(()=>document.getElementById('row'+btn.dataset.id)?.remove());
    };
});

// BULK DELETE
bulkBtn.onclick = () => {
    if (!confirm('Delete selected transactions?')) return;
    const ids = [...document.querySelectorAll('.chk:checked')].map(c=>c.value);
    fetch('', {
        method:'POST',
        headers:{'Content-Type':'application/x-www-form-urlencoded'},
        body:`ajax=1&action=bulk&${ids.map(i=>'ids[]='+i).join('&')}`
    }).then(()=>ids.forEach(id=>document.getElementById('row'+id)?.remove()));
};
</script>

</body>
</html>
