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

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

<!-- Tailwind CSS Utility Engine -->
<script src="https://cdn.tailwindcss.com"></script>
<script>
  tailwind.config = {
    darkMode: 'class',
    theme: {
      extend: {
        colors: {
          slate: { 950: '#0b1329' }
        }
      }
    }
  }
</script>

<!-- Bootstrap 5 CSS for grid architecture -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Google Fonts & FontAwesome Icons -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

<style>
    body {
        font-family: 'Inter', sans-serif !important;
        background-color: #f8fafc;
        transition: background-color 0.3s ease, color 0.3s ease;
    }

    /* Premium card properties */
    .payment-card {
        background: #ffffff;
        border: 1px solid rgba(226, 232, 240, 0.8);
        border-radius: 1.25rem;
        transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1);
    }
    .payment-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 10px 18px -4px rgba(0, 0, 0, 0.04);
    }

    /* Glow Badges for Fintech Vibe */
    .badge-verified-glow {
        background-color: rgba(16, 185, 129, 0.1);
        color: #10b981;
        border: 1px solid rgba(16, 185, 129, 0.2);
    }
    .badge-pending-glow {
        background-color: rgba(245, 158, 11, 0.1);
        color: #f59e0b;
        border: 1px solid rgba(245, 158, 11, 0.2);
    }

    /* Scrollbars customizing */
    ::-webkit-scrollbar { width: 6px; height: 6px; }
    ::-webkit-scrollbar-track { background: #f1f5f9; }
    ::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 4px; }

    /* Dark Mode Core Overrides */
    html.dark body {
        background-color: #0b1329 !important;
        color: #f8fafc !important;
    }
    html.dark .card,
    html.dark .payment-card,
    html.dark .table-container {
        background-color: #1e293b !important;
        border-color: #334155 !important;
        color: #f1f5f9 !important;
    }
    html.dark .text-slate-900, html.dark h1, html.dark h2, html.dark h3, html.dark h4, html.dark h5 {
        color: #f8fafc !important;
    }
    html.dark .text-slate-500, html.dark .text-muted {
        color: #94a3b8 !important;
    }
    html.dark .bg-white {
        background-color: #1e293b !important;
    }
    html.dark .border, html.dark .border-bottom {
        border-color: #334155 !important;
    }
    html.dark .bg-slate-50 {
        background-color: #111a2e !important;
    }
    html.dark .table-hover tbody tr:hover {
        background-color: #111b30 !important;
    }
    html.dark .badge-verified-glow {
        background-color: rgba(16, 185, 129, 0.2);
        color: #34d399;
    }
    html.dark .badge-pending-glow {
        background-color: rgba(245, 158, 11, 0.2);
        color: #fbbf24;
    }
</style>

