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

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

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

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<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 Fintech Telemetry Cards */
    .metric-card-premium {
        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);
        position: relative;
        overflow: hidden;
    }
    .metric-card-premium::before {
        content: '';
        position: absolute;
        top: 0; left: 0; width: 5px; height: 100%;
    }
    .metric-blue::before { background: linear-gradient(to bottom, #3b82f6, #1d4ed8); }
    .metric-emerald::before { background: linear-gradient(to bottom, #10b981, #047857); }
    .metric-amber::before { background: linear-gradient(to bottom, #f59e0b, #d97706); }
    .metric-rose::before { background: linear-gradient(to bottom, #ef4444, #dc2626); }

    .metric-card-premium:hover {
        transform: translateY(-3px);
        box-shadow: 0 12px 20px -5px rgba(0, 0, 0, 0.04);
    }

    /* Interactive Report Deck Cards */
    .report-deck-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);
        cursor: pointer;
        text-decoration: none !important;
    }
    .report-deck-card:hover {
        transform: translateY(-4px);
        border-color: rgba(99, 102, 241, 0.4);
        box-shadow: 0 15px 30px -10px rgba(99, 102, 241, 0.12);
    }
    .report-deck-card:hover .arrow-icon {
        transform: translateX(4px);
    }

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

    /* Dark Mode Core Theme Overrides */
    html.dark body {
        background-color: #0b1329 !important;
        color: #f8fafc !important;
    }
    html.dark .metric-card-premium,
    html.dark .report-deck-card,
    html.dark .menu-header-box,
    html.dark .tab-content-container,
    html.dark .interactive-tab-btn {
        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, html.dark .text-slate-400 {
        color: #94a3b8 !important;
    }
    html.dark .bg-slate-50, html.dark .bg-slate-100 {
        background-color: #111a2e !important;
    }
    html.dark .border-slate-100, html.dark .border-slate-200 {
        border-color: #334155 !important;
    }
    html.dark .table-hover tbody tr:hover {
        background-color: #1e293b/50 !important;
    }
</style>

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

    <!-- Header Section with Responsive Control 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-indigo-50 text-indigo-700 dark:bg-indigo-950/30 dark:text-indigo-400 border border-indigo-200 dark:border-indigo-800/50 shadow-sm">
                    <span class="w-2 h-2 rounded-full bg-indigo-600 animate-pulse"></span>
                    Konsol Eksekutif & Analitik Bisnis Bengkel CNC
                </span>
                <span id="liveClock" class="text-xs text-slate-500 dark:text-slate-400 font-medium hidden sm:inline">
                    <i class="far fa-clock mr-1"></i> Memuat waktu...
                </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-chart-line text-indigo-600 dark:text-indigo-400"></i>
                Pusat Laporan Terpadu
            </h1>
            <p class="text-sm text-slate-500 mt-1">Pantau performa komprehensif, logistik produksi, arus kas masuk/keluar, upah SDM, serta pengawasan risiko piutang klien.</p>
        </div>

        <!-- Utility Theme Control Buttons -->
        <div class="flex items-center gap-2 w-full md:w-auto justify-end">
            <!-- Theme Changer Switch 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>
            <!-- Direct Excel Trigger -->
            <button type="button" onclick="startPremiumMultiSheetExport()" class="bg-emerald-600 hover:bg-emerald-700 text-white font-semibold text-sm rounded-xl px-4 py-2.5 shadow-md hover:shadow-lg transition-all flex items-center gap-2 border-0">
                <i class="fas fa-file-excel"></i>
                <span>Ekspor Semua (XLSX)</span>
            </button>
        </div>
    </div>

    <!-- Dashboard Telemetry Grid -->
    <div class="row g-4 mb-6">
        <!-- Metric Box: Total Order -->
        <div class="col-12 col-sm-6 col-lg-3">
            <div class="metric-card-premium metric-blue p-4 flex items-center gap-4 bg-white shadow-xs">
                <div class="w-12 h-12 bg-blue-50 dark:bg-blue-950/30 text-blue-600 dark:text-blue-400 rounded-xl flex items-center justify-center text-xl">
                    <i class="fas fa-shopping-basket"></i>
                </div>
                <div>
                    <span class="text-xs font-bold text-slate-400 uppercase tracking-wider block">Total Transaksi Order</span>
                    <h3 class="text-2xl font-extrabold text-slate-900 mb-0" id="metricOrderValue"><?= esc($order ?? 0) ?></h3>
                </div>
            </div>
        </div>

        <!-- Metric Box: Total Customer -->
        <div class="col-12 col-sm-6 col-lg-3">
            <div class="metric-card-premium metric-emerald p-4 flex items-center gap-4 bg-white shadow-xs">
                <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-users"></i>
                </div>
                <div>
                    <span class="text-xs font-bold text-slate-400 uppercase tracking-wider block">Pelanggan Terdaftar</span>
                    <h3 class="text-2xl font-extrabold text-slate-900 mb-0" id="metricCustomerValue"><?= esc($customer ?? 0) ?></h3>
                </div>
            </div>
        </div>

        <!-- Metric Box: Total Produk -->
        <div class="col-12 col-sm-6 col-lg-3">
            <div class="metric-card-premium metric-amber p-4 flex items-center gap-4 bg-white shadow-xs">
                <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-cubes"></i>
                </div>
                <div>
                    <span class="text-xs font-bold text-slate-400 uppercase tracking-wider block">Katalog Produk Aktif</span>
                    <h3 class="text-2xl font-extrabold text-slate-900 mb-0" id="metricProductValue"><?= esc($product ?? 0) ?></h3>
                </div>
            </div>
        </div>

        <!-- Metric Box: Belanja Material -->
        <div class="col-12 col-sm-6 col-lg-3">
            <div class="metric-card-premium metric-rose p-4 flex items-center gap-4 bg-white shadow-xs">
                <div class="w-12 h-12 bg-rose-50 dark:bg-rose-950/30 text-rose-600 dark:text-rose-400 rounded-xl flex items-center justify-center text-xl">
                    <i class="fas fa-truck-ramp-box"></i>
                </div>
                <div class="min-w-0">
                    <span class="text-xs font-bold text-slate-400 uppercase tracking-wider block">Beban Belanja Logam</span>
                    <h3 class="text-lg font-extrabold text-rose-600 truncate mb-0" id="metricMaterialValue" title="Rp <?= number_format($material['total_biaya'] ?? 0, 0, ',', '.') ?>">
                        Rp <?= number_format($material['total_biaya'] ?? 0, 0, ',', '.') ?>
                    </h3>
                </div>
            </div>
        </div>
    </div>

    <!-- Interactive Report Deck Hub (Menu Laporan) -->
    <div class="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 shadow-sm overflow-hidden mb-6">
        
        <!-- Deck Header Context -->
        <div class="p-4 border-b border-slate-100 dark:border-slate-700 menu-header-box flex justify-between items-center 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-indigo-500"></i>
                    Navigasi Katalog Jurnal & Laporan Detail
                </h4>
                <p class="text-xs text-slate-500 mt-0.5">Pilih modul di bawah ini untuk melihat audit terperinci atau menyaring rekaman transaksi secara penuh.</p>
            </div>
        </div>

        <!-- Grid Cards Selection Deck -->
        <div class="p-4 sm:p-5">
            <div class="row g-4">
                
                <!-- Card Option: Laporan Penjualan -->
                <div class="col-12 col-md-6 col-lg-4">
                    <a href="<?= base_url('owner/report/sales') ?>" class="report-deck-card p-4 flex flex-col justify-between h-full bg-white">
                        <div>
                            <div class="flex justify-between items-start mb-3">
                                <div class="w-10 h-10 bg-blue-50 dark:bg-blue-950/30 text-blue-600 dark:text-blue-400 rounded-xl flex items-center justify-center text-lg">
                                    <i class="fas fa-shopping-cart"></i>
                                </div>
                                <i class="fas fa-chevron-right text-slate-300 arrow-icon transition-transform"></i>
                            </div>
                            <h4 class="text-sm font-bold text-slate-900 mb-1">Laporan Penjualan</h4>
                            <p class="text-[11px] text-slate-400 leading-relaxed mb-0">Tinjau akumulasi grafik omzet kotor, performa proyek terlaris, serta invoice lunas.</p>
                        </div>
                    </a>
                </div>

                <!-- Card Option: Laporan Material -->
                <div class="col-12 col-md-6 col-lg-4">
                    <a href="<?= base_url('owner/report/material') ?>" class="report-deck-card p-4 flex flex-col justify-between h-full bg-white">
                        <div>
                            <div class="flex justify-between items-start mb-3">
                                <div class="w-10 h-10 bg-emerald-50 dark:bg-emerald-950/30 text-emerald-600 dark:text-emerald-400 rounded-xl flex items-center justify-center text-lg">
                                    <i class="fas fa-truck-loading"></i>
                                </div>
                                <i class="fas fa-chevron-right text-slate-300 arrow-icon transition-transform"></i>
                            </div>
                            <h4 class="text-sm font-bold text-slate-900 mb-1">Laporan Belanja Material</h4>
                            <p class="text-[11px] text-slate-400 leading-relaxed mb-0">Pantau restok bahan baku logam CNC, vendor pemasok, serta HPP produksi proyek.</p>
                        </div>
                    </a>
                </div>

                <!-- Card Option: Laporan Penggajian -->
                <div class="col-12 col-md-6 col-lg-4">
                    <a href="<?= base_url('owner/report/payroll') ?>" class="report-deck-card p-4 flex flex-col justify-between h-full bg-white">
                        <div>
                            <div class="flex justify-between items-start mb-3">
                                <div class="w-10 h-10 bg-amber-50 dark:bg-amber-950/30 text-amber-600 dark:text-amber-400 rounded-xl flex items-center justify-center text-lg">
                                    <i class="fas fa-money-check"></i>
                                </div>
                                <i class="fas fa-chevron-right text-slate-300 arrow-icon transition-transform"></i>
                            </div>
                            <h4 class="text-sm font-bold text-slate-900 mb-1">Laporan Penggajian Pegawai</h4>
                            <p class="text-[11px] text-slate-400 leading-relaxed mb-0">Audit rincian upah pokok karyawan, alokasi bonus CNC, serta sanksi potongan kasir.</p>
                        </div>
                    </a>
                </div>

                <!-- Card Option: Cash Flow -->
                <div class="col-12 col-md-6 col-lg-4">
                    <a href="<?= base_url('owner/report/cashflow') ?>" class="report-deck-card p-4 flex flex-col justify-between h-full bg-white">
                        <div>
                            <div class="flex justify-between items-start mb-3">
                                <div class="w-10 h-10 bg-teal-50 dark:bg-teal-950/30 text-teal-600 dark:text-teal-400 rounded-xl flex items-center justify-center text-lg">
                                    <i class="fas fa-wallet"></i>
                                </div>
                                <i class="fas fa-chevron-right text-slate-300 arrow-icon transition-transform"></i>
                            </div>
                            <h4 class="text-sm font-bold text-slate-900 mb-1">Arus Kas (Cash Flow)</h4>
                            <p class="text-[11px] text-slate-400 leading-relaxed mb-0">Rekonsiliasi transaksi kas masuk dibanding kas keluar untuk mengukur laba bersih operasional.</p>
                        </div>
                    </a>
                </div>

                <!-- Card Option: Piutang -->
                <div class="col-12 col-md-6 col-lg-4">
                    <a href="<?= base_url('owner/report/receivable') ?>" class="report-deck-card p-4 flex flex-col justify-between h-full bg-white">
                        <div>
                            <div class="flex justify-between items-start mb-3">
                                <div class="w-10 h-10 bg-rose-50 dark:bg-rose-950/30 text-rose-600 dark:text-rose-400 rounded-xl flex items-center justify-center text-lg">
                                    <i class="fas fa-file-invoice-dollar"></i>
                                </div>
                                <i class="fas fa-chevron-right text-slate-300 arrow-icon transition-transform"></i>
                            </div>
                            <h4 class="text-sm font-bold text-slate-900 mb-1">Catatan Piutang Klien</h4>
                            <p class="text-[11px] text-slate-400 leading-relaxed mb-0">Pantau sisa invoice outstanding dari klien yang belum terverifikasi lunas.</p>
                        </div>
                    </a>
                </div>

                <!-- Card Option: Export Excel Direct Trigger -->
                <div class="col-12 col-md-6 col-lg-4">
                    <div onclick="startPremiumMultiSheetExport()" class="report-deck-card p-4 flex flex-col justify-between h-full bg-indigo-50/10 hover:bg-emerald-50/10 border-indigo-200/50 dark:border-indigo-900/40">
                        <div>
                            <div class="flex justify-between items-start mb-3">
                                <div class="w-10 h-10 bg-emerald-50 dark:bg-emerald-950/30 text-emerald-600 dark:text-emerald-400 rounded-xl flex items-center justify-center text-lg">
                                    <i class="fas fa-file-excel animate-bounce"></i>
                                </div>
                                <i class="fas fa-download text-slate-300 arrow-icon transition-transform"></i>
                            </div>
                            <h4 class="text-sm font-bold text-emerald-700 dark:text-emerald-400 mb-1">Ekspor Excel Cepat</h4>
                            <p class="text-[11px] text-slate-400 leading-relaxed mb-0">Unduh seluruh ringkasan data finansial multi-sheet instan untuk keperluan perpajakan.</p>
                        </div>
                    </div>
                </div>

            </div>
        </div>
    </div>

    <!-- Rangkuman Data Terpadu Section (Live Recaps Tab) -->
    <div class="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 shadow-sm overflow-hidden mb-6 tab-content-container">
        <div class="p-4 border-b border-slate-100 dark:border-slate-700 flex flex-col lg:flex-row justify-between items-start lg: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-database text-indigo-500"></i>
                    Rangkuman Mutasi & Audit Terkini
                </h4>
                <p class="text-xs text-slate-500 mt-0.5">Peninjauan langsung data rekap operasional bengkel tanpa harus meninggalkan halaman utama.</p>
            </div>
            
            <!-- Tab Controls -->
            <div class="flex flex-wrap gap-1 bg-slate-100 dark:bg-slate-900 p-1 rounded-xl">
                <button onclick="switchTab('tab-sales')" id="btn-tab-sales" class="interactive-tab-btn px-3 py-1.5 rounded-lg text-xs font-semibold bg-white dark:bg-slate-800 text-indigo-600 shadow-sm transition-all border-0">
                    <i class="fas fa-shopping-cart mr-1"></i> Penjualan
                </button>
                <button onclick="switchTab('tab-materials')" id="btn-tab-materials" class="interactive-tab-btn px-3 py-1.5 rounded-lg text-xs font-semibold text-slate-600 dark:text-slate-400 transition-all border-0">
                    <i class="fas fa-truck mr-1"></i> Belanja Material
                </button>
                <button onclick="switchTab('tab-cashflow')" id="btn-tab-cashflow" class="interactive-tab-btn px-3 py-1.5 rounded-lg text-xs font-semibold text-slate-600 dark:text-slate-400 transition-all border-0">
                    <i class="fas fa-wallet mr-1"></i> Jurnal Kas
                </button>
                <button onclick="switchTab('tab-receivables')" id="btn-tab-receivables" class="interactive-tab-btn px-3 py-1.5 rounded-lg text-xs font-semibold text-slate-600 dark:text-slate-400 transition-all border-0">
                    <i class="fas fa-file-invoice-dollar mr-1"></i> Piutang Klien
                </button>
                <button onclick="switchTab('tab-payroll')" id="btn-tab-payroll" class="interactive-tab-btn px-3 py-1.5 rounded-lg text-xs font-semibold text-slate-600 dark:text-slate-400 transition-all border-0">
                    <i class="fas fa-money-check mr-1"></i> Payroll Gaji
                </button>
            </div>
        </div>

        <!-- Tab 1: Sales Summary Table -->
        <div id="tab-sales" class="tab-pane-element">
            <div class="table-responsive">
                <table class="w-full text-left border-collapse">
                    <thead>
                        <tr class="bg-slate-50 dark:bg-slate-900/50 text-slate-500 dark:text-slate-400 font-bold text-xs uppercase border-b border-slate-200 dark:border-slate-700">
                            <th class="py-3 px-4" width="180">No. Invoice</th>
                            <th class="py-3 px-4">Tanggal Order</th>
                            <th class="py-3 px-4">Nama Pelanggan</th>
                            <th class="py-3 px-4 text-right" width="180">Total Transaksi</th>
                            <th class="py-3 px-4 text-center" width="150">Status</th>
                        </tr>
                    </thead>
                    <tbody class="text-xs text-slate-600 dark:text-slate-300 divide-y divide-slate-100 dark:divide-slate-700">
                        <?php if(!empty($salesList)): ?>
                            <?php foreach($salesList as $s): ?>
                                <tr class="hover:bg-slate-50/50 dark:hover:bg-slate-900/10 transition-all">
                                    <td class="py-3 px-4 font-mono font-bold text-indigo-600 dark:text-indigo-400"><?= esc($s['invoice']) ?></td>
                                    <td class="py-3 px-4"><?= date('d M Y H:i', strtotime($s['created_at'])) ?></td>
                                    <td class="py-3 px-4 font-semibold"><?= esc($s['customer_name'] ?? 'Pelanggan Umum') ?></td>
                                    <td class="py-3 px-4 text-right font-extrabold text-slate-900 dark:text-slate-100">Rp <?= number_format($s['total'], 0, ',', '.') ?></td>
                                    <td class="py-3 px-4 text-center">
                                        <span class="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[10px] font-bold <?= strtolower($s['status']) === 'completed' || strtolower($s['status']) === 'lunas' ? 'bg-emerald-50 text-emerald-700 dark:bg-emerald-950/20 dark:text-emerald-400' : 'bg-amber-50 text-amber-700 dark:bg-amber-950/20 dark:text-amber-400' ?>">
                                            <?= ucfirst($s['status']) ?>
                                        </span>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="5" class="py-8 text-center text-slate-400 italic">Tidak ada rekaman penjualan tersedia.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Tab 2: Materials Summary Table -->
        <div id="tab-materials" class="tab-pane-element hidden">
            <div class="table-responsive">
                <table class="w-full text-left border-collapse">
                    <thead>
                        <tr class="bg-slate-50 dark:bg-slate-900/50 text-slate-500 dark:text-slate-400 font-bold text-xs uppercase border-b border-slate-200 dark:border-slate-700">
                            <th class="py-3 px-4" width="150">Tanggal Beli</th>
                            <th class="py-3 px-4">Supplier / Vendor</th>
                            <th class="py-3 px-4">Nama Material Logam</th>
                            <th class="py-3 px-4 text-center" width="100">Qty</th>
                            <th class="py-3 px-4 text-right" width="180">Harga Satuan</th>
                            <th class="py-3 px-4 text-right" width="180">Total Beban</th>
                        </tr>
                    </thead>
                    <tbody class="text-xs text-slate-600 dark:text-slate-300 divide-y divide-slate-100 dark:divide-slate-700">
                        <?php if(!empty($materialsList)): ?>
                            <?php foreach($materialsList as $m): ?>
                                <tr class="hover:bg-slate-50/50 dark:hover:bg-slate-900/10 transition-all">
                                    <td class="py-3 px-4"><?= date('d M Y', strtotime($m['tanggal_beli'])) ?></td>
                                    <td class="py-3 px-4 font-semibold text-slate-700 dark:text-slate-400"><?= esc($m['nama_supplier'] ?? 'Toko Logam Lokal') ?></td>
                                    <td class="py-3 px-4 font-bold text-slate-800 dark:text-slate-200"><?= esc($m['nama_product'] ?? 'Material Mesin CNC') ?></td>
                                    <td class="py-3 px-4 text-center"><?= number_format($m['qty'], 2) ?></td>
                                    <td class="py-3 px-4 text-right">Rp <?= number_format($m['harga_beli'], 0, ',', '.') ?></td>
                                    <td class="py-3 px-4 text-right font-extrabold text-rose-600">Rp <?= number_format($m['qty'] * $m['harga_beli'], 0, ',', '.') ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="6" class="py-8 text-center text-slate-400 italic">Tidak ada rekaman pembelian material logam tersedia.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Tab 3: Cashflow Summary Table -->
        <div id="tab-cashflow" class="tab-pane-element hidden">
            <div class="table-responsive">
                <table class="w-full text-left border-collapse">
                    <thead>
                        <tr class="bg-slate-50 dark:bg-slate-900/50 text-slate-500 dark:text-slate-400 font-bold text-xs uppercase border-b border-slate-200 dark:border-slate-700">
                            <th class="py-3 px-4" width="180">Tanggal Transaksi</th>
                            <th class="py-3 px-4" width="180">Kategori Kas</th>
                            <th class="py-3 px-4">Deskripsi Rekonsiliasi</th>
                            <th class="py-3 px-4 text-right" width="160">Debit (Masuk)</th>
                            <th class="py-3 px-4 text-right" width="160">Kredit (Keluar)</th>
                        </tr>
                    </thead>
                    <tbody class="text-xs text-slate-600 dark:text-slate-300 divide-y divide-slate-100 dark:divide-slate-700">
                        <?php if(!empty($cashflowList)): ?>
                            <?php foreach($cashflowList as $c): ?>
                                <tr class="hover:bg-slate-50/50 dark:hover:bg-slate-900/10 transition-all">
                                    <td class="py-3 px-4"><?= date('d M Y H:i', strtotime($c['tanggal'])) ?></td>
                                    <td class="py-3 px-4">
                                        <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-bold <?= strpos(strtolower($c['kategori']), 'debit') !== false ? 'bg-emerald-50 text-emerald-700 dark:bg-emerald-950/20 dark:text-emerald-400' : 'bg-rose-50 text-rose-700 dark:bg-rose-950/20 dark:text-rose-400' ?>">
                                            <?= esc($c['kategori']) ?>
                                        </span>
                                    </td>
                                    <td class="py-3 px-4 font-semibold text-slate-700 dark:text-slate-300"><?= esc($c['deskripsi']) ?></td>
                                    <td class="py-3 px-4 text-right text-emerald-600 font-bold"><?= $c['debit'] > 0 ? 'Rp '.number_format($c['debit'], 0, ',', '.') : '-' ?></td>
                                    <td class="py-3 px-4 text-right text-rose-600 font-bold"><?= $c['kredit'] > 0 ? 'Rp '.number_format($c['kredit'], 0, ',', '.') : '-' ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="5" class="py-8 text-center text-slate-400 italic">Tidak ada aliran mutasi arus kas terekam.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Tab 4: Receivables Summary Table -->
        <div id="tab-receivables" class="tab-pane-element hidden">
            <div class="table-responsive">
                <table class="w-full text-left border-collapse">
                    <thead>
                        <tr class="bg-slate-50 dark:bg-slate-900/50 text-slate-500 dark:text-slate-400 font-bold text-xs uppercase border-b border-slate-200 dark:border-slate-700">
                            <th class="py-3 px-4" width="180">Invoice Order</th>
                            <th class="py-3 px-4">Nama Pelanggan</th>
                            <th class="py-3 px-4">Tanggal Order</th>
                            <th class="py-3 px-4 text-right" width="180">Total Tagihan</th>
                            <th class="py-3 px-4 text-right" width="180">Sisa Piutang</th>
                            <th class="py-3 px-4 text-center" width="160">Skor Risiko</th>
                        </tr>
                    </thead>
                    <tbody class="text-xs text-slate-600 dark:text-slate-300 divide-y divide-slate-100 dark:divide-slate-700">
                        <?php if(!empty($receivableList)): ?>
                            <?php foreach($receivableList as $r): ?>
                                <tr class="hover:bg-slate-50/50 dark:hover:bg-slate-900/10 transition-all">
                                    <td class="py-3 px-4 font-mono font-bold text-indigo-600 dark:text-indigo-400"><?= esc($r['invoice']) ?></td>
                                    <td class="py-3 px-4 font-semibold"><?= esc($r['customer'] ?? 'Pelanggan Umum') ?></td>
                                    <td class="py-3 px-4"><?= date('d M Y', strtotime($r['created_at'])) ?></td>
                                    <td class="py-3 px-4 text-right font-medium">Rp <?= number_format($r['total'], 0, ',', '.') ?></td>
                                    <td class="py-3 px-4 text-right font-extrabold text-rose-600">Rp <?= number_format($r['sisa_piutang'], 0, ',', '.') ?></td>
                                    <td class="py-3 px-4 text-center">
                                        <?php 
                                            $totalVal = floatval($r['total'] ?? 0);
                                            $remainingVal = floatval($r['sisa_piutang'] ?? 0);
                                            $isHighRisk = ($remainingVal > ($totalVal * 0.5));
                                        ?>
                                        <span class="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[10px] font-bold <?= $isHighRisk ? 'bg-rose-50 text-rose-700 dark:bg-rose-950/20 dark:text-rose-400 animate-pulse' : 'bg-amber-50 text-amber-700 dark:bg-amber-950/20 dark:text-amber-400' ?>">
                                            <?= $isHighRisk ? 'Risiko Tinggi (Follow Up)' : 'Risiko Sedang' ?>
                                        </span>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="6" class="py-8 text-center text-slate-400 italic">Buku piutang bersih. Semua sisa tagihan terbayar penuh.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Tab 5: Payroll Summary Table -->
        <div id="tab-payroll" class="tab-pane-element hidden">
            <div class="table-responsive">
                <table class="w-full text-left border-collapse">
                    <thead>
                        <tr class="bg-slate-50 dark:bg-slate-900/50 text-slate-500 dark:text-slate-400 font-bold text-xs uppercase border-b border-slate-200 dark:border-slate-700">
                            <th class="py-3 px-4" width="120">ID Pegawai</th>
                            <th class="py-3 px-4">Nama Lengkap</th>
                            <th class="py-3 px-4 text-center" width="100">Periode</th>
                            <th class="py-3 px-4 text-right" width="150">Gaji Pokok</th>
                            <th class="py-3 px-4 text-right" width="130">Bonus CNC</th>
                            <th class="py-3 px-4 text-right" width="130">Potongan</th>
                            <th class="py-3 px-4 text-right" width="180">Total Upah Bersih</th>
                            <th class="py-3 px-4 text-center" width="130">Status</th>
                        </tr>
                    </thead>
                    <tbody class="text-xs text-slate-600 dark:text-slate-300 divide-y divide-slate-100 dark:divide-slate-700">
                        <?php if(!empty($payrollList)): ?>
                            <?php foreach($payrollList as $p): ?>
                                <tr class="hover:bg-slate-50/50 dark:hover:bg-slate-900/10 transition-all">
                                    <td class="py-3 px-4 font-mono font-semibold text-slate-400">#<?= esc($p['id_pegawai']) ?></td>
                                    <td class="py-3 px-4 font-bold text-slate-800 dark:text-slate-200"><?= esc($p['nama_lengkap'] ?? 'Pegawai') ?></td>
                                    <td class="py-3 px-4 text-center font-medium"><?= esc($p['periode']) ?></td>
                                    <td class="py-3 px-4 text-right">Rp <?= number_format($p['gaji_pokok'], 0, ',', '.') ?></td>
                                    <td class="py-3 px-4 text-right text-emerald-600">+Rp <?= number_format($p['bonus'], 0, ',', '.') ?></td>
                                    <td class="py-3 px-4 text-right text-rose-500">-Rp <?= number_format($p['potongan'], 0, ',', '.') ?></td>
                                    <td class="py-3 px-4 text-right font-extrabold text-slate-900 dark:text-slate-100">Rp <?= number_format($p['total_gaji'], 0, ',', '.') ?></td>
                                    <td class="py-3 px-4 text-center">
                                        <span class="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[10px] font-bold <?= strtolower($p['status']) === 'paid' ? 'bg-emerald-50 text-emerald-700 dark:bg-emerald-950/20 dark:text-emerald-400' : 'bg-amber-50 text-amber-700 dark:bg-amber-950/20 dark:text-amber-400' ?>">
                                            <?= ucfirst($p['status']) ?>
                                        </span>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="8" class="py-8 text-center text-slate-400 italic">Tidak ada entri data penggajian karyawan bulan ini.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- PREMIUM EXPORT DATABASE PROGRESS MODAL -->
<div id="exportProgressModal" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/60 backdrop-blur-xs hidden opacity-0 transition-all duration-300">
    <div class="bg-white dark:bg-slate-800 rounded-2xl max-w-md w-full overflow-hidden shadow-2xl transform scale-95 transition-transform duration-300 border border-slate-200 dark:border-slate-700">
        <div class="h-1.5 bg-emerald-500 w-full animate-pulse"></div>
        <div class="p-6">
            <div class="w-12 h-12 rounded-full bg-emerald-50 dark:bg-emerald-950/30 text-emerald-600 dark:text-emerald-400 flex items-center justify-center text-xl mb-4">
                <i class="fas fa-cloud-arrow-down animate-bounce"></i>
            </div>
            <h3 class="text-lg font-bold text-slate-900 dark:text-slate-100 mb-1">Mengekstrak Data Laporan</h3>
            <p class="text-xs text-slate-500 mb-4">Mohon tunggu sementara kami memproses seluruh data multi-sheet...</p>
            
            <!-- Progress Status indicators -->
            <div class="space-y-2 text-xs">
                <div class="flex justify-between items-center py-1.5 border-b border-slate-100 dark:border-slate-800">
                    <span class="text-slate-400 flex items-center gap-2">
                        <i id="statusIconSummary" class="fas fa-circle-notch text-slate-300"></i> Ringkasan Eksekutif KPI
                    </span>
                    <strong id="statusTextSummary" class="text-slate-500">Antre...</strong>
                </div>
                <div class="flex justify-between items-center py-1.5 border-b border-slate-100 dark:border-slate-800">
                    <span class="text-slate-400 flex items-center gap-2">
                        <i id="statusIconSales" class="fas fa-circle-notch text-slate-300"></i> Laporan Penjualan (Sales)
                    </span>
                    <strong id="statusTextSales" class="text-slate-500">Antre...</strong>
                </div>
                <div class="flex justify-between items-center py-1.5 border-b border-slate-100 dark:border-slate-800">
                    <span class="text-slate-400 flex items-center gap-2">
                        <i id="statusIconMaterials" class="fas fa-circle-notch text-slate-300"></i> Belanja Material & Logistik
                    </span>
                    <strong id="statusTextMaterials" class="text-slate-500">Antre...</strong>
                </div>
                <div class="flex justify-between items-center py-1.5 border-b border-slate-100 dark:border-slate-800">
                    <span class="text-slate-400 flex items-center gap-2">
                        <i id="statusIconPayroll" class="fas fa-circle-notch text-slate-300"></i> Slip Gaji & Payroll Pegawai
                    </span>
                    <strong id="statusTextPayroll" class="text-slate-500">Antre...</strong>
                </div>
                <div class="flex justify-between items-center py-1.5 border-b border-slate-100 dark:border-slate-800">
                    <span class="text-slate-400 flex items-center gap-2">
                        <i id="statusIconCashflow" class="fas fa-circle-notch text-slate-300"></i> Rekap Arus Kas (Cash Flow)
                    </span>
                    <strong id="statusTextCashflow" class="text-slate-500">Antre...</strong>
                </div>
                <div class="flex justify-between items-center py-1.5">
                    <span class="text-slate-400 flex items-center gap-2">
                        <i id="statusIconReceivable" class="fas fa-circle-notch text-slate-300"></i> Buku Piutang Outstanding
                    </span>
                    <strong id="statusTextReceivable" class="text-slate-500">Antre...</strong>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- SheetJS Library for advanced multi-sheet xlsx output -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>

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

    // ==========================================
    // DYNAMIC SYSTEM CLOCK ENGINE
    // ==========================================
    function updateLiveClock() {
        const options = { 
            weekday: 'long', 
            year: 'numeric', 
            month: 'long', 
            day: 'numeric', 
            hour: '2-digit', 
            minute: '2-digit',
            second: '2-digit'
        };
        const clockElement = document.getElementById('liveClock');
        if (clockElement) {
            clockElement.innerHTML = `<i class="far fa-clock mr-1"></i> ` + new Date().toLocaleDateString('id-ID', options);
        }
    }
    setInterval(updateLiveClock, 1000);
    updateLiveClock();

    // ==========================================
    // INTERACTIVE LIVE RECAPPING TAB SELECTOR
    // ==========================================
    window.switchTab = function(activeTabId) {
        // Hide all tab panes
        document.querySelectorAll('.tab-pane-element').forEach(pane => {
            pane.classList.add('hidden');
        });

        // Show active tab
        document.getElementById(activeTabId).classList.remove('hidden');

        // Reset button classes to normal states
        document.querySelectorAll('.interactive-tab-btn').forEach(btn => {
            btn.className = "interactive-tab-btn px-3 py-1.5 rounded-lg text-xs font-semibold text-slate-600 dark:text-slate-400 transition-all border-0 bg-transparent";
        });

        // Add highlighted classes to active button
        const activeBtn = document.getElementById('btn-' + activeTabId);
        if (activeBtn) {
            activeBtn.className = "interactive-tab-btn px-3 py-1.5 rounded-lg text-xs font-semibold bg-white dark:bg-slate-800 text-indigo-600 dark:text-indigo-400 shadow-sm transition-all border-0";
        }
    };

    // ==========================================
    // PREMIUM DATABASE MULTI-SHEET EXPORTER ENGINE
    // ==========================================
    const progressModal = document.getElementById('exportProgressModal');

    function setStepStatus(stepId, state, detailText = '') {
        const icon = document.getElementById('statusIcon' + stepId);
        const text = document.getElementById('statusText' + stepId);
        
        if (!icon || !text) return;

        if (state === 'loading') {
            icon.className = "fas fa-circle-notch animate-spin text-indigo-500";
            text.className = "text-indigo-500 font-bold animate-pulse";
            text.innerText = detailText || "Memuat...";
        } else if (state === 'success') {
            icon.className = "fas fa-circle-check text-emerald-500 text-sm";
            text.className = "text-emerald-600 font-bold";
            text.innerText = detailText || "Selesai";
        } else if (state === 'error') {
            icon.className = "fas fa-circle-exclamation text-rose-500 text-sm";
            text.className = "text-rose-500 font-bold";
            text.innerText = detailText || "Gagal (Simulasi)";
        }
    }

    // Dynamic Fallback DOM Scraper
    function getScrapedSummaryData() {
        const totalOrderText = document.getElementById('metricOrderValue')?.innerText.trim() || '0';
        const totalCustomerText = document.getElementById('metricCustomerValue')?.innerText.trim() || '0';
        const totalProductText = document.getElementById('metricProductValue')?.innerText.trim() || '0';
        const totalMaterialText = document.getElementById('metricMaterialValue')?.innerText.replace(/[^\d]/g, '') || '0';

        return [
            ["DASHBOARD RINGKASAN EKSEKUTIF BENGKEL CNC (DATA SCRAPED FALLBACK)"],
            ["Sistem Laporan Keuangan Terpadu"],
            ["Tanggal Ekspor", new Date().toLocaleString('id-ID')],
            [],
            ["METRIK KUNCI OPERASIONAL", "NILAI REKAMAN", "DESKRIPSI"],
            ["Total Transaksi Order", parseInt(totalOrderText), "Jumlah pemesanan masuk terdaftar"],
            ["Pelanggan Terdaftar", parseInt(totalCustomerText), "Mitra dan klien terdaftar"],
            ["Katalog Produk Aktif", parseInt(totalProductText), "Jumlah varian model produk mesin"],
            ["Beban Belanja Material Logam", parseFloat(totalMaterialText), "Total pengeluaran HPP bahan baku logam"]
        ];
    }

    window.startPremiumMultiSheetExport = async function() {
        progressModal.classList.remove('hidden');
        setTimeout(() => {
            progressModal.classList.remove('opacity-0');
        }, 10);

        // Reset indicators
        ['Summary', 'Sales', 'Materials', 'Payroll', 'Cashflow', 'Receivable'].forEach(key => {
            const icon = document.getElementById('statusIcon' + key);
            const text = document.getElementById('statusText' + key);
            if (icon) icon.className = "fas fa-circle-notch text-slate-300";
            if (text) {
                text.innerText = "Antre...";
                text.className = "text-slate-500";
            }
        });

        // Initialize Workbook
        const wb = XLSX.utils.book_new();

        // 1. Fetch Summary Sheet
        setStepStatus('Summary', 'loading');
        let summaryData = [];
        try {
            const response = await fetch('<?= base_url("owner/report/api/summary") ?>');
            if (response.ok) {
                summaryData = await response.json();
                setStepStatus('Summary', 'success', "Selesai");
            } else { throw new Error(); }
        } catch(e) {
            summaryData = getScrapedSummaryData();
            setStepStatus('Summary', 'success', "Selesai (Scraped)");
        }

        // 2. Fetch Sales (Laporan Penjualan)
        setStepStatus('Sales', 'loading');
        let salesData = [];
        try {
            const response = await fetch('<?= base_url("owner/report/api/sales") ?>');
            if (response.ok) {
                salesData = await response.json();
                setStepStatus('Sales', 'success', `${salesData.length} baris`);
            } else { throw new Error(); }
        } catch(e) {
            salesData = [
                ["No. Invoice", "Tanggal", "Nama Customer", "Nilai Transaksi (IDR)", "Status"],
                ["-", "-", "Koneksi database terputus / Data kosong", 0, "-"]
            ];
            setStepStatus('Sales', 'success', "Selesai (Database Kosong)");
        }

        // 3. Fetch Materials (Laporan Belanja)
        setStepStatus('Materials', 'loading');
        let materialData = [];
        try {
            const response = await fetch('<?= base_url("owner/report/api/materials") ?>');
            if (response.ok) {
                materialData = await response.json();
                setStepStatus('Materials', 'success', `${materialData.length} baris`);
            } else { throw new Error(); }
        } catch(e) {
            materialData = [
                ["No", "Tanggal Beli", "Supplier/Vendor", "Nama Material", "Volume (Qty)", "Harga Satuan", "Total Beban (IDR)"],
                [1, "-", "Koneksi database terputus / Data kosong", "-", 0, 0, 0]
            ];
            setStepStatus('Materials', 'success', "Selesai (Database Kosong)");
        }

        // 4. Fetch Payroll (Laporan Gaji)
        setStepStatus('Payroll', 'loading');
        let payrollData = [];
        try {
            const response = await fetch('<?= base_url("owner/report/api/payroll") ?>');
            if (response.ok) {
                payrollData = await response.json();
                setStepStatus('Payroll', 'success', `${payrollData.length} baris`);
            } else { throw new Error(); }
        } catch(e) {
            payrollData = [
                ["ID Pegawai", "Nama Lengkap", "Periode", "Gaji Pokok", "Bonus Kinerja", "Potongan", "Total Upah Bersih (IDR)", "Status"],
                ["-", "Koneksi database terputus / Data kosong", "-", 0, 0, 0, 0, "-"]
            ];
            setStepStatus('Payroll', 'success', "Selesai (Database Kosong)");
        }

        // 5. Fetch Cash Flow (Arus Kas)
        setStepStatus('Cashflow', 'loading');
        let cashflowData = [];
        try {
            const response = await fetch('<?= base_url("owner/report/api/cashflow") ?>');
            if (response.ok) {
                cashflowData = await response.json();
                setStepStatus('Cashflow', 'success', `${cashflowData.length} baris`);
            } else { throw new Error(); }
        } catch(e) {
            cashflowData = [
                ["Tanggal", "Kategori Kas", "Deskripsi Transaksi", "Kas Masuk (Debit)", "Kas Keluar (Kredit)", "Saldo Buku (IDR)"],
                ["-", "-", "Koneksi database terputus / Data kosong", 0, 0, 0]
            ];
            setStepStatus('Cashflow', 'success', "Selesai (Database Kosong)");
        }

        // 6. Fetch Receivables (Piutang)
        setStepStatus('Receivable', 'loading');
        let receivableData = [];
        try {
            const response = await fetch('<?= base_url("owner/report/api/receivable") ?>');
            if (response.ok) {
                receivableData = await response.json();
                setStepStatus('Receivable', 'success', `${receivableData.length} baris`);
            } else { throw new Error(); }
        } catch(e) {
            receivableData = [
                ["No. Invoice", "Nama Pelanggan", "Tanggal Transaksi", "Nilai Invoice (IDR)", "Sisa Piutang (IDR)", "Status Risiko"],
                ["-", "Koneksi database terputus / Data kosong", "-", 0, 0, "-"]
            ];
            setStepStatus('Receivable', 'success', "Selesai (Database Kosong)");
        }

        const makeSheet = (header, data) => {
            const arrayData = Array.isArray(data[0]) ? data : [header, ...data.map(obj => Object.values(obj))];
            return XLSX.utils.aoa_to_sheet(arrayData);
        };

        const sheetSummary = makeSheet([], summaryData);
        sheetSummary['!cols'] = [
            { wch: 35 }, 
            { wch: 25 }, 
            { wch: 55 }
        ];

        XLSX.utils.book_append_sheet(wb, sheetSummary, "Ringkasan Eksekutif");
        XLSX.utils.book_append_sheet(wb, makeSheet(["No. Invoice", "Tanggal", "Nama Customer", "Nilai Transaksi (IDR)", "Status"], salesData), "Jurnal Penjualan");
        XLSX.utils.book_append_sheet(wb, makeSheet(["No", "Tanggal Beli", "Supplier/Vendor", "Nama Material", "Volume (Qty)", "Harga Satuan", "Total Belanja (IDR)"], materialData), "Belanja Material");
        XLSX.utils.book_append_sheet(wb, makeSheet(["ID Pegawai", "Nama Lengkap", "Periode", "Gaji Pokok", "Bonus Kinerja", "Potongan", "Total Upah Bersih (IDR)", "Status"], payrollData), "Gaji & Payroll");
        XLSX.utils.book_append_sheet(wb, makeSheet(["Tanggal", "Kategori Kas", "Deskripsi Transaksi", "Kas Masuk (Debit)", "Kas Keluar (Kredit)", "Saldo Buku (IDR)"], cashflowData), "Arus Kas");
        XLSX.utils.book_append_sheet(wb, makeSheet(["No. Invoice", "Nama Pelanggan", "Tanggal Transaksi", "Nilai Invoice (IDR)", "Sisa Piutang (IDR)", "Status Risiko"], receivableData), "Piutang Outstanding");

        XLSX.writeFile(wb, "Pusat_Laporan_Eksekutif_Bengkel_CNC.xlsx");

        setTimeout(() => {
            progressModal.classList.add('opacity-0');
            setTimeout(() => { progressModal.classList.add('hidden'); }, 300);
        }, 1000);
    };

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

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