<?= $this->extend('layouts/admin_layout') ?>

<?= $this->section('content') ?>

<style>
    /* ===== MODERN SAAS DESIGN SYSTEM TOKENS ===== */
    :root {
        --bg-body: #f8fafc;
        --bg-card: #ffffff;
        --bg-accent: #f1f5f9;
        --bg-input: #ffffff;
        --border-color: #e2e8f0;
        --border-hover: #cbd5e1;
        --text-main: #0f172a;
        --text-sub: #64748b;
        --primary: #4f46e5;
        --primary-hover: #4338ca;
        --primary-light: rgba(79, 70, 229, 0.08);
        --success: #10b981;
        --warning: #f59e0b;
        --danger: #ef4444;
        --info: #06b6d4;
        --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
        --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.07), 0 2px 4px -2px rgba(0, 0, 0, 0.05);
        --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.05);
        --radius-lg: 16px;
        --radius-md: 12px;
        --radius-sm: 8px;
        --transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
    }

    @media (prefers-color-scheme: dark) {
        :root {
            --bg-body: #0b0f19;
            --bg-card: #151e2e;
            --bg-accent: #1e293b;
            --bg-input: #0f172a;
            --border-color: #243044;
            --border-hover: #334155;
            --text-main: #f8fafc;
            --text-sub: #94a3b8;
            --primary-light: rgba(79, 70, 229, 0.18);
            --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.3);
            --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.4);
            --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.5);
        }
    }

    [data-bs-theme="dark"] {
        --bg-body: #0b0f19;
        --bg-card: #151e2e;
        --bg-accent: #1e293b;
        --bg-input: #0f172a;
        --border-color: #243044;
        --border-hover: #334155;
        --text-main: #f8fafc;
        --text-sub: #94a3b8;
        --primary-light: rgba(79, 70, 229, 0.18);
        --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.3);
        --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.4);
        --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.5);
    }

    body, .content-wrapper, .main-content, .content, .page-content, main, .payment-dashboard-workspace {
        background-color: var(--bg-body) !important;
        color: var(--text-main) !important;
        transition: var(--transition);
    }

    /* Card Premium Styling */
    .card-premium {
        background: var(--bg-card);
        border: 1px solid var(--border-color);
        border-radius: var(--radius-lg);
        box-shadow: var(--shadow-sm);
        transition: var(--transition);
    }

    /* Stat Cards Upgrade */
    .stat-card {
        background: var(--bg-card);
        border: 1px solid var(--border-color);
        border-radius: var(--radius-lg);
        padding: 1.25rem;
        transition: var(--transition);
        position: relative;
        overflow: hidden;
    }

    .stat-card:hover {
        transform: translateY(-4px);
        box-shadow: var(--shadow-lg);
        border-color: var(--border-hover);
    }

    .stat-card .stat-icon {
        width: 44px;
        height: 44px;
        border-radius: var(--radius-md);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.25rem;
    }

    /* Table Container & Aesthetics */
    .table-container {
        background: var(--bg-card);
        border: 1px solid var(--border-color);
        border-radius: var(--radius-lg);
        box-shadow: var(--shadow-md);
        overflow: hidden;
    }

    .custom-table {
        margin-bottom: 0;
        width: 100%;
        color: var(--text-main);
    }

    .custom-table thead {
        background: var(--bg-accent);
        border-bottom: 1px solid var(--border-color);
    }

    .custom-table thead th {
        font-size: 0.72rem;
        text-transform: uppercase;
        letter-spacing: 0.08em;
        font-weight: 700;
        color: var(--text-sub);
        padding: 0.85rem 1rem;
        border: none;
    }

    .custom-table tbody tr {
        border-bottom: 1px solid var(--border-color);
        transition: var(--transition);
    }

    .custom-table tbody tr:last-child {
        border-bottom: none;
    }

    .custom-table tbody tr:hover {
        background-color: var(--bg-accent) !important;
    }

    .custom-table td {
        padding: 0.9rem 1rem !important;
        vertical-align: middle;
    }

    /* Avatar Initial */
    .avatar-circle {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        background: var(--primary-light);
        color: var(--primary);
        font-weight: 700;
        font-size: 0.85rem;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
    }

    /* Action Buttons */
    .btn-action-group .btn {
        padding: 0.35rem 0.65rem;
        font-size: 0.8rem;
        border-radius: var(--radius-sm);
        transition: var(--transition);
    }

    /* Soft Badges Custom */
    .badge-soft-success { background: rgba(16, 185, 129, 0.12); color: #10b981; border: 1px solid rgba(16, 185, 129, 0.2); }
    .badge-soft-warning { background: rgba(245, 158, 11, 0.12); color: #f59e0b; border: 1px solid rgba(245, 158, 11, 0.2); }
    .badge-soft-danger  { background: rgba(239, 68, 68, 0.12); color: #ef4444; border: 1px solid rgba(239, 68, 68, 0.2); }
    .badge-soft-primary { background: rgba(79, 70, 229, 0.12); color: #4f46e5; border: 1px solid rgba(79, 70, 229, 0.2); }
    .badge-soft-secondary { background: rgba(100, 116, 139, 0.12); color: #64748b; border: 1px solid rgba(100, 116, 139, 0.2); }

    /* Form Controls Override */
    .form-control, .form-select {
        background-color: var(--bg-input) !important;
        border-color: var(--border-color) !important;
        color: var(--text-main) !important;
        font-size: 0.85rem;
    }

    .form-control:focus, .form-select:focus {
        border-color: var(--primary) !important;
        box-shadow: 0 0 0 3px var(--primary-light) !important;
    }

    /* Pagination Styling */
    .pagination .page-link {
        border: 1px solid var(--border-color) !important;
        border-radius: var(--radius-sm) !important;
        margin: 0 2px;
        color: var(--text-sub);
        background: var(--bg-card);
        font-size: 0.8rem;
        font-weight: 500;
        padding: 0.4rem 0.75rem;
        transition: var(--transition);
    }

    .pagination .page-link:hover {
        background: var(--bg-accent);
        color: var(--primary);
    }

    .pagination .page-item.active .page-link {
        background: var(--primary) !important;
        color: #ffffff !important;
        border-color: var(--primary) !important;
        box-shadow: var(--shadow-sm);
    }

    .pagination .page-item.disabled .page-link {
        opacity: 0.5;
        background: var(--bg-card);
    }
</style>

<div class="container-fluid py-4 payment-dashboard-workspace">

    <?php 
        // Akumulasi Statistik
        $totalReceived = 0;
        $countVerified = 0;
        $countPending  = 0;
        $totalTx       = !empty($payments) && is_array($payments) ? count($payments) : 0;

        if (!empty($payments) && is_array($payments)) {
            foreach ($payments as $p) {
                $st = strtolower($p['status'] ?? '');
                if (in_array($st, ['verified', 'success', 'paid'])) {
                    $totalReceived += (float)($p['jumlah_bayar'] ?? 0);
                    $countVerified++;
                } elseif ($st === 'pending') {
                    $countPending++;
                }
            }
        }
    ?>

    <!-- PAGE HEADER -->
    <div class="d-flex flex-column flex-sm-row justify-content-between align-items-sm-center mb-4 gap-3">
        <div>
            <h3 class="fw-bold mb-0 text-main"><?= esc($title ?? 'Riwayat Pembayaran') ?></h3>
            <p class="text-sub small mb-0 mt-0.5">Daftar arus kas masuk, verifikasi transaksi, dan mutasi pembayaran kasir.</p>
        </div>
        <div>
            <a href="<?= base_url('admin/orders') ?>" class="btn btn-outline-secondary px-3.5 py-2 rounded-3 shadow-sm fw-semibold d-inline-flex align-items-center gap-2 fs-7">
                <i class="bi bi-box-seam"></i> Kelola Order
            </a>
        </div>
    </div>

    <!-- FLASH MESSAGES -->
    <?php if (session()->getFlashdata('success')): ?>
        <div class="alert alert-success alert-dismissible fade show rounded-3 shadow-sm border-0 mb-4" role="alert">
            <div class="d-flex align-items-center gap-2">
                <i class="bi bi-check-circle-fill fs-5"></i>
                <div><?= esc(session()->getFlashdata('success')) ?></div>
            </div>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <?php if (session()->getFlashdata('error')): ?>
        <div class="alert alert-danger alert-dismissible fade show rounded-3 shadow-sm border-0 mb-4" role="alert">
            <div class="d-flex align-items-center gap-2">
                <i class="bi bi-exclamation-triangle-fill fs-5"></i>
                <div><?= esc(session()->getFlashdata('error')) ?></div>
            </div>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <!-- STATISTIK RINGKASAN -->
    <div class="row g-3 mb-4">
        <!-- Total Masuk -->
        <div class="col-12 col-sm-6 col-xl-3">
            <div class="stat-card shadow-sm d-flex align-items-center justify-content-between">
                <div>
                    <div class="small fw-bold text-uppercase text-sub mb-1" style="font-size: 0.7rem; letter-spacing: 0.05em;">Total Dana Masuk</div>
                    <div class="h4 fw-bolder mb-0 text-success">Rp <?= number_format($totalReceived, 0, ',', '.') ?></div>
                </div>
                <div class="stat-icon bg-success-subtle text-success">
                    <i class="bi bi-wallet2"></i>
                </div>
            </div>
        </div>

        <!-- Total Transaksi -->
        <div class="col-12 col-sm-6 col-xl-3">
            <div class="stat-card shadow-sm d-flex align-items-center justify-content-between">
                <div>
                    <div class="small fw-bold text-uppercase text-sub mb-1" style="font-size: 0.7rem; letter-spacing: 0.05em;">Total Transaksi</div>
                    <div class="h4 fw-bolder mb-0 text-main"><?= number_format($totalTx) ?></div>
                </div>
                <div class="stat-icon bg-primary-subtle text-primary">
                    <i class="bi bi-receipt-cutoff"></i>
                </div>
            </div>
        </div>

        <!-- Terverifikasi -->
        <div class="col-12 col-sm-6 col-xl-3">
            <div class="stat-card shadow-sm d-flex align-items-center justify-content-between">
                <div>
                    <div class="small fw-bold text-uppercase text-sub mb-1" style="font-size: 0.7rem; letter-spacing: 0.05em;">Terverifikasi</div>
                    <div class="h4 fw-bolder mb-0 text-success"><?= number_format($countVerified) ?></div>
                </div>
                <div class="stat-icon bg-success-subtle text-success">
                    <i class="bi bi-check-all"></i>
                </div>
            </div>
        </div>

        <!-- Pending -->
        <div class="col-12 col-sm-6 col-xl-3">
            <div class="stat-card shadow-sm d-flex align-items-center justify-content-between">
                <div>
                    <div class="small fw-bold text-uppercase text-sub mb-1" style="font-size: 0.7rem; letter-spacing: 0.05em;">Pending Verifikasi</div>
                    <div class="h4 fw-bolder mb-0 text-warning"><?= number_format($countPending) ?></div>
                </div>
                <div class="stat-icon bg-warning-subtle text-warning">
                    <i class="bi bi-clock-history"></i>
                </div>
            </div>
        </div>
    </div>

    <!-- FILTER & TABLE AREA -->
    <div class="table-container p-3.5">
        
        <!-- Filter Action Bar -->
        <div class="row g-2 mb-3.5 align-items-center">
            <div class="col-12 col-md-6 col-lg-5">
                <div class="input-group">
                    <span class="input-group-text bg-transparent border-end-0 text-sub"><i class="bi bi-search"></i></span>
                    <input type="text" id="searchPayment" class="form-control border-start-0 ps-1 rounded-end-3" placeholder="Cari Order #, pelanggan, metode...">
                </div>
            </div>
            <div class="col-6 col-md-4 col-lg-3">
                <select id="filterStatus" class="form-select rounded-3">
                    <option value="">Semua Status</option>
                    <option value="verified">Verified / Success</option>
                    <option value="pending">Pending</option>
                    <option value="rejected">Rejected / Failed</option>
                </select>
            </div>
            <div class="col-6 col-md-2 col-lg-2 ms-auto text-end">
                <button type="button" class="btn btn-outline-secondary btn-sm rounded-3 py-2 px-3 w-100 text-nowrap" onclick="resetFilters()" title="Reset Filter">
                    <i class="bi bi-arrow-counterclockwise"></i> Reset
                </button>
            </div>
        </div>

        <!-- Table Stream -->
        <div class="table-responsive">
            <table class="table custom-table align-middle" id="paymentTable">
                <thead>
                    <tr>
                        <th class="ps-3" style="width: 60px;">#</th>
                        <th>Order #</th>
                        <th>Pelanggan</th>
                        <th>Metode</th>
                        <th>Jumlah Bayar</th>
                        <th>Tanggal Bayar</th>
                        <th>Status</th>
                        <th class="text-end pe-3">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(!empty($payments) && is_array($payments)): foreach($payments as $index => $payment): ?>
                        <?php 
                            $initial = strtoupper(substr(trim($payment['customer_name'] ?? 'C'), 0, 1));
                            $st = strtolower($payment['status'] ?? 'verified');
                            $badgeClass = in_array($st, ['verified', 'success', 'paid']) ? 'badge-soft-success' : ($st === 'pending' ? 'badge-soft-warning' : 'badge-soft-danger');
                        ?>
                        <tr class="payment-row">
                            <td class="ps-3 text-sub small fw-medium"><?= $index + 1 ?></td>
                            
                            <!-- Order Number -->
                            <td>
                                <a href="<?= base_url('admin/orders/show/' . $payment['id_order']) ?>" class="fw-bold text-primary text-decoration-none hover-underline">
                                    #<?= esc($payment['order_number']) ?>
                                </a>
                            </td>

                            <!-- Customer Info -->
                            <td>
                                <div class="d-flex align-items-center gap-2.5">
                                    <div class="avatar-circle"><?= $initial ?></div>
                                    <div class="fw-semibold text-main" style="font-size: 0.88rem;">
                                        <?= esc($payment['customer_name']) ?>
                                    </div>
                                </div>
                            </td>

                            <!-- Payment Method -->
                            <td>
                                <span class="badge badge-soft-secondary rounded-pill px-2.5 py-1">
                                    <i class="bi bi-credit-card me-1"></i><?= esc($payment['nama_metode'] ? $payment['nama_metode'] : 'Cash / Manual') ?>
                                </span>
                            </td>

                            <!-- Nominal -->
                            <td>
                                <div class="fw-bolder text-success" style="font-size: 0.88rem;">
                                    Rp <?= number_format((float)($payment['jumlah_bayar'] ?? 0), 0, ',', '.') ?>
                                </div>
                            </td>

                            <!-- Date & Time -->
                            <td>
                                <div class="small text-main font-monospace">
                                    <?= $payment['tanggal_bayar'] ? date('d M Y', strtotime($payment['tanggal_bayar'])) : '-' ?>
                                </div>
                                <div class="small text-sub opacity-75" style="font-size: 0.75rem;">
                                    <?= $payment['tanggal_bayar'] ? date('H:i T', strtotime($payment['tanggal_bayar'])) : '' ?>
                                </div>
                            </td>

                            <!-- Status -->
                            <td>
                                <span class="badge <?= $badgeClass ?> rounded-pill px-2.5 py-1">
                                    <?= esc(ucfirst($payment['status'] ?? 'Verified')) ?>
                                </span>
                            </td>

                            <!-- Action -->
                            <td class="text-end pe-3">
                                <div class="btn-group btn-action-group shadow-sm" role="group">
                                    <a href="<?= base_url('admin/orders/show/' . $payment['id_order']) ?>" class="btn btn-outline-secondary" title="Lihat Detail Order">
                                        <i class="bi bi-eye me-1"></i> Detail Order
                                    </a>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; else: ?>
                        <tr id="emptyRowStatic">
                            <td colspan="8" class="text-center py-5 text-sub">
                                <i class="bi bi-inbox fs-2 d-block opacity-40 mb-2"></i>
                                Belum ada riwayat transaksi pembayaran.
                            </td>
                        </tr>
                    <?php endif; ?>

                    <!-- Dynamic JS Empty Search State -->
                    <tr id="noMatchingDataRow" class="d-none">
                        <td colspan="8" class="text-center py-5 text-sub">
                            <i class="bi bi-search fs-2 d-block opacity-40 mb-2"></i>
                            <strong>Tidak ada pembayaran yang cocok.</strong>
                            <p class="small text-sub mb-0 mt-1">Coba sesuaikan kata kunci pencarian atau reset filter Anda.</p>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
        
        <!-- Table Footer Pagination -->
        <div class="p-3 border-top border-color d-flex flex-column flex-sm-row justify-content-between align-items-center gap-3">
            <div class="text-sub small" id="tableInfo">Menampilkan data pembayaran...</div>
            <nav aria-label="Payment pagination">
                <ul class="pagination pagination-sm mb-0" id="paginationControls"></ul>
            </nav>
        </div>
    </div>
</div>

<!-- JAVASCRIPT ENGINE FOR SEARCH & PAGINATION -->
<script>
    const rowsPerPage = 10;
    let currentPage = 1;
    
    const rows = Array.from(document.querySelectorAll('#paymentTable tbody tr.payment-row'));
    const searchInput = document.getElementById('searchPayment');
    const statusSelect = document.getElementById('filterStatus');
    const noMatchRow = document.getElementById('noMatchingDataRow');

    function renderTable(page = 1) {
        currentPage = page;
        const searchVal = searchInput.value.toLowerCase().trim();
        const statusVal = statusSelect.value.toLowerCase().trim();

        // Filtering logic
        const filteredRows = rows.filter(row => {
            const rowText = row.innerText.toLowerCase();
            const matchesSearch = searchVal === '' || rowText.includes(searchVal);
            
            // Cell index 6 corresponds to Status column
            const statusCellText = row.cells[6] ? row.cells[6].innerText.toLowerCase() : '';
            const matchesStatus = statusVal === '' || statusCellText.includes(statusVal);

            return matchesSearch && matchesStatus;
        });

        // Hide all data rows
        rows.forEach(r => r.style.display = 'none');

        // Toggle Empty Search Result
        if (filteredRows.length === 0 && rows.length > 0) {
            noMatchRow.classList.remove('d-none');
        } else {
            noMatchRow.classList.add('d-none');
        }

        // Calculate pagination slicing
        const totalItems = filteredRows.length;
        const totalPages = Math.ceil(totalItems / rowsPerPage) || 1;
        
        if (currentPage > totalPages) currentPage = totalPages;

        const startIdx = (currentPage - 1) * rowsPerPage;
        const endIdx = startIdx + rowsPerPage;

        filteredRows.slice(startIdx, endIdx).forEach(r => r.style.display = '');

        // Update Info Text
        const infoEl = document.getElementById('tableInfo');
        if (totalItems > 0) {
            const fromNum = startIdx + 1;
            const toNum = Math.min(endIdx, totalItems);
            infoEl.innerText = `Menampilkan ${fromNum} - ${toNum} dari ${totalItems} pembayaran`;
        } else {
            infoEl.innerText = 'Menampilkan 0 pembayaran';
        }

        // Render Pagination Control Buttons
        renderPagination(totalPages);
    }

    function renderPagination(totalPages) {
        const pagControls = document.getElementById('paginationControls');
        pagControls.innerHTML = '';

        if (totalPages <= 1) return;

        // Previous Button
        const prevLi = document.createElement('li');
        prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
        prevLi.innerHTML = `<button class="page-link" onclick="renderTable(${currentPage - 1})"><i class="bi bi-chevron-left"></i></button>`;
        pagControls.appendChild(prevLi);

        // Page Numbers
        for (let i = 1; i <= totalPages; i++) {
            const li = document.createElement('li');
            li.className = `page-item ${i === currentPage ? 'active' : ''}`;
            li.innerHTML = `<button class="page-link" onclick="renderTable(${i})">${i}</button>`;
            pagControls.appendChild(li);
        }

        // Next Button
        const nextLi = document.createElement('li');
        nextLi.className = `page-item ${currentPage === totalPages ? 'disabled' : ''}`;
        nextLi.innerHTML = `<button class="page-link" onclick="renderTable(${currentPage + 1})"><i class="bi bi-chevron-right"></i></button>`;
        pagControls.appendChild(nextLi);
    }

    function resetFilters() {
        searchInput.value = '';
        statusSelect.value = '';
        renderTable(1);
    }

    // Event Listeners
    [searchInput, statusSelect].forEach(el => {
        if (el) {
            el.addEventListener('input', () => renderTable(1));
            el.addEventListener('change', () => renderTable(1));
        }
    });

    // Run Initial Lifecycle
    window.addEventListener('DOMContentLoaded', () => {
        renderTable(1);
    });
</script>

<?= $this->endSection() ?>