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

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

<!-- Tailwind CSS Engine & Configuration for modern responsive utility design -->
<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 & dynamic layouts -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Google Fonts: Inter for sophisticated typography -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
<!-- FontAwesome 6 Icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

<style>
    /* Global design tokens aligned with Inter Font */
    body {
        font-family: 'Inter', sans-serif !important;
        background-color: #f8fafc;
        transition: background-color 0.3s ease, color 0.3s ease;
    }
    
    /* Elegant transition-based fintech card system */
    .card-fintech {
        background: #ffffff;
        border: 1px solid rgba(226, 232, 240, 0.8);
        border-radius: 1.25rem;
        transition: all 0.4s cubic-bezier(0.16, 1, 0.3, 1);
        position: relative;
        overflow: hidden;
    }
    
    .card-fintech::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 6px;
        height: 100%;
        border-radius: 4px 0 0 4px;
    }
    
    .card-fintech.border-primary-left::before { background: linear-gradient(to bottom, #3b82f6, #1d4ed8); }
    .card-fintech.border-success-left::before { background: linear-gradient(to bottom, #10b981, #047857); }
    .card-fintech.border-danger-left::before { background: linear-gradient(to bottom, #ef4444, #b91c1c); }
    
    .card-fintech:hover {
        transform: translateY(-5px);
        box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.05), 0 10px 10px -5px rgba(0, 0, 0, 0.02);
        border-color: rgba(59, 130, 246, 0.3);
    }

    /* Secondary Micro-Cards style */
    .card-sec-fin {
        border-radius: 1rem;
        border: 1px solid rgba(226, 232, 240, 0.8);
        background-color: #ffffff;
        transition: all 0.3s ease;
    }
    .card-sec-fin:hover {
        border-color: #cbd5e1;
        background-color: #f8fafc;
    }

    /* Icon box design */
    .icon-box-fin {
        width: 48px;
        height: 48px;
        border-radius: 1rem;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.25rem;
    }

    /* Premium Custom Badges styling */
    .finance-badge {
        font-size: 0.75rem;
        font-weight: 700;
        padding: 0.35rem 0.75rem;
        border-radius: 2rem;
        letter-spacing: 0.05em;
        text-transform: uppercase;
    }
    .badge-success-glow { background-color: rgba(16, 185, 129, 0.12); color: #10b981; }
    .badge-danger-glow { background-color: rgba(239, 68, 68, 0.12); color: #ef4444; }
    .badge-primary-glow { background-color: rgba(59, 130, 246, 0.12); color: #3b82f6; }

    /* Custom financial glowing metrics indicators */
    .glow-success { filter: drop-shadow(0 0 10px rgba(16, 185, 129, 0.15)); }
    .glow-danger { filter: drop-shadow(0 0 10px rgba(239, 68, 68, 0.15)); }
    .glow-primary { filter: drop-shadow(0 0 10px rgba(59, 130, 246, 0.15)); }

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

    /* --- DARK MODE EXPLICIT BOOTSTRAP OVERRIDES --- */
    html.dark body {
        background-color: #0b1329 !important;
        color: #f8fafc !important;
    }
    html.dark .card,
    html.dark .card-fintech,
    html.dark .card-sec-fin,
    html.dark .table-card {
        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, html.dark h6 {
        color: #f8fafc !important;
    }
    html.dark .text-muted,
    html.dark .text-slate-500,
    html.dark .text-slate-400 {
        color: #94a3b8 !important;
    }
    html.dark .bg-white {
        background-color: #1e293b !important;
    }
    html.dark .border,
    html.dark .border-bottom,
    html.dark .border-slate-100,
    html.dark .border-slate-200 {
        border-color: #334155 !important;
    }
    html.dark .bg-slate-50,
    html.dark .bg-slate-50\/50,
    html.dark tr.bg-slate-50 {
        background-color: #111a2e !important;
    }
    html.dark .btn-white {
        background-color: #1e293b !important;
        border-color: #475569 !important;
        color: #cbd5e1 !important;
    }
    html.dark .btn-white:hover {
        background-color: #334155 !important;
    }

    /* Print guidelines */
    @media print {
        .no-print { display: none !important; }
        .print-full-width { width: 100% !important; max-width: 100% !important; }
    }
</style>

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

    <!-- Top Navigation Deck & Live Command Header -->
    <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">
        <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-blue-50 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400 border border-blue-200 dark:border-blue-800/50 shadow-sm animate-pulse">
                    <span class="w-2 h-2 rounded-full bg-blue-600"></span>
                    Sistem Pemantauan Fiskal Real-time
                </span>
                <span id="liveClock" class="text-xs text-slate-500 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">Pusat Kendali & Analisis Keuangan</h1>
            <p class="text-sm text-slate-500 mt-1">Integrasi analitik profitabilitas operasional, alokasi pengeluaran, dan performa produksi CNC.</p>
        </div>

        <!-- Premium Navigation and Utilities -->
        <div class="flex flex-wrap items-center gap-2 no-print w-full md:w-auto">
            <!-- Functional Dark Mode Toggle -->
            <button onclick="toggleDarkMode()" class="btn-util 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="Toggle Tema Gelap/Terang">
                <i id="themeIcon" class="fas fa-moon text-lg"></i>
            </button>
            <!-- Excel Export Feature -->
            <button onclick="exportToExcel()" class="bg-emerald-600 hover:bg-emerald-700 text-white font-medium 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>
            <button onclick="window.print()" 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 font-medium text-sm rounded-xl px-4 py-2.5 shadow-sm transition-all flex items-center gap-2">
                <i class="fas fa-print text-slate-500 dark:text-slate-400"></i>
                <span>Cetak</span>
            </button>
            <button onclick="perbaruiData()" class="bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 text-white font-semibold text-sm rounded-xl px-4 py-2.5 shadow-sm hover:shadow transition-all flex items-center gap-2 border-0">
                <i class="fas fa-sync-alt"></i>
                <span>Perbarui Data</span>
            </button>
        </div>
    </div>

    <!-- Tiga Kartu Finansial Utama -->
    <div class="row g-4 mb-4">
        
        <!-- KARTU ONDEMAND: PENDAPATAN (OMZET) -->
        <div class="col-12 col-md-4">
            <div class="card-fintech border-success-left p-6 h-100 shadow-sm flex flex-col justify-between bg-white">
                <div>
                    <div class="flex justify-between items-start mb-4">
                        <div class="icon-box-fin bg-emerald-50 dark:bg-emerald-950/40 text-emerald-600 dark:text-emerald-400">
                            <i class="fas fa-file-invoice-dollar"></i>
                        </div>
                        <span class="finance-badge badge-success-glow">
                            <i class="fas fa-arrow-trend-up me-1"></i> Arus Masuk
                        </span>
                    </div>
                    <p class="text-xs font-bold text-slate-400 uppercase tracking-wider mb-1">Total Pendapatan (Omzet)</p>
                    <h2 class="text-2xl sm:text-3xl font-extrabold text-slate-900 tracking-tight mb-2 glow-success">
                        Rp <span class="php-val" id="valOmzet"><?= number_format($omzet, 0, ',', '.') ?></span>
                    </h2>
                </div>
                <div class="flex items-center gap-1.5 text-xs text-slate-500 mt-2">
                    <i class="fas fa-circle-check text-emerald-500"></i>
                    <span>Dana masuk dari order bulan berjalan, termasuk cicilan</span>
                </div>
            </div>
        </div>

        <!-- KARTU ONDEMAND: PENGELUARAN (BEBAN) -->
        <div class="col-12 col-md-4">
            <div class="card-fintech border-danger-left p-6 h-100 shadow-sm flex flex-col justify-between bg-white">
                <div>
                    <div class="flex justify-between items-start mb-4">
                        <div class="icon-box-fin bg-rose-50 dark:bg-rose-950/40 text-rose-600 dark:text-rose-400">
                            <i class="fas fa-wallet"></i>
                        </div>
                        <span class="finance-badge badge-danger-glow">
                            <i class="fas fa-arrow-trend-down me-1"></i> Pengeluaran
                        </span>
                    </div>
                    <p class="text-xs font-bold text-slate-400 uppercase tracking-wider mb-1">Total Pengeluaran (Beban)</p>
                    <h2 class="text-2xl sm:text-3xl font-extrabold text-slate-900 tracking-tight mb-2 glow-danger">
                        Rp <span class="php-val" id="valBeban"><?= number_format($beban, 0, ',', '.') ?></span>
                    </h2>
                </div>
                <div class="flex items-center gap-1.5 text-xs text-slate-500 mt-2">
                    <i class="fas fa-circle-notch text-rose-500"></i>
                    <span>Biaya Material, Payroll & Operasional CNC</span>
                </div>
            </div>
        </div>

        <!-- KARTU ONDEMAND: LABA / RUGI BERSIH -->
        <div class="col-12 col-md-4">
            <div class="card-fintech border-primary-left p-6 h-100 shadow-sm flex flex-col justify-between bg-white">
                <div>
                    <div class="flex justify-between items-start mb-4">
                        <div class="icon-box-fin bg-blue-50 dark:bg-blue-950/40 text-blue-600 dark:text-blue-400">
                            <i class="fas fa-coins"></i>
                        </div>
                        <span class="finance-badge badge-primary-glow">
                            <i class="fas fa-balance-scale"></i> Bersih
                        </span>
                    </div>
                    <p class="text-xs font-bold text-slate-400 uppercase tracking-wider mb-1">Laba / Rugi Bersih</p>
                    <h2 class="text-2xl sm:text-3xl font-extrabold text-slate-900 tracking-tight mb-3 glow-primary">
                        Rp <span class="php-val" id="valLaba"><?= number_format($laba, 0, ',', '.') ?></span>
                    </h2>
                </div>
                <!-- Status badge berdasarkan Laba (Dibuat adaptif via PHP & fallback JS) -->
                <div id="labaStatusBadge" class="mt-2">
                    <?php if(isset($laba) && $laba >= 0): ?>
                        <span class="inline-flex items-center gap-1 px-3 py-1 rounded-full text-xs font-semibold bg-emerald-100 text-emerald-800 dark:bg-emerald-900/30 dark:text-emerald-400 shadow-sm">
                            <i class="fas fa-circle-check"></i> SURPLUS (UNTUNG)
                        </span>
                    <?php else: ?>
                        <span class="inline-flex items-center gap-1 px-3 py-1 rounded-full text-xs font-semibold bg-rose-100 text-rose-800 dark:bg-rose-900/30 dark:text-rose-400 shadow-sm">
                            <i class="fas fa-triangle-exclamation"></i> DEFISIT (RUGI)
                        </span>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Ringkasan Pembayaran Order Admin -->
    <div class="row g-3 mb-4">
        <div class="col-12 col-md-4">
            <div class="card-sec-fin p-4 shadow-xs bg-white h-100">
                <div class="flex items-center gap-4">
                    <div class="p-3 bg-emerald-50 dark:bg-emerald-950/30 text-emerald-600 dark:text-emerald-400 rounded-xl">
                        <i class="fas fa-circle-check text-lg"></i>
                    </div>
                    <div class="min-w-0">
                        <span class="text-xs text-slate-400 font-medium block">Order Sudah Dibayar (Lunas)</span>
                        <span class="text-base font-extrabold text-emerald-600 truncate block">Rp <?= number_format($settledAmount ?? 0, 0, ',', '.') ?></span>
                        <span class="text-[11px] text-emerald-600 font-semibold"><?= number_format($paidOrders ?? 0) ?> faktur lunas</span>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-12 col-md-4">
            <div class="card-sec-fin p-4 shadow-xs bg-white h-100">
                <div class="flex items-center gap-4">
                    <div class="p-3 bg-rose-50 dark:bg-rose-950/30 text-rose-600 dark:text-rose-400 rounded-xl">
                        <i class="fas fa-file-circle-xmark text-lg"></i>
                    </div>
                    <div class="min-w-0">
                        <span class="text-xs text-slate-400 font-medium block">Order Belum Dibayar</span>
                        <span class="text-base font-extrabold text-rose-600 truncate block">Rp <?= number_format($unpaidAmount ?? 0, 0, ',', '.') ?></span>
                        <span class="text-[11px] text-rose-600 font-semibold"><?= number_format($unpaidOrders ?? 0) ?> faktur belum dibayar</span>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-12 col-md-4">
            <div class="card-sec-fin p-4 shadow-xs bg-white h-100">
                <div class="flex items-center gap-4">
                    <div class="p-3 bg-amber-50 dark:bg-amber-950/30 text-amber-600 dark:text-amber-400 rounded-xl">
                        <i class="fas fa-hourglass-half text-lg"></i>
                    </div>
                    <div class="min-w-0">
                        <span class="text-xs text-slate-400 font-medium block">Cicilan & Piutang Berjalan</span>
                        <span class="text-base font-extrabold text-amber-600 truncate block">Rp <?= number_format($outstandingAmount ?? 0, 0, ',', '.') ?></span>
                        <span class="text-[11px] text-amber-600 font-semibold"><?= number_format($partialOrders ?? 0) ?> cicilan · <?= number_format(($partialOrders ?? 0) + ($unpaidOrders ?? 0)) ?> belum lunas</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Statistik Tambahan (Sleek Micro Cards) -->
    <div class="row g-3 mb-4">
        
        <!-- Beban Belanja Material -->
        <div class="col-12 col-md-4">
            <div class="card-sec-fin p-4 shadow-xs bg-white">
                <div class="flex items-center gap-4">
                    <div class="p-3 bg-slate-50 dark:bg-slate-800 text-slate-600 dark:text-slate-300 rounded-xl">
                        <i class="fas fa-boxes-stacked text-lg"></i>
                    </div>
                    <div class="min-w-0">
                        <span class="text-xs text-slate-400 font-medium block">Beban Belanja Material</span>
                        <span class="text-base font-extrabold text-slate-800 dark:text-slate-200 truncate block">
                            Rp <span class="php-val" id="valMaterial"><?= number_format($material, 0, ',', '.') ?></span>
                        </span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Beban Gaji & Payroll -->
        <div class="col-12 col-md-4">
            <div class="card-sec-fin p-4 shadow-xs bg-white">
                <div class="flex items-center gap-4">
                    <div class="p-3 bg-slate-50 dark:bg-slate-800 text-slate-600 dark:text-slate-300 rounded-xl">
                        <i class="fas fa-users-gear text-lg"></i>
                    </div>
                    <div class="min-w-0">
                        <span class="text-xs text-slate-400 font-medium block">Beban Gaji & Payroll</span>
                        <span class="text-base font-extrabold text-slate-800 dark:text-slate-200 truncate block">
                            Rp <span class="php-val" id="valPayroll"><?= number_format($payroll, 0, ',', '.') ?></span>
                        </span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Outstanding Piutang Invoice -->
        <div class="col-12 col-md-4">
            <div class="card-sec-fin p-4 shadow-xs bg-white">
                <div class="flex items-center gap-4">
                    <div class="p-3 bg-slate-50 dark:bg-slate-800 text-slate-600 dark:text-slate-300 rounded-xl">
                        <i class="fas fa-hand-holding-dollar text-lg"></i>
                    </div>
                    <div class="min-w-0">
                        <span class="text-xs text-slate-400 font-medium block">Outstanding Piutang Invoice</span>
                        <span class="text-base font-extrabold text-slate-800 dark:text-slate-200 truncate block">
                            Rp <span class="php-val" id="valPiutang"><?= number_format($piutang, 0, ',', '.') ?></span>
                        </span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Dua Kolom Analisis Keuangan Utama -->
    <div class="row g-4 mb-4">
        
        <!-- Kolom Kiri: Visualisasi Chart Komparasi Alokasi -->
        <div class="col-12 col-lg-8">
            <div class="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 shadow-sm overflow-hidden flex flex-col h-100">
                <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-3 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-chart-bar text-blue-600 dark:text-blue-400"></i>
                            Komparasi Alokasi Finansial CNC
                        </h4>
                        <p class="text-xs text-slate-500 mt-0.5">Analisis proporsi omzet masuk terhadap beban belanja dan laba bersih.</p>
                    </div>
                    <div class="flex items-center gap-2">
                        <button onclick="switchChartType('bar')" id="btnBarChart" class="px-3 py-1.5 rounded-lg text-xs font-semibold bg-blue-600 text-white shadow-xs transition-all border-0">Bar</button>
                        <button onclick="switchChartType('doughnut')" id="btnDoughnutChart" class="px-3 py-1.5 rounded-lg text-xs font-semibold bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 text-slate-600 dark:text-slate-200 hover:bg-slate-50 shadow-xs transition-all">Doughnut</button>
                    </div>
                </div>
                <div class="p-6 flex-1 flex flex-col justify-center min-h-[360px]">
                    <div class="relative w-full h-[320px]">
                        <canvas id="financeChartComplex"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <!-- Kolom Kanan: Live Financial Simulator & Health Analyzer -->
        <div class="col-12 col-lg-4 flex flex-col gap-4">
            
            <!-- Widget Indikator Kesehatan Keuangan -->
            <div class="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 shadow-sm p-4 flex-1">
                <h4 class="text-sm font-bold text-slate-900 dark:text-slate-100 mb-3 flex items-center gap-1.5">
                    <i class="fas fa-heart-pulse text-emerald-500"></i>
                    Indikator Kesehatan Fiskal
                </h4>
                
                <div class="flex items-center gap-4">
                    <!-- Gauge Bulat Minimalis -->
                    <div class="relative flex items-center justify-center w-20 h-20">
                        <svg class="w-full h-full transform -rotate-90">
                            <circle cx="40" cy="40" r="34" stroke="#f1f5f9" class="dark:stroke-slate-700" stroke-width="6" fill="transparent" />
                            <circle id="healthScoreCircle" cx="40" cy="40" r="34" stroke="#10b981" stroke-width="6" fill="transparent" stroke-dasharray="213.6" stroke-dashoffset="100" class="transition-all duration-1000 ease-out" />
                        </svg>
                        <span id="healthPercentageText" class="absolute text-sm font-extrabold text-slate-800 dark:text-slate-100">0%</span>
                    </div>
                    <div>
                        <span id="healthRatingBadge" class="inline-flex px-2 py-0.5 rounded text-xs font-bold bg-emerald-50 text-emerald-700 border border-emerald-200 mb-1">Memuat Skor...</span>
                        <p id="healthSummaryText" class="text-xs text-slate-500 leading-relaxed">Rasio margin laba bersih terhadap omzet keseluruhan.</p>
                    </div>
                </div>
            </div>

            <!-- Widget Simulator Laba "What-If" Interaktif -->
            <div class="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 shadow-sm p-4 relative overflow-hidden flex-1">
                <div class="absolute -top-12 -right-12 w-28 h-28 bg-blue-50/50 dark:bg-blue-900/10 rounded-full blur-xl pointer-events-none"></div>
                
                <div class="flex justify-between items-center mb-3">
                    <h4 class="text-sm font-bold text-slate-900 dark:text-slate-100 flex items-center gap-1.5">
                        <i class="fas fa-sliders text-indigo-600"></i>
                        Simulator Profitabilitas (What-If)
                    </h4>
                    <button onclick="resetSimulator()" class="text-xs text-indigo-600 dark:text-indigo-400 hover:text-indigo-800 font-semibold flex items-center gap-1 border-0 bg-transparent">
                        <i class="fas fa-undo"></i> Reset
                    </button>
                </div>
                <p class="text-xs text-slate-500 mb-4 leading-relaxed">Geser slider untuk memproyeksikan perubahan keuntungan jika biaya atau performa dioptimalkan.</p>
                
                <div class="space-y-3">
                    <!-- Slider Efisiensi Material -->
                    <div>
                        <div class="flex justify-between text-xs font-semibold text-slate-700 dark:text-slate-300 mb-1">
                            <span>Efisiensi Material (Sisa Bahan)</span>
                            <span id="sliderMaterialLabel" class="text-indigo-600 dark:text-indigo-400">+0%</span>
                        </div>
                        <input type="range" id="sliderMaterial" min="0" max="30" value="0" class="w-full accent-indigo-600 h-1.5 bg-slate-100 dark:bg-slate-700 rounded-lg appearance-none cursor-pointer">
                    </div>

                    <!-- Slider Efisiensi Gaji/Operasional -->
                    <div>
                        <div class="flex justify-between text-xs font-semibold text-slate-700 dark:text-slate-300 mb-1">
                            <span>Optimalisasi Payroll/Gaji</span>
                            <span id="sliderPayrollLabel" class="text-indigo-600 dark:text-indigo-400">+0%</span>
                        </div>
                        <input type="range" id="sliderPayroll" min="0" max="20" value="0" class="w-full accent-indigo-600 h-1.5 bg-slate-100 dark:bg-slate-700 rounded-lg appearance-none cursor-pointer">
                    </div>

                    <!-- Hasil Simulasi Berbasis Realtime -->
                    <div class="p-3 bg-slate-50 dark:bg-slate-900/40 rounded-xl border border-slate-100 dark:border-slate-700 mt-2">
                        <div class="flex justify-between items-center mb-1">
                            <span class="text-xs font-bold text-slate-600 dark:text-slate-400">Simulasi Laba Baru:</span>
                            <span id="simulatedLabaValue" class="text-sm font-extrabold text-slate-900 dark:text-slate-100">Rp 0</span>
                        </div>
                        <div class="flex justify-between items-center">
                            <span class="text-[10px] text-slate-400">Peningkatan Keuntungan:</span>
                            <span id="simulatedBoostValue" class="text-xs font-bold text-emerald-600">+Rp 0</span>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>

    <!-- Tabel Log Ringkasan Transaksi Klien & Keuangan Proyek CNC -->
    <div class="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 shadow-sm overflow-hidden mb-6">
        <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-3">
            <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-700 dark:text-slate-300"></i>
                    Rincian Alokasi Biaya Terpaut
                </h4>
                <p class="text-xs text-slate-500">Daftar beban operasional bengkel produksi dan pengerjaan CNC berjalan.</p>
            </div>
            <div class="relative w-full sm:w-64">
                <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-xs"></i>
                </span>
                <input type="text" id="filterTableInput" onkeyup="filterLogTable()" placeholder="Cari entitas..." class="w-full pl-9 pr-4 py-1.5 text-xs bg-slate-50 dark:bg-slate-900/30 dark:text-slate-100 border border-slate-200 dark:border-slate-700 rounded-xl focus:bg-white dark:focus:bg-slate-800 focus:outline-none focus:ring-2 focus:ring-blue-500 transition-all">
            </div>
        </div>
        <div class="table-responsive">
            <table class="w-full text-left border-collapse" id="logTable">
                <thead>
                    <tr class="bg-slate-50 dark:bg-slate-900/55 text-slate-500 dark:text-slate-400 font-bold text-xs uppercase tracking-wider border-b border-slate-100 dark:border-slate-700">
                        <th class="py-3 px-5">Pos Pengeluaran</th>
                        <th class="py-3 px-5">Alokasi Fiskal</th>
                        <th class="py-3 px-5">Proporsi Terhadap Omzet</th>
                        <th class="py-3 px-5">Status Risiko</th>
                    </tr>
                </thead>
                <tbody class="text-xs text-slate-600 dark:text-slate-300 divide-y divide-slate-100 dark:divide-slate-700">
                    <tr class="hover:bg-slate-50/50 dark:hover:bg-slate-900/10 transition-all">
                        <td class="py-3 px-5 font-semibold text-slate-800 dark:text-slate-200">Penyediaan Material Produksi</td>
                        <td class="py-3 px-5">Rp <span class="php-val"><?= number_format($material, 0, ',', '.') ?></span></td>
                        <td class="py-3 px-5 text-slate-500" id="propMaterial">Calculating...</td>
                        <td class="py-3 px-5">
                            <span class="inline-flex px-2 py-0.5 rounded text-[10px] font-bold bg-amber-50 dark:bg-amber-950/20 text-amber-700 dark:text-amber-400 border border-amber-200 dark:border-amber-800/40">Menengah</span>
                        </td>
                    </tr>
                    <tr class="hover:bg-slate-50/50 dark:hover:bg-slate-900/10 transition-all">
                        <td class="py-3 px-5 font-semibold text-slate-800 dark:text-slate-200">Biaya Gaji Operasional & Payroll</td>
                        <td class="py-3 px-5">Rp <span class="php-val"><?= number_format($payroll, 0, ',', '.') ?></span></td>
                        <td class="py-3 px-5 text-slate-500" id="propPayroll">Calculating...</td>
                        <td class="py-3 px-5">
                            <span class="inline-flex px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-50 dark:bg-emerald-950/20 text-emerald-700 dark:text-emerald-400 border border-emerald-200 dark:border-emerald-800/40">Aman</span>
                        </td>
                    </tr>
                    <tr class="hover:bg-slate-50/50 dark:hover:bg-slate-900/10 transition-all">
                        <td class="py-3 px-5 font-semibold text-slate-800 dark:text-slate-200">Sisa Outstanding Piutang Klien</td>
                        <td class="py-3 px-5">Rp <span class="php-val"><?= number_format($piutang, 0, ',', '.') ?></span></td>
                        <td class="py-3 px-5 text-slate-500" id="propPiutang">Calculating...</td>
                        <td class="py-3 px-5">
                            <span class="inline-flex px-2 py-0.5 rounded text-[10px] font-bold bg-rose-50 dark:bg-rose-950/20 text-rose-700 dark:text-rose-400 border border-rose-200 dark:border-rose-800/40">Perhatian</span>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- JS Dependencies: Chart.js and SheetJS (for clean .xlsx generation) -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>

<script>
document.addEventListener("DOMContentLoaded", function() {
    
    // ==========================================
    // DETEKSI MODE PREVIEW & DUMMY DATA PREMIUM
    // ==========================================
    let isPreview = false;
    const testElement = document.querySelector('.php-val');
    
    if (testElement && (testElement.innerHTML.includes('<?') || testElement.innerHTML.trim() === "")) {
        isPreview = true;
    }

    const appData = {
        omzet: isPreview ? 185000000 : parseFloat("<?= $omzet ?? 0 ?>"),
        beban: isPreview ? 115000000 : parseFloat("<?= $beban ?? 0 ?>"),
        laba: isPreview ? 70000000 : parseFloat("<?= $laba ?? 0 ?>"),
        material: isPreview ? 45000000 : parseFloat("<?= $material ?? 0 ?>"),
        payroll: isPreview ? 35000000 : parseFloat("<?= $payroll ?? 0 ?>"),
        piutang: isPreview ? 25000000 : parseFloat("<?= $piutang ?? 0 ?>"),
    };

    // Chart.js data raw mapping
    let chartDataRaw = { omzet: appData.omzet, beban: appData.beban, laba: appData.laba };
    try {
        <?php if(isset($chartData)): ?>
            chartDataRaw = <?= $chartData ?>;
        <?php endif; ?>
    } catch(e) {
        console.warn("Gagal parse data dari server, menggunakan data internal.");
    }

    // Update the visual metrics fallback on client preview
    if (isPreview) {
        document.getElementById('valOmzet').innerText = formatCurrency(appData.omzet);
        document.getElementById('valBeban').innerText = formatCurrency(appData.beban);
        document.getElementById('valLaba').innerText = formatCurrency(appData.laba);
        document.getElementById('valMaterial').innerText = formatCurrency(appData.material);
        document.getElementById('valPayroll').innerText = formatCurrency(appData.payroll);
        document.getElementById('valPiutang').innerText = formatCurrency(appData.piutang);
        
        const badgeContainer = document.getElementById('labaStatusBadge');
        if (appData.laba >= 0) {
            badgeContainer.innerHTML = `
                <span class="inline-flex items-center gap-1 px-3 py-1 rounded-full text-xs font-semibold bg-emerald-100 text-emerald-800 dark:bg-emerald-900/30 dark:text-emerald-400 shadow-sm">
                    <i class="fas fa-circle-check"></i> SURPLUS (UNTUNG)
                </span>`;
        } else {
            badgeContainer.innerHTML = `
                <span class="inline-flex items-center gap-1 px-3 py-1 rounded-full text-xs font-semibold bg-rose-100 text-rose-800 dark:bg-rose-900/30 dark:text-rose-400 shadow-sm">
                    <i class="fas fa-triangle-exclamation"></i> DEFISIT (RUGI)
                </span>`;
        }
    }

    // ==========================================
    // UTILITAS FORMAT RUPIAH & JAM REALTIME
    // ==========================================
    function formatCurrency(value) {
        return new Intl.NumberFormat('id-ID', {
            style: 'decimal',
            maximumFractionDigits: 0
        }).format(value);
    }

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

    // ==========================================
    // PROPORSI ALOKASI FISKAL DI TABEL
    // ==========================================
    function calculateProportions() {
        const total = appData.omzet || 1;
        document.getElementById('propMaterial').innerText = ((appData.material / total) * 100).toFixed(1) + '% dari Omzet';
        document.getElementById('propPayroll').innerText = ((appData.payroll / total) * 100).toFixed(1) + '% dari Omzet';
        document.getElementById('propPiutang').innerText = ((appData.piutang / total) * 100).toFixed(1) + '% dari Omzet';
    }
    calculateProportions();

    // ==========================================
    // PREMIUM CHART.JS DYNAMIC ARCHITECTURE
    // ==========================================
    const ctx = document.getElementById('financeChartComplex').getContext('2d');
    
    // Custom gradients configuration
    const gradientOmzet = ctx.createLinearGradient(0, 0, 0, 350);
    gradientOmzet.addColorStop(0, 'rgba(16, 185, 129, 0.85)');
    gradientOmzet.addColorStop(1, 'rgba(16, 185, 129, 0.15)');

    const gradientBeban = ctx.createLinearGradient(0, 0, 0, 350);
    gradientBeban.addColorStop(0, 'rgba(239, 68, 68, 0.85)');
    gradientBeban.addColorStop(1, 'rgba(239, 68, 68, 0.15)');

    const gradientLaba = ctx.createLinearGradient(0, 0, 0, 350);
    gradientLaba.addColorStop(0, 'rgba(59, 130, 246, 0.85)');
    gradientLaba.addColorStop(1, 'rgba(59, 130, 246, 0.15)');

    let activeChartType = 'bar';
    window.financeChartInstance = new Chart(ctx, getChartConfig('bar'));

    function getChartConfig(type) {
        const isDarkMode = document.documentElement.classList.contains('dark');
        const gridColor = isDarkMode ? '#334155' : '#f1f5f9';
        const labelColor = isDarkMode ? '#cbd5e1' : '#64748b';

        if (type === 'bar') {
            return {
                type: 'bar',
                data: {
                    labels: ['Omzet Masuk', 'Beban Pengeluaran', 'Laba Bersih'],
                    datasets: [{
                        label: 'Nilai Fiskal (Rp)',
                        data: [chartDataRaw.omzet, chartDataRaw.beban, chartDataRaw.laba],
                        backgroundColor: [gradientOmzet, gradientBeban, gradientLaba],
                        borderColor: ['#10b981', '#ef4444', '#3b82f6'],
                        borderWidth: 2,
                        borderRadius: 14,
                        borderSkipped: false,
                        barThickness: 50,
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { display: false },
                        tooltip: {
                            backgroundColor: isDarkMode ? '#1e293b' : '#0f172a',
                            titleColor: '#ffffff',
                            bodyColor: '#cbd5e1',
                            padding: 14,
                            cornerRadius: 12,
                            callbacks: {
                                label: function(context) {
                                    return ' ' + context.label + ': Rp ' + formatCurrency(context.parsed.y);
                                }
                            }
                        }
                    },
                    scales: {
                        y: {
                            grid: { color: gridColor, drawBorder: false },
                            ticks: {
                                color: labelColor,
                                font: { family: 'Inter', size: 11 },
                                callback: function(value) {
                                    if (value >= 1000000) {
                                        return 'Rp ' + (value / 1000000).toFixed(0) + ' Jt';
                                    }
                                    return 'Rp ' + value;
                                }
                            }
                        },
                        x: {
                            grid: { display: false },
                            ticks: {
                                color: isDarkMode ? '#cbd5e1' : '#1e293b',
                                font: { family: 'Inter', size: 11, weight: '600' }
                            }
                        }
                    }
                }
            };
        } else if (type === 'doughnut') {
            return {
                type: 'doughnut',
                data: {
                    labels: ['Beban Pengeluaran', 'Laba Bersih'],
                    datasets: [{
                        data: [chartDataRaw.beban, chartDataRaw.laba > 0 ? chartDataRaw.laba : 0],
                        backgroundColor: ['rgba(239, 68, 68, 0.8)', 'rgba(59, 130, 246, 0.8)'],
                        borderColor: isDarkMode ? '#1e293b' : '#ffffff',
                        borderWidth: 4,
                        hoverOffset: 12
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                color: labelColor,
                                font: { family: 'Inter', size: 12 },
                                padding: 20
                            }
                        },
                        tooltip: {
                            backgroundColor: isDarkMode ? '#1e293b' : '#0f172a',
                            padding: 14,
                            cornerRadius: 12,
                            callbacks: {
                                label: function(context) {
                                    let percentage = ((context.parsed / (chartDataRaw.beban + chartDataRaw.laba)) * 100).toFixed(1);
                                    return ' ' + context.label + ': Rp ' + formatCurrency(context.parsed) + ' (' + percentage + '%)';
                                }
                            }
                        }
                    },
                    cutout: '65%'
                }
            };
        }
    }

    window.switchChartType = function(type) {
        if (activeChartType === type) return;
        activeChartType = type;
        
        const btnBar = document.getElementById('btnBarChart');
        const btnDoughnut = document.getElementById('btnDoughnutChart');
        
        if (type === 'bar') {
            btnBar.className = "px-3 py-1.5 rounded-lg text-xs font-semibold bg-blue-600 text-white shadow-xs transition-all border-0";
            btnDoughnut.className = "px-3 py-1.5 rounded-lg text-xs font-semibold bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 text-slate-600 dark:text-slate-200 hover:bg-slate-50 shadow-xs transition-all";
        } else {
            btnDoughnut.className = "px-3 py-1.5 rounded-lg text-xs font-semibold bg-blue-600 text-white shadow-xs transition-all border-0";
            btnBar.className = "px-3 py-1.5 rounded-lg text-xs font-semibold bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 text-slate-600 dark:text-slate-200 hover:bg-slate-50 shadow-xs transition-all";
        }

        if (window.financeChartInstance) {
            window.financeChartInstance.destroy();
        }
        window.financeChartInstance = new Chart(ctx, getChartConfig(type));
    };

    // ==========================================
    // DYNAMIC HEALTH INDEX INDICATOR
    // ==========================================
    function calculateHealthScore() {
        const marginRasio = appData.omzet > 0 ? (appData.laba / appData.omzet) * 100 : 0;
        let score = Math.min(Math.max(Math.round(marginRasio), 0), 100);
        
        const circle = document.getElementById('healthScoreCircle');
        const textPercent = document.getElementById('healthPercentageText');
        const badge = document.getElementById('healthRatingBadge');
        const summary = document.getElementById('healthSummaryText');
        
        const strokeDashoffset = 213.6 - (score / 100) * 213.6;
        circle.style.strokeDashoffset = strokeDashoffset;
        textPercent.innerText = score + "%";

        if (score >= 40) {
            badge.innerText = "Sangat Prima (A+)";
            badge.className = "inline-flex px-2 py-0.5 rounded text-[10px] font-extrabold bg-emerald-50 text-emerald-700 border border-emerald-200 mb-1";
            circle.setAttribute('stroke', '#10b981');
            summary.innerText = "Stabilitas profit margin berada dalam tingkat prima untuk eskalasi bisnis CNC Anda.";
        } else if (score >= 20) {
            badge.innerText = "Normal-Stabil (B)";
            badge.className = "inline-flex px-2 py-0.5 rounded text-[10px] font-extrabold bg-blue-50 text-blue-700 border border-blue-200 mb-1";
            circle.setAttribute('stroke', '#3b82f6');
            summary.innerText = "Kinerja stabil. Pastikan pengumpulan outstanding piutang lancar.";
        } else if (score > 0) {
            badge.innerText = "Perhatian Khusus (C)";
            badge.className = "inline-flex px-2 py-0.5 rounded text-[10px] font-extrabold bg-amber-50 text-amber-700 border border-amber-200 mb-1";
            circle.setAttribute('stroke', '#f59e0b');
            summary.innerText = "Profit tipis. Waktunya melakukan efisiensi di komponen belanja material bengkel.";
        } else {
            badge.innerText = "Sinyal Bahaya / Defisit (E)";
            badge.className = "inline-flex px-2 py-0.5 rounded text-[10px] font-extrabold bg-rose-50 text-rose-700 border border-rose-200 mb-1 animate-pulse";
            circle.setAttribute('stroke', '#ef4444');
            summary.innerText = "Operasional defisit. Segera lakukan restrukturisasi tarif jasa CNC Anda.";
        }
    }
    calculateHealthScore();

    // ==========================================
    // INTERAKTIF SIMULATION PROJECTION ENGINE
    // ==========================================
    const sliderMaterial = document.getElementById('sliderMaterial');
    const sliderPayroll = document.getElementById('sliderPayroll');
    
    function calculateSimulation() {
        const materialVal = parseFloat(sliderMaterial.value);
        const payrollVal = parseFloat(sliderPayroll.value);
        
        document.getElementById('sliderMaterialLabel').innerText = `+${materialVal}%`;
        document.getElementById('sliderPayrollLabel').innerText = `+${payrollVal}%`;

        const savingMaterial = appData.material * (materialVal / 100);
        const savingPayroll = appData.payroll * (payrollVal / 100);
        const totalSavings = savingMaterial + savingPayroll;
        
        const simulatedLaba = appData.laba + totalSavings;

        document.getElementById('simulatedLabaValue').innerText = 'Rp ' + formatCurrency(simulatedLaba);
        document.getElementById('simulatedBoostValue').innerText = '+Rp ' + formatCurrency(totalSavings);
    }

    sliderMaterial.addEventListener('input', calculateSimulation);
    sliderPayroll.addEventListener('input', calculateSimulation);
    calculateSimulation();

    window.resetSimulator = function() {
        sliderMaterial.value = 0;
        sliderPayroll.value = 0;
        calculateSimulation();
    };

    // ==========================================
    // CLIENT-SIDE SEARCH FILTER TABLE
    // ==========================================
    window.filterLogTable = function() {
        const input = document.getElementById('filterTableInput');
        const filter = input.value.toUpperCase();
        const table = document.getElementById('logTable');
        const tr = table.getElementsByTagName('tr');

        for (let i = 1; i < tr.length; i++) {
            let found = false;
            let td = tr[i].getElementsByTagName('td');
            for (let j = 0; j < td.length; j++) {
                if (td[j]) {
                    let txtValue = td[j].textContent || td[j].innerText;
                    if (txtValue.toUpperCase().indexOf(filter) > -1) {
                        found = true;
                        break;
                    }
                }
            }
            tr[i].style.display = found ? "" : "none";
        }
    };

    // Reload trigger
    window.perbaruiData = function() {
        location.reload();
    };

    // ==========================================
    // EXCEL EXPORTER GENERATION (XLSX SHEETJS)
    // ==========================================
    window.exportToExcel = function() {
        // Prepare structured matrix matching corporate standards
        const reportData = [
            ["LAPORAN ANALISIS KINERJA FISKAL & KEUANGAN"],
            ["Entitas Bengkel CNC & Integrasi Finansial Owner"],
            ["Waktu Pembuatan", new Date().toLocaleString('id-ID')],
            [],
            ["POS KEUANGAN UTAMA", "ALOKASI NILAI (IDR)", "PROPORSI (%) TERHADAP OMZET"],
            ["Total Pendapatan (Omzet)", appData.omzet, "100.0%"],
            ["Total Pengeluaran (Beban)", appData.beban, ((appData.beban / appData.omzet) * 100).toFixed(1) + "%"],
            ["Laba / Rugi Bersih", appData.laba, ((appData.laba / appData.omzet) * 100).toFixed(1) + "%"],
            [],
            ["RINCIAN ALOKASI BEBAN TAMBAHAN & OUTSTANDING", "", ""],
            ["Beban Penyediaan Material Produksi", appData.material, ((appData.material / appData.omzet) * 100).toFixed(1) + "%"],
            ["Biaya Gaji Operasional & Payroll", appData.payroll, ((appData.payroll / appData.omzet) * 100).toFixed(1) + "%"],
            ["Sisa Outstanding Piutang Klien", appData.piutang, ((appData.piutang / appData.omzet) * 100).toFixed(1) + "%"]
        ];

        // Create workbook & worksheet instance
        const wb = XLSX.utils.book_new();
        const ws = XLSX.utils.aoa_to_sheet(reportData);

        // Append sheet with customized naming conventions
        XLSX.utils.book_append_sheet(wb, ws, "Fiskal CNC Owner");

        // Save file triggers browser download dialogue
        XLSX.writeFile(wb, "Laporan_Kinerja_Finansial_CNC_Owner.xlsx");
    };

    // ==========================================
    // DARK MODE SYSTEM 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 animate-spin-slow";
        }

        // Redraw active Chart to swap fonts & grids on the fly
        if (window.financeChartInstance) {
            const config = getChartConfig(activeChartType);
            window.financeChartInstance.destroy();
            window.financeChartInstance = new Chart(ctx, config);
        }
    };

    // Keep state on page reload
    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 animate-spin-slow";
        // Force chart redraw to dark theme properties
        setTimeout(() => {
            if (window.financeChartInstance) {
                window.financeChartInstance.destroy();
                window.financeChartInstance = new Chart(ctx, getChartConfig(activeChartType));
            }
        }, 100);
    }
});
</script>

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