<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/auth.php';
requireAdmin();

// Handle approve/reject
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!validateCsrf()) { setFlash('error', 'CSRF error.'); header('Location: ' . url('/admin/validasi.php')); exit; }
    $trxId = (int)$_POST['transaksi_id'];
    $action = $_POST['action'] ?? '';

    if ($action === 'approve') {
        $pdo->beginTransaction();
        try {
            $pdo->prepare("UPDATE transaksi SET status='tervalidasi' WHERE id=?")->execute([$trxId]);
            // Get transaction details
            $trx = $pdo->prepare("SELECT user_id FROM transaksi WHERE id=?");
            $trx->execute([$trxId]); $trxData = $trx->fetch();
            $details = $pdo->prepare("SELECT kelas_id FROM detail_transaksi WHERE transaksi_id=?");
            $details->execute([$trxId]); $detailList = $details->fetchAll();
            foreach ($detailList as $d) {
                $pdo->prepare("INSERT INTO absensi (transaksi_id, user_id, kelas_id, status) VALUES (?,?,?,'hadir')")->execute([$trxId, $trxData['user_id'], $d['kelas_id']]);
                $pdo->prepare("UPDATE kelas SET sisa_slot = GREATEST(sisa_slot - 1, 0) WHERE id=?")->execute([$d['kelas_id']]);
            }
            $pdo->commit();
            setFlash('success', 'Transaksi #' . $trxId . ' berhasil divalidasi!');
        } catch (Exception $e) { $pdo->rollBack(); setFlash('error', 'Gagal validasi.'); }
    } elseif ($action === 'reject') {
        $pdo->prepare("UPDATE transaksi SET status='ditolak' WHERE id=?")->execute([$trxId]);
        setFlash('info', 'Transaksi #' . $trxId . ' ditolak.');
    }
    header('Location: ' . url('/admin/validasi.php')); exit;
}

// Fetch pending transactions
$stmt = $pdo->query("
    SELECT t.*, u.nama, u.email
    FROM transaksi t JOIN users u ON t.user_id = u.id
    WHERE t.status = 'pending' AND t.bukti_bayar IS NOT NULL
    ORDER BY t.created_at ASC
");
$pendingList = $stmt->fetchAll();

require_once __DIR__ . '/../includes/header.php';
?>
<div class="max-w-6xl mx-auto px-4 py-8">
    <div class="mb-8 animate-fadeUp"><h1 class="text-3xl font-black mb-2">Validasi <span class="text-volt">Pembayaran</span></h1><p class="text-muted text-sm">Approve atau reject bukti pembayaran member</p></div>

    <?php if (empty($pendingList)): ?>
        <div class="empty-state"><div class="emoji">✅</div><p class="text-lg font-bold mb-2">Tidak Ada Pending</p><p class="text-sm text-muted">Semua pembayaran sudah diproses</p></div>
    <?php else: ?>
    <div class="space-y-6">
    <?php foreach ($pendingList as $i => $trx):
        $delay = 'd' . min($i+1, 12);
        $detStmt = $pdo->prepare("SELECT dt.*, k.nama_kelas FROM detail_transaksi dt JOIN kelas k ON dt.kelas_id = k.id WHERE dt.transaksi_id = ?");
        $detStmt->execute([$trx['id']]); $details = $detStmt->fetchAll();
    ?>
    <div class="card animate-fadeUp <?= $delay ?>">
        <div class="flex flex-wrap items-start justify-between gap-4 mb-4">
            <div>
                <p class="font-bold text-lg"><?= htmlspecialchars($trx['nama']) ?></p>
                <p class="text-xs text-muted"><?= htmlspecialchars($trx['email']) ?> · <?= date('d M Y, H:i', strtotime($trx['created_at'])) ?></p>
            </div>
            <span class="badge-pending">Pending</span>
        </div>

        <div class="grid md:grid-cols-2 gap-6">
            <div>
                <p class="text-xs text-muted font-bold uppercase mb-2">Kelas yang Dibooking</p>
                <div class="space-y-2">
                <?php foreach ($details as $d): ?>
                    <div class="flex justify-between text-sm"><span><?= htmlspecialchars($d['nama_kelas']) ?></span><span class="text-volt font-bold">Rp <?= number_format($d['harga_satuan'],0,',','.') ?></span></div>
                <?php endforeach; ?>
                </div>
                <div class="mt-3 pt-3 border-t border-border flex justify-between font-bold"><span>Total</span><span class="text-volt text-lg">Rp <?= number_format($trx['total_harga'],0,',','.') ?></span></div>
            </div>
            <div>
                <p class="text-xs text-muted font-bold uppercase mb-2">Bukti Pembayaran</p>
                <a href="<?= BASE_URL ?>/assets/uploads/<?= htmlspecialchars($trx['bukti_bayar']) ?>" target="_blank" class="block">
                    <img src="<?= BASE_URL ?>/assets/uploads/<?= htmlspecialchars($trx['bukti_bayar']) ?>" alt="Bukti bayar" class="w-full max-w-xs rounded-lg border border-border hover:border-volt transition-colors">
                </a>
            </div>
        </div>

        <div class="flex gap-3 mt-6 pt-4 border-t border-border">
            <form method="POST" class="flex-1"><input type="hidden" name="csrf_token" value="<?= csrfToken() ?>"><input type="hidden" name="transaksi_id" value="<?= $trx['id'] ?>"><input type="hidden" name="action" value="approve"><button type="submit" class="btn-volt w-full py-3" onclick="return confirm('Approve transaksi ini?')">✓ Approve</button></form>
            <form method="POST" class="flex-1"><input type="hidden" name="csrf_token" value="<?= csrfToken() ?>"><input type="hidden" name="transaksi_id" value="<?= $trx['id'] ?>"><input type="hidden" name="action" value="reject"><button type="submit" class="w-full py-3 bg-red-500/10 text-red-400 border border-red-500/30 rounded-lg font-bold hover:bg-red-500/20 transition-colors" onclick="return confirm('Reject transaksi ini?')">✕ Reject</button></form>
        </div>
    </div>
    <?php endforeach; ?>
    </div>
    <?php endif; ?>
</div>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