<div class="container-fluid py-4 px-3 sm:px-4 lg:px-6">

    <!-- Header & Action Deck -->
    <div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6 pb-6 border-b border-slate-200 dark:border-slate-700">
        <div>
            <div class="flex items-center gap-2 mb-2">
                <span class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold bg-emerald-50 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400 border border-emerald-200 dark:border-emerald-800/50 shadow-sm">
                    <span class="w-2 h-2 rounded-full bg-emerald-600 animate-pulse"></span>
                    Audit Arus Kas Masuk
                </span>
            </div>
            <h1 class="text-2xl sm:text-3xl font-extrabold text-slate-900 tracking-tight flex items-center gap-2">
                <i class="fas fa-hand-holding-dollar text-emerald-600 dark:text-emerald-400"></i>
                <?= esc($title ?? 'Daftar Pembayaran') ?>
            </h1>
            <p class="text-sm text-slate-500 mt-1">Pantau pembayaran masuk, status verifikasi bank transfer, serta pencocokan kasir secara transparan.</p>
        </div>

        <!-- Utility Action Buttons -->
        <div class="flex flex-wrap items-center gap-2 w-full md:w-auto justify-end">
            <!-- Theme Changer Button -->
            <button type="button" onclick="toggleDarkMode()" class="bg-white dark:bg-slate-800 hover:bg-slate-50 dark:hover:bg-slate-700 text-slate-700 dark:text-slate-200 border border-slate-200 dark:border-slate-600 rounded-xl p-2.5 shadow-sm transition-all flex items-center justify-center" title="Ubah Tema Gelap/Terang">
                <i id="themeIcon" class="fas fa-moon text-lg"></i>
            </button>
            <!-- Excel Export Button -->
            <button onclick="exportPaymentsExcel()" class="bg-emerald-600 hover:bg-emerald-700 text-white font-semibold text-sm rounded-xl px-4 py-2.5 shadow-sm transition-all flex items-center gap-2 border-0">
                <i class="fas fa-file-excel"></i>
                <span>Ekspor Excel</span>
            </button>
        </div>
    </div>

    <!-- Mini Metric Cards Dashboard -->
    <div class="row g-4 mb-6">
        <!-- Metric: Total Pembayaran Terverifikasi (Kas Masuk Bersih) -->
        <div class="col-12 col-md-4">
            <div class="payment-card p-4 flex items-center gap-4 bg-white">
                <div class="w-12 h-12 bg-emerald-50 dark:bg-emerald-950/30 text-emerald-600 dark:text-emerald-400 rounded-xl flex items-center justify-center text-xl">
                    <i class="fas fa-money-bill-trend-up"></i>
                </div>
                <div>
                    <span class="text-xs font-semibold text-slate-400 uppercase tracking-wider block">Total Kas Terverifikasi</span>
                    <h3 id="statTotalVerified" class="text-xl font-extrabold text-emerald-600 mb-0">Rp 0</h3>
                </div>
            </div>
        </div>

        <!-- Metric: Total Piutang / Pending Transfer -->
        <div class="col-12 col-md-4">
            <div class="payment-card p-4 flex items-center gap-4 bg-white">
                <div class="w-12 h-12 bg-amber-50 dark:bg-amber-950/30 text-amber-600 dark:text-amber-400 rounded-xl flex items-center justify-center text-xl">
                    <i class="fas fa-clock-rotate-left"></i>
                </div>
                <div>
                    <span class="text-xs font-semibold text-slate-400 uppercase tracking-wider block">Menunggu Verifikasi (Pending)</span>
                    <h3 id="statTotalPending" class="text-xl font-extrabold text-amber-500 mb-0">Rp 0</h3>
                </div>
            </div>
        </div>

        <!-- Metric: Frekuensi Transaksi -->
        <div class="col-12 col-md-4">
            <div class="payment-card p-4 flex items-center gap-4 bg-white">
                <div class="w-12 h-12 bg-indigo-50 dark:bg-indigo-950/30 text-indigo-600 dark:text-indigo-400 rounded-xl flex items-center justify-center text-xl">
                    <i class="fas fa-receipt"></i>
                </div>
                <div>
                    <span class="text-xs font-semibold text-slate-400 uppercase tracking-wider block">Frekuensi Pembayaran</span>
                    <h3 id="statTotalTransactions" class="text-xl font-extrabold text-slate-900 mb-0">0</h3>
                </div>
            </div>
        </div>
    </div>

    <!-- Core Database Catalog Table Section -->
    <div class="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 shadow-sm overflow-hidden mb-6">
        
        <!-- Search & Control Header -->
        <div class="p-4 border-b border-slate-100 dark:border-slate-700 flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 bg-slate-50/50 dark:bg-slate-900/30">
            <div>
                <h4 class="text-base font-bold text-slate-900 dark:text-slate-100 flex items-center gap-2">
                    <i class="fas fa-list-check text-slate-500"></i>
                    Rincian Pembayaran Masuk
                </h4>
                <p class="text-xs text-slate-500 mt-0.5">Disinkronkan secara aman untuk memverifikasi keabsahan dana pelanggan.</p>
            </div>
            <!-- Live Client-side Searching -->
            <div class="relative w-full sm:w-80">
                <span class="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
                    <i class="fas fa-magnifying-glass text-slate-400 text-sm"></i>
                </span>
                <input type="text" id="paymentSearch" onkeyup="filterPaymentTable()" placeholder="Cari nama, no order, metode bayar..." class="w-full pl-9 pr-4 py-2 text-xs bg-white dark:bg-slate-900 dark:text-slate-100 border border-slate-200 dark:border-slate-700 rounded-xl focus:outline-none focus:ring-2 focus:ring-emerald-500 transition-all shadow-xs">
            </div>
        </div>

        <!-- Master Responsive Table -->
        <div class="table-responsive">
            <table class="w-full text-left border-collapse" id="paymentsTable">
                <thead>
                    <tr class="bg-slate-50 dark:bg-slate-900/50 text-slate-500 dark:text-slate-400 font-bold text-xs uppercase tracking-wider border-b border-slate-200 dark:border-slate-700">
                        <th class="py-3.5 px-4 text-center" width="60">No</th>
                        <th class="py-3.5 px-4" width="180">Tanggal Bayar</th>
                        <th class="py-3.5 px-4" width="150">No Order</th>
                        <th class="py-3.5 px-4">Nama Pelanggan (Customer)</th>
                        <th class="py-3.5 px-4" width="180">Metode Bayar</th>
                        <th class="py-3.5 px-4 text-right" width="180">Jumlah Bayar</th>
                        <th class="py-3.5 px-4 text-center" width="160">Status Verifikasi</th>
                    </tr>
                </thead>
                <tbody class="text-xs text-slate-600 dark:text-slate-300 divide-y divide-slate-100 dark:divide-slate-700">
                    <?php $no = 1; ?>
                    <?php if(empty($payments)): ?>
                        <!-- Table Empty Fallback -->
                        <tr>
                            <td colspan="7" class="py-12 text-center">
                                <div class="flex flex-col items-center justify-center text-slate-400">
                                    <i class="fas fa-receipt text-4xl mb-3 opacity-30"></i>
                                    <span class="text-sm font-semibold">Tidak Ada Data Transaksi</span>
                                    <p class="text-xs text-slate-400 mt-1">Belum ada catatan pembayaran yang terekam pada server database saat ini.</p>
                                </div>
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach($payments as $p): ?>
                            <?php 
                                $statusRaw = strtolower($p['status'] ?? 'pending');
                                $jumlah_bayar = floatval($p['jumlah_bayar'] ?? 0);
                            ?>
                            <tr class="hover:bg-slate-50/50 dark:hover:bg-slate-900/10 transition-all payment-row-element"
                                data-customer="<?= esc(strtolower($p['customer_name'] ?? '')) ?>"
                                data-order="<?= esc(strtolower($p['order_number'] ?? '')) ?>"
                                data-method="<?= esc(strtolower($p['nama_metode'] ?? 'N/A')) ?>"
                                data-status="<?= $statusRaw ?>"
                                data-amount="<?= $jumlah_bayar ?>">
                                
                                <!-- No. -->
                                <td class="py-3.5 px-4 text-center font-semibold text-slate-400"><?= $no++ ?></td>
                                
                                <!-- Tanggal Bayar -->
                                <td class="py-3.5 px-4 font-medium text-slate-700 dark:text-slate-300">
                                    <?= !empty($p['tanggal_bayar']) ? esc(date('d M Y H:i', strtotime($p['tanggal_bayar']))) : '-' ?>
                                </td>

                                <!-- No Order -->
                                <td class="py-3.5 px-4">
                                    <span class="inline-flex items-center px-2 py-1 rounded bg-slate-100 dark:bg-slate-700 text-slate-600 dark:text-slate-300 font-mono font-bold text-[10px]">
                                        <i class="fas fa-hashtag me-1 opacity-55"></i><?= esc($p['order_number'] ?? '-') ?>
                                    </span>
                                </td>

                                <!-- Nama Pelanggan -->
                                <td class="py-3.5 px-4 font-bold text-slate-800 dark:text-slate-200">
                                    <?= esc($p['customer_name'] ?? 'Pelanggan Anonim') ?>
                                </td>

                                <!-- Metode Pembayaran -->
                                <td class="py-3.5 px-4 font-semibold text-slate-700 dark:text-slate-300">
                                    <span class="flex items-center gap-1.5">
                                        <i class="fas fa-credit-card text-slate-400"></i>
                                        <?= esc($p['nama_metode'] ?? 'Transfer Bank') ?>
                                    </span>
                                </td>

                                <!-- Jumlah Bayar -->
                                <td class="py-3.5 px-4 text-right font-extrabold text-slate-900 dark:text-slate-100 text-sm">
                                    Rp <?= number_format($jumlah_bayar, 0, ',', '.') ?>
                                </td>

                                <!-- Status -->
                                <td class="py-3.5 px-4 text-center">
                                    <?php if($statusRaw == 'verified'): ?>
                                        <span class="inline-flex items-center gap-1 px-3 py-1 rounded-full text-[10px] font-bold badge-verified-glow">
                                            <span class="w-1.5 h-1.5 rounded-full bg-emerald-500"></span>
                                            Terverifikasi
                                        </span>
                                    <?php else: ?>
                                        <span class="inline-flex items-center gap-1 px-3 py-1 rounded-full text-[10px] font-bold badge-pending-glow">
                                            <span class="w-1.5 h-1.5 rounded-full bg-amber-500 animate-pulse"></span>
                                            Pending
                                        </span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- SheetJS Library for Dynamic Pure XLSX Output -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>

