<?php
require_once 'init.php';

$filterStatus = $_GET['status'] ?? '';

// Handle approve / reject actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $paymentId = intval($_POST['payment_id'] ?? 0);
    $action    = $_POST['action'] ?? '';

    if ($paymentId) {
        if ($action === 'approve') {
            $subscription->approvePayment($paymentId);
            $_SESSION['admin_msg'] = ['type' => 'success', 'text' => 'Pembayaran disetujui dan langganan diaktifkan.'];
        } elseif ($action === 'reject') {
            $subscription->rejectPayment($paymentId);
            $_SESSION['admin_msg'] = ['type' => 'danger', 'text' => 'Pembayaran ditolak.'];
        }
    }
    Helper::redirect(APP_URL . '/admin/payments.php' . ($filterStatus ? '?status=' . $filterStatus : ''));
}

$payments = $subscription->getAllPaymentsAdmin($filterStatus ?: null);

$msg = $_SESSION['admin_msg'] ?? null;
unset($_SESSION['admin_msg']);

$pageTitle = 'Admin - Verifikasi Pembayaran';
?>
<?php include '../layout/header.php'; ?>
    <?php include '../layout/navbar.php'; ?>

    <div class="container-fluid mt-4 px-3 px-md-4" style="max-width:1100px;margin-left:auto;margin-right:auto;">
        <div class="page-header">
            <h1><i class="fas fa-shield-alt me-2" style="color:var(--primary)"></i>Verifikasi Pembayaran</h1>
        </div>

        <?php if ($msg): ?>
        <div class="alert alert-<?php echo $msg['type']; ?> alert-dismissible fade show mb-4">
            <i class="fas fa-<?php echo $msg['type'] === 'success' ? 'check-circle' : 'times-circle'; ?> me-2"></i>
            <?php echo $msg['text']; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>

        <!-- Filter tabs -->
        <ul class="nav nav-tabs mb-4">
            <li class="nav-item">
                <a class="nav-link <?php echo !$filterStatus ? 'active' : ''; ?>" href="payments.php">Semua</a>
            </li>
            <li class="nav-item">
                <a class="nav-link <?php echo $filterStatus === 'reviewing' ? 'active' : ''; ?>" href="?status=reviewing">
                    Menunggu Verifikasi
                    <?php
                    $reviewCount = count(array_filter($payments ?? [], fn($p) => $p['status'] === 'reviewing'));
                    if (!$filterStatus && $reviewCount > 0): ?>
                    <span class="badge ms-1" style="background:var(--primary)"><?php echo $reviewCount; ?></span>
                    <?php endif; ?>
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link <?php echo $filterStatus === 'pending' ? 'active' : ''; ?>" href="?status=pending">Menunggu Bayar</a>
            </li>
            <li class="nav-item">
                <a class="nav-link <?php echo $filterStatus === 'paid' ? 'active' : ''; ?>" href="?status=paid">Lunas</a>
            </li>
        </ul>

        <div class="card">
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0 table-mobile-card">
                        <thead>
                            <tr>
                                <th>Invoice</th>
                                <th>User</th>
                                <th>Paket</th>
                                <th>Jumlah</th>
                                <th>Tanggal</th>
                                <th>Status</th>
                                <th>Bukti</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($payments)): ?>
                            <tr>
                                <td colspan="8" class="text-center py-5 text-muted">
                                    <i class="fas fa-inbox fa-2x mb-2 d-block"></i>Tidak ada data
                                </td>
                            </tr>
                            <?php endif; ?>
                            <?php foreach ($payments as $p): ?>
                            <tr class="<?php echo $p['status'] === 'reviewing' ? 'table-warning' : ''; ?>">
                                <td data-label="Invoice"><small class="font-monospace"><?php echo $p['invoice_number']; ?></small></td>
                                <td data-label="User">
                                    <strong><?php echo htmlspecialchars($p['user_name']); ?></strong><br>
                                    <small class="text-muted"><?php echo htmlspecialchars($p['user_email']); ?></small>
                                </td>
                                <td data-label="Paket" class="text-uppercase fw-600"><?php echo $p['plan_type']; ?></td>
                                <td data-label="Jumlah" style="font-weight:700;color:var(--primary)"><?php echo Helper::formatCurrency($p['amount']); ?></td>
                                <td data-label="Tanggal"><small><?php echo Helper::formatDate($p['created_at']); ?></small></td>
                                <td data-label="Status"><?php echo Helper::getStatusBadge($p['status']); ?></td>
                                <td data-label="Bukti">
                                    <?php if ($p['payment_proof']): ?>
                                    <?php
                                        $proofUrl = APP_URL . '/uploads/payment_proof/' . htmlspecialchars($p['payment_proof']);
                                        $isPdf    = strtolower(pathinfo($p['payment_proof'], PATHINFO_EXTENSION)) === 'pdf';
                                    ?>
                                    <button type="button" class="btn btn-sm btn-outline-primary"
                                            onclick="showProof('<?php echo $proofUrl; ?>', <?php echo $isPdf ? 'true' : 'false'; ?>)">
                                        <i class="fas fa-<?php echo $isPdf ? 'file-pdf' : 'image'; ?>"></i> Lihat
                                    </button>
                                    <?php else: ?>
                                    <span class="text-muted">—</span>
                                    <?php endif; ?>
                                </td>
                                <td data-label="Aksi">
                                    <?php if ($p['status'] === 'reviewing'): ?>
                                    <div class="d-flex gap-2 flex-wrap">
                                        <form method="POST" class="d-inline"
                                              onsubmit="return confirm('Setujui pembayaran ini?')">
                                            <input type="hidden" name="payment_id" value="<?php echo $p['id']; ?>">
                                            <input type="hidden" name="action" value="approve">
                                            <button class="btn btn-sm btn-success">
                                                <i class="fas fa-check"></i> Setujui
                                            </button>
                                        </form>
                                        <form method="POST" class="d-inline"
                                              onsubmit="return confirm('Tolak pembayaran ini?')">
                                            <input type="hidden" name="payment_id" value="<?php echo $p['id']; ?>">
                                            <input type="hidden" name="action" value="reject">
                                            <button class="btn btn-sm btn-danger">
                                                <i class="fas fa-times"></i> Tolak
                                            </button>
                                        </form>
                                    </div>
                                    <?php else: ?>
                                    <span class="text-muted">—</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal Bukti Transfer -->
    <div class="modal fade" id="proofModal" tabindex="-1">
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <div class="modal-content" style="border-radius:var(--radius);border:none">
                <div class="modal-header" style="border-bottom:1px solid var(--border)">
                    <h5 class="modal-title fw-bold"><i class="fas fa-image me-2" style="color:var(--primary)"></i>Bukti Transfer</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body text-center p-2" id="proofModalBody"></div>
                <div class="modal-footer" style="border-top:1px solid var(--border)">
                    <a id="proofDownloadLink" href="#" target="_blank" class="btn btn-outline-primary btn-sm">
                        <i class="fas fa-external-link-alt me-1"></i> Buka di Tab Baru
                    </a>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
                </div>
            </div>
        </div>
    </div>

    <?php include '../layout/footer.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function showProof(url, isPdf) {
            const body = document.getElementById('proofModalBody');
            document.getElementById('proofDownloadLink').href = url;

            if (isPdf) {
                body.innerHTML = '<iframe src="' + url + '" width="100%" height="500px" style="border:none;"></iframe>';
            } else {
                body.innerHTML = '<img src="' + url + '" class="img-fluid rounded" style="max-height:70vh;" '
                               + 'onerror="this.outerHTML=\'<div class=alert alert-danger>Gagal memuat gambar</div>\'">';
            }

            new bootstrap.Modal(document.getElementById('proofModal')).show();
        }

        document.getElementById('proofModal').addEventListener('hidden.bs.modal', function () {
            document.getElementById('proofModalBody').innerHTML = '';
        });
    </script>
</body>
</html>