<script>
document.addEventListener("DOMContentLoaded", function() {

    // ==========================================
    // INVENTARIS INTELLIGENT METRICS ENGINE
    // ==========================================
    function calculatePaymentTelemetry() {
        const rows = document.querySelectorAll('.payment-row-element');
        let totalVerified = 0;
        let totalPending = 0;
        let transactionCount = rows.length;

        rows.forEach(row => {
            const status = row.getAttribute('data-status') || 'pending';
            const amount = parseFloat(row.getAttribute('data-amount')) || 0;

            if (status === 'verified') {
                totalVerified += amount;
            } else {
                totalPending += amount;
            }
        });

        const formatRupiah = (val) => {
            return new Intl.NumberFormat('id-ID', {
                style: 'currency',
                currency: 'IDR',
                maximumFractionDigits: 0
            }).format(val);
        };

        // Render metrics to UI
        document.getElementById('statTotalVerified').innerText = formatRupiah(totalVerified);
        document.getElementById('statTotalPending').innerText = formatRupiah(totalPending);
        document.getElementById('statTotalTransactions').innerText = transactionCount;
    }
    
    // Run telemetry initially
    calculatePaymentTelemetry();

    // ==========================================
    // CLIENT SEARCH FILTER ENGINE
    // ==========================================
    window.filterPaymentTable = function() {
        const query = document.getElementById('paymentSearch').value.toLowerCase().trim();
        const rows = document.querySelectorAll('.payment-row-element');

        rows.forEach(row => {
            const customer = row.getAttribute('data-customer') || '';
            const order = row.getAttribute('data-order') || '';
            const method = row.getAttribute('data-method') || '';

            const matchesQuery = customer.includes(query) || 
                                 order.includes(query) || 
                                 method.includes(query);

            if (matchesQuery) {
                row.style.display = "";
            } else {
                row.style.display = "none";
            }
        });
    };

    // ==========================================
    // EXPORT PAYMENT TO EXCEL (SheetJS)
    // ==========================================
    window.exportPaymentsExcel = function() {
        const rows = document.querySelectorAll('.payment-row-element');
        const exportData = [
            ["LAPORAN AUDIT TRANSAKSI PEMBAYARAN MASUK"],
            ["Modul Keuangan & Kontrol Kasir Owner"],
            ["Waktu Ekspor Laporan", new Date().toLocaleString('id-ID')],
            [],
            ["NO", "TANGGAL BAYAR", "NOMOR ORDER", "CUSTOMER (PELANGGAN)", "METODE PEMBAYARAN", "JUMLAH BAYAR (IDR)", "STATUS VERIFIKASI"]
        ];

        let itemCounter = 1;
        rows.forEach(row => {
            const tanggal = row.querySelector('td:nth-child(2)').innerText.trim();
            const orderNo = row.getAttribute('data-order').toUpperCase();
            const customer = row.querySelector('td:nth-child(4)').innerText.trim();
            const metode = row.querySelector('td:nth-child(5)').innerText.trim();
            const jumlah = parseFloat(row.getAttribute('data-amount')) || 0;
            const status = row.getAttribute('data-status') === 'verified' ? "Terverifikasi" : "Pending";

            exportData.push([
                itemCounter++,
                tanggal,
                orderNo || "-",
                customer,
                metode,
                jumlah,
                status
            ]);
        });

        // Initialize Worksheet & Workbook structure
        const wb = XLSX.utils.book_new();
        const ws = XLSX.utils.aoa_to_sheet(exportData);

        // Styling Columns size
        ws['!cols'] = [
            { wch: 5 },  // No
            { wch: 22 }, // Tanggal
            { wch: 15 }, // Order No
            { wch: 30 }, // Customer
            { wch: 20 }, // Metode
            { wch: 20 }, // Jumlah Bayar
            { wch: 16 }  // Status
        ];

        XLSX.utils.book_append_sheet(wb, ws, "Rekap Pembayaran");
        XLSX.writeFile(wb, "Laporan_Pembayaran_Masuk_Owner.xlsx");
    };

    // ==========================================
    // SYSTEM DARK MODE CONTROLLER
    // ==========================================
    window.toggleDarkMode = function() {
        const html = document.documentElement;
        const icon = document.getElementById('themeIcon');
        
        if (html.classList.contains('dark')) {
            html.classList.remove('dark');
            localStorage.setItem('theme', 'light');
            icon.className = "fas fa-moon text-lg";
        } else {
            html.classList.add('dark');
            localStorage.setItem('theme', 'dark');
            icon.className = "fas fa-sun text-lg text-amber-400";
        }
    };

    // Sync theme options on page load
    if (localStorage.getItem('theme') === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
        document.documentElement.classList.add('dark');
        document.getElementById('themeIcon').className = "fas fa-sun text-lg text-amber-400";
    }
});
</script>

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