<?= $this->extend('layouts/main') ?>
<?= $this->section('css') ?>
<link href="https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.3/dist/chart.umd.min.js"></script>
<style>
:root {
    --ink:      #0b0f1a;
    --ink2:     #374151;
    --ink3:     #6b7280;
    --surface:  #f3f4f6;
    --card:     #ffffff;
    --edge:     rgba(0,0,0,.07);
    --edge2:    rgba(0,0,0,.12);
    --blue:     #2563eb;
    --blue-lt:  #eff6ff;
    --green:    #059669;
    --green-lt: #ecfdf5;
    --amber:    #d97706;
    --amber-lt: #fffbeb;
    --red:      #dc2626;
    --red-lt:   #fef2f2;
    --purple:   #7c3aed;
    --purple-lt:#f5f3ff;
    --radius:   12px;
    --mono:     'DM Mono', monospace;
    --sans:     'Plus Jakarta Sans', sans-serif;
    --shadow:   0 1px 3px rgba(0,0,0,.08), 0 4px 16px rgba(0,0,0,.05);
}
* { box-sizing:border-box; margin:0; padding:0; }
body { font-family:var(--sans) !important; color:var(--ink) !important; background:var(--surface) !important; }

/* ── Header ── */
.lp-header { display:flex; align-items:flex-end; justify-content:space-between; flex-wrap:wrap; gap:12px; margin-bottom:24px; }
.lp-header h1 { font-size:1.5rem; font-weight:800; color:var(--ink); display:flex; align-items:center; gap:10px; }
.lp-header h1 .ico-wrap { width:40px; height:40px; background:linear-gradient(135deg,#2563eb,#7c3aed); border-radius:12px; display:flex; align-items:center; justify-content:center; }
.lp-header h1 .ico-wrap i { color:#fff; font-size:1.1rem; }
.lp-header p { font-size:.8rem; color:var(--ink3); margin-top:3px; }

/* ── Stat Grid ── */
.stat-grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(190px,1fr)); gap:14px; margin-bottom:16px; }
.stat-card { background:var(--card); border:1.5px solid var(--edge); border-radius:var(--radius); padding:18px 18px 16px; box-shadow:var(--shadow); position:relative; overflow:hidden; }
.stat-card::before { content:''; position:absolute; top:0; left:0; right:0; height:3px; background:var(--accent-color,var(--blue)); border-radius:var(--radius) var(--radius) 0 0; }
.stat-card .sc-label { font-size:.72rem; font-weight:600; text-transform:uppercase; letter-spacing:.06em; color:var(--ink3); margin-bottom:8px; }
.stat-card .sc-val { font-size:1.28rem; font-weight:800; color:var(--ink); font-family:var(--mono); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
.stat-card .sc-sub { font-size:.7rem; color:var(--ink3); margin-top:4px; font-family:var(--mono); }
.stat-card .sc-ico { position:absolute; right:14px; top:20px; font-size:2rem; opacity:.06; }
.stat-card .sc-trend { font-size:.65rem; margin-top:5px; }
.sc-trend.up   { color:var(--green); }
.sc-trend.down { color:var(--red); }

/* ── Channel Row ── */
.channel-row { display:grid; grid-template-columns:repeat(auto-fill,minmax(160px,1fr)); gap:10px; margin-bottom:20px; }
.ch-pill { background:var(--card); border:1.5px solid var(--edge); border-radius:10px; padding:12px 14px; box-shadow:var(--shadow); display:flex; align-items:center; gap:10px; }
.ch-dot  { width:10px; height:10px; border-radius:50%; flex-shrink:0; }
.ch-info { min-width:0; }
.ch-name { font-size:.7rem; font-weight:700; text-transform:uppercase; letter-spacing:.05em; color:var(--ink3); }
.ch-val  { font-size:.88rem; font-weight:800; font-family:var(--mono); color:var(--ink); white-space:nowrap; }
.ch-trx  { font-size:.65rem; color:var(--ink3); font-family:var(--mono); }

/* ── Filter Bar ── */
.filter-bar { background:var(--card); border:1.5px solid var(--edge); border-radius:var(--radius); padding:14px 18px; margin-bottom:20px; box-shadow:var(--shadow); }
.filter-bar form { display:flex; flex-wrap:wrap; gap:10px; align-items:flex-end; }
.fb-group { display:flex; flex-direction:column; gap:4px; }
.fb-group label { font-size:.72rem; font-weight:600; color:var(--ink3); text-transform:uppercase; letter-spacing:.05em; }
.fb-group input, .fb-group select { background:var(--surface); border:1.5px solid var(--edge2); border-radius:8px; padding:7px 11px; font-family:var(--sans); font-size:.82rem; color:var(--ink); outline:none; min-width:140px; transition:border-color .15s; }
.fb-group input:focus, .fb-group select:focus { border-color:var(--blue); background:#fff; }
.fb-search { flex:1; min-width:160px; }
.fb-group select.has-value { border-color:var(--blue); background:#fff; }

.btn-filter { background:var(--blue); color:#fff; border:none; border-radius:8px; padding:8px 18px; font-family:var(--sans); font-size:.82rem; font-weight:700; cursor:pointer; display:flex; align-items:center; gap:6px; transition:opacity .15s; }
.btn-filter:hover { opacity:.85; }
.btn-export { background:var(--green); color:#fff; border:none; border-radius:8px; padding:8px 16px; font-family:var(--sans); font-size:.82rem; font-weight:700; cursor:pointer; display:flex; align-items:center; gap:6px; text-decoration:none; transition:opacity .15s; }
.btn-export:hover { opacity:.85; color:#fff; }
.btn-export.loading { opacity:.6; pointer-events:none; }
.btn-reset-filter { background:none; color:var(--ink3); border:1.5px solid var(--edge2); border-radius:8px; padding:7px 14px; font-family:var(--sans); font-size:.8rem; cursor:pointer; transition:all .13s; }
.btn-reset-filter:hover { border-color:var(--ink2); color:var(--ink); }

/* ── Main Grid (chart + top produk) ── */
.main-grid { display:grid; grid-template-columns:1fr 300px; gap:18px; margin-bottom:20px; }
.chart-card { background:var(--card); border:1.5px solid var(--edge); border-radius:var(--radius); padding:20px 20px 16px; box-shadow:var(--shadow); }
.card-title { font-size:.82rem; font-weight:700; color:var(--ink); text-transform:uppercase; letter-spacing:.04em; margin-bottom:16px; display:flex; align-items:center; gap:8px; }
.card-title i { color:var(--blue); }
.chart-legend { display:flex; gap:14px; margin-bottom:12px; }
.cl-item { display:flex; align-items:center; gap:5px; font-size:.7rem; font-weight:600; color:var(--ink3); }
.cl-dot  { width:8px; height:8px; border-radius:2px; }

.top-card { background:var(--card); border:1.5px solid var(--edge); border-radius:var(--radius); padding:18px; box-shadow:var(--shadow); display:flex; flex-direction:column; }
.tp-item { display:flex; align-items:center; gap:10px; padding:8px 0; border-bottom:1px solid var(--edge); }
.tp-item:last-child { border-bottom:none; }
.tp-rank { width:24px; height:24px; border-radius:6px; background:var(--surface); display:flex; align-items:center; justify-content:center; font-size:.7rem; font-weight:700; color:var(--ink3); flex-shrink:0; }
.tp-rank.r1 { background:#fef9c3; color:#b45309; }
.tp-rank.r2 { background:#f1f5f9; color:#475569; }
.tp-rank.r3 { background:#fff7ed; color:#c2410c; }
.tp-name { flex:1; font-size:.78rem; font-weight:600; color:var(--ink); min-width:0; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
.tp-qty  { font-family:var(--mono); font-size:.74rem; color:var(--blue); font-weight:600; white-space:nowrap; }

/* ── Table Card ── */
.table-card { background:var(--card); border:1.5px solid var(--edge); border-radius:var(--radius); box-shadow:var(--shadow); overflow:hidden; }
.table-head-bar { display:flex; justify-content:space-between; align-items:center; padding:14px 18px; border-bottom:1px solid var(--edge); }
.table-head-bar .th-info { font-size:.82rem; font-weight:700; color:var(--ink); display:flex; align-items:center; gap:8px; }
.trx-count { background:var(--surface); color:var(--ink3); border-radius:20px; padding:2px 10px; font-size:.68rem; font-family:var(--mono); font-weight:600; }

.table-wrap { overflow-x:auto; }
.lp-table { width:100%; border-collapse:collapse; font-size:.78rem; }
.lp-table thead th { background:#f8fafc; padding:10px 14px; text-align:left; font-weight:700; font-size:.68rem; text-transform:uppercase; letter-spacing:.06em; color:var(--ink3); white-space:nowrap; border-bottom:1px solid var(--edge); }
.lp-table tbody tr { border-bottom:1px solid var(--edge); transition:background .1s; }
.lp-table tbody tr:hover { background:#f8fafc; }
.lp-table tbody tr:last-child { border-bottom:none; }
.lp-table td { padding:10px 14px; vertical-align:middle; color:var(--ink2); white-space:nowrap; }
.lp-table td .no-trx { font-family:var(--mono); font-size:.72rem; color:var(--blue); font-weight:600; }
.lp-table td .date-cell { font-family:var(--mono); font-size:.72rem; color:var(--ink3); }

.badge-chan, .badge-met { display:inline-block; padding:2px 8px; border-radius:5px; font-size:.65rem; font-weight:600; white-space:nowrap; }
.chan-pos       { background:var(--blue-lt);   color:var(--blue);   }
.chan-reseller  { background:var(--purple-lt);  color:var(--purple); }
.chan-maklon    { background:var(--amber-lt);   color:var(--amber);  }
.chan-online    { background:var(--green-lt);   color:var(--green);  }
.met-tunai      { background:var(--green-lt);  color:var(--green);  }
.met-transfer   { background:var(--blue-lt);   color:var(--blue);   }
.met-qris       { background:var(--purple-lt); color:var(--purple); }
.met-cod        { background:var(--amber-lt);  color:var(--amber);  }
.met-other      { background:var(--surface);   color:var(--ink3);   }
.badge-tiktok   { background:#fff0f6; color:#e91e8c; border:1px solid #ffc1e0; font-size:.6rem; padding:1px 6px; border-radius:4px; font-weight:700; margin-left:4px; vertical-align:middle; }

.rp-cell { font-family:var(--mono); font-weight:600; color:var(--ink); }
.btn-detail { background:var(--blue-lt); color:var(--blue); border:none; border-radius:6px; padding:4px 10px; font-family:var(--sans); font-size:.72rem; font-weight:600; cursor:pointer; transition:background .12s; }
.btn-detail:hover { background:#dbeafe; }

/* ── Paging ── */
.paging-bar { display:flex; justify-content:space-between; align-items:center; padding:12px 18px; border-top:1px solid var(--edge); font-size:.76rem; }
.paging-btns { display:flex; gap:4px; }
.paging-btns button { background:var(--surface); border:1.5px solid var(--edge2); border-radius:7px; padding:4px 10px; font-family:var(--sans); font-size:.72rem; font-weight:600; color:var(--ink); cursor:pointer; transition:all .12s; }
.paging-btns button:hover:not(:disabled) { border-color:var(--blue); color:var(--blue); }
.paging-btns button:disabled { opacity:.35; cursor:not-allowed; }
.paging-btns button.active { background:var(--blue); color:#fff; border-color:var(--blue); }

/* ── Summary Bar ── */
.summary-bar { display:flex; gap:18px; flex-wrap:wrap; padding:12px 18px; background:#f8fafc; border-bottom:1px solid var(--edge); font-size:.76rem; }
.sb-item { display:flex; flex-direction:column; gap:1px; }
.sb-item .sk { color:var(--ink3); font-weight:600; text-transform:uppercase; font-size:.65rem; letter-spacing:.05em; }
.sb-item .sv { font-family:var(--mono); font-weight:700; color:var(--ink); }

/* ── Loader ── */
.loading-overlay { position:absolute; inset:0; background:rgba(255,255,255,.7); display:flex; align-items:center; justify-content:center; border-radius:var(--radius); z-index:10; }
.spinner { width:28px; height:28px; border:3px solid var(--edge2); border-top-color:var(--blue); border-radius:50%; animation:spin .6s linear infinite; }
@keyframes spin { to { transform:rotate(360deg); } }

/* ── Modal ── */
.modal-backdrop { position:fixed; inset:0; background:rgba(0,0,0,.45); z-index:10000; display:flex; align-items:center; justify-content:center; animation:fadeIn .2s ease; padding:16px; }
@keyframes fadeIn { from{opacity:0} to{opacity:1} }
.modal-box { background:#fff; border-radius:18px; padding:24px 26px; width:520px; max-width:96vw; max-height:90vh; overflow-y:auto; box-shadow:0 20px 60px rgba(0,0,0,.25); animation:slideUp .2s ease; }
@keyframes slideUp { from{transform:translateY(20px);opacity:0} to{transform:none;opacity:1} }
.modal-title { font-size:1rem; font-weight:800; margin-bottom:4px; display:flex; align-items:center; gap:8px; }
.modal-no { font-family:var(--mono); font-size:.78rem; color:var(--blue); margin-bottom:14px; }
.modal-meta { background:var(--surface); border-radius:10px; padding:12px 14px; margin-bottom:14px; display:grid; grid-template-columns:1fr 1fr; gap:6px 16px; }
.mm-row { display:flex; flex-direction:column; }
.mm-row .mk { font-size:.68rem; font-weight:600; color:var(--ink3); text-transform:uppercase; letter-spacing:.04em; }
.mm-row .mv { font-size:.82rem; font-weight:600; color:var(--ink); font-family:var(--mono); }
.modal-items-title { font-size:.72rem; font-weight:700; text-transform:uppercase; letter-spacing:.06em; color:var(--ink3); margin-bottom:8px; }
.modal-items-table { width:100%; border-collapse:collapse; font-size:.77rem; margin-bottom:14px; }
.modal-items-table th { text-align:left; font-size:.66rem; text-transform:uppercase; letter-spacing:.05em; color:var(--ink3); padding:6px 8px; border-bottom:1px solid var(--edge); }
.modal-items-table td { padding:7px 8px; border-bottom:1px solid var(--edge); color:var(--ink2); }
.modal-items-table tr:last-child td { border-bottom:none; }
.modal-total-row { display:flex; justify-content:space-between; align-items:center; border-top:2px dashed var(--edge2); padding-top:10px; font-weight:800; }
.modal-total-row .mv { font-family:var(--mono); font-size:1.1rem; color:var(--green); }
.modal-close { width:100%; background:var(--surface); border:1.5px solid var(--edge2); border-radius:9px; padding:10px; font-family:var(--sans); font-size:.82rem; font-weight:600; cursor:pointer; margin-top:8px; transition:background .12s; }
.modal-close:hover { background:#e2e8f0; }

.table-empty { text-align:center; padding:56px 0; color:var(--ink3); }
.table-empty i { font-size:2.5rem; display:block; margin-bottom:10px; opacity:.2; }
.table-empty p { font-size:.82rem; }

/* ── Toast ── */
.toast { position:fixed; bottom:24px; right:24px; background:var(--ink); color:#fff; border-radius:10px; padding:12px 18px; font-family:var(--sans); font-size:.82rem; font-weight:600; display:flex; align-items:center; gap:10px; box-shadow:0 8px 32px rgba(0,0,0,.25); z-index:99999; animation:toastIn .25s ease; max-width:320px; }
.toast.success { background:var(--green); }
.toast.error   { background:var(--red); }
@keyframes toastIn  { from{transform:translateY(16px);opacity:0} to{transform:none;opacity:1} }
@keyframes toastOut { to{transform:translateY(16px);opacity:0} }
.toast.hide { animation:toastOut .25s ease forwards; }

@media(max-width:900px) { .main-grid{grid-template-columns:1fr;} .stat-grid{grid-template-columns:repeat(2,1fr);} }
@media(max-width:600px) { .filter-bar form{flex-direction:column;} .stat-grid{grid-template-columns:1fr 1fr;} .channel-row{grid-template-columns:1fr 1fr;} }
</style>
<?= $this->endSection() ?>

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

<div class="lp-header">
    <div>
        <h1>
            <span class="ico-wrap"><i class="bi bi-bar-chart-line-fill"></i></span>
            Laporan Penjualan
        </h1>
        <p>Ringkasan, tren, dan riwayat seluruh transaksi — Internal & TikTok Marketplace</p>
    </div>
    <a id="btnExport" href="#" class="btn-export" onclick="handleExport(event)">
        <i class="bi bi-file-earmark-excel-fill"></i>
        <span class="export-text">Export Excel (.xlsx)</span>
    </a>
</div>

<!-- ═══ STAT CARDS (data dari controller via union, akurat) ═══ -->
<div class="stat-grid">
    <div class="stat-card" style="--accent-color:var(--blue)">
        <i class="bi bi-receipt sc-ico"></i>
        <div class="sc-label">Transaksi Hari Ini</div>
        <div class="sc-val"><?= number_format($todayStat['total_transaksi'] ?? 0) ?></div>
        <div class="sc-sub">transaksi</div>
    </div>
    <div class="stat-card" style="--accent-color:var(--green)">
        <i class="bi bi-cash-coin sc-ico"></i>
        <div class="sc-label">Omzet Hari Ini</div>
        <div class="sc-val">Rp <?= number_format($todayStat['total_omzet'] ?? 0, 0, ',', '.') ?></div>
        <div class="sc-sub">
            Internal: Rp <?= number_format($todayStat['omzet_internal'] ?? 0, 0, ',', '.') ?>
            &nbsp;|&nbsp;
            TikTok: Rp <?= number_format($todayStat['omzet_tiktok'] ?? 0, 0, ',', '.') ?>
        </div>
    </div>
    <div class="stat-card" style="--accent-color:var(--green)">
        <i class="bi bi-cash sc-ico"></i>
        <div class="sc-label">Tunai</div>
        <div class="sc-val">Rp <?= number_format($todayStat['kas_tunai'] ?? 0, 0, ',', '.') ?></div>
        <div class="sc-sub">kas tunai</div>
    </div>
    <div class="stat-card" style="--accent-color:var(--amber)">
        <i class="bi bi-bank sc-ico"></i>
        <div class="sc-label">Transfer</div>
        <div class="sc-val">Rp <?= number_format($todayStat['transfer'] ?? 0, 0, ',', '.') ?></div>
        <div class="sc-sub">via bank</div>
    </div>
    <div class="stat-card" style="--accent-color:var(--purple)">
        <i class="bi bi-qr-code-scan sc-ico"></i>
        <div class="sc-label">QRIS</div>
        <div class="sc-val">Rp <?= number_format($todayStat['qris'] ?? 0, 0, ',', '.') ?></div>
        <div class="sc-sub">e-wallet / QRIS</div>
    </div>
    <?php if (($todayStat['cod'] ?? 0) > 0): ?>
    <div class="stat-card" style="--accent-color:var(--amber)">
        <i class="bi bi-truck sc-ico"></i>
        <div class="sc-label">COD</div>
        <div class="sc-val">Rp <?= number_format($todayStat['cod'] ?? 0, 0, ',', '.') ?></div>
        <div class="sc-sub">cash on delivery</div>
    </div>
    <?php endif; ?>
</div>

<!-- ═══ CHANNEL BREAKDOWN HARI INI ═══ -->
<?php if (!empty($channelStat)): ?>
<div class="channel-row">
    <?php
    $chanConfig = [
        'Ecer'        => ['#2563eb', 'Kasir POS'],
        'Reseller'    => ['#7c3aed', 'Reseller'],
        'Maklon'      => ['#d97706', 'Maklon'],
        'marketplace' => ['#059669', 'Marketplace'],
    ];
    foreach ($channelStat as $ch):
        [$color, $label] = $chanConfig[$ch['channel']] ?? ['#6b7280', $ch['channel']];
    ?>
    <div class="ch-pill">
        <div class="ch-dot" style="background:<?= $color ?>"></div>
        <div class="ch-info">
            <div class="ch-name"><?= esc($label) ?></div>
            <div class="ch-val">Rp <?= number_format($ch['total_omzet'], 0, ',', '.') ?></div>
            <div class="ch-trx"><?= number_format($ch['total_trx']) ?> trx</div>
        </div>
    </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<!-- ═══ FILTER BAR ═══ -->
<div class="filter-bar">
    <form id="filterForm" onsubmit="return false;">
        <div class="fb-group">
            <label>Dari Tanggal</label>
            <input type="date" id="tglMulai" value="<?= date('Y-m-01') ?>">
        </div>
        <div class="fb-group">
            <label>Sampai Tanggal</label>
            <input type="date" id="tglAkhir" value="<?= date('Y-m-d') ?>">
        </div>
        <div class="fb-group">
            <label>Channel</label>
            <select id="selChannel">
                <option value="">Semua Channel</option>
                <option value="pos">Kasir (POS)</option>
                <option value="reseller">Reseller</option>
                <option value="maklon">Maklon</option>
                <option value="marketplace">Marketplace / TikTok</option>
            </select>
        </div>
        <div class="fb-group">
            <label>Metode Bayar</label>
            <select id="selMetode" disabled>
                <option value="">Memuat metode…</option>
            </select>
        </div>
        <div class="fb-group fb-search">
            <label>Cari</label>
            <input type="text" id="srchInput" placeholder="No. transaksi, Order ID, catatan…">
        </div>
        <button type="button" class="btn-filter" onclick="loadData()">
            <i class="bi bi-funnel-fill"></i> Filter
        </button>
        <button type="button" class="btn-reset-filter" onclick="resetFilter()">
            <i class="bi bi-x-lg"></i> Reset
        </button>
    </form>
</div>

<!-- ═══ CHART + TOP PRODUK ═══ -->
<div class="main-grid">
    <div class="chart-card" style="position:relative">
        <div class="card-title"><i class="bi bi-graph-up-arrow"></i> Grafik Omzet Harian</div>
        <div class="chart-legend">
            <div class="cl-item"><div class="cl-dot" style="background:#2563eb"></div> Total</div>
            <div class="cl-item"><div class="cl-dot" style="background:#7c3aed"></div> Internal</div>
            <div class="cl-item"><div class="cl-dot" style="background:#e91e8c"></div> TikTok</div>
        </div>
        <canvas id="omzetChart" height="80"></canvas>
        <div class="loading-overlay" id="chartLoader" style="display:none"><div class="spinner"></div></div>
    </div>

    <div class="top-card">
        <div class="card-title"><i class="bi bi-trophy-fill" style="color:var(--amber)"></i> Top Produk Bulan Ini</div>
        <?php if (empty($topProduk)): ?>
            <div style="color:var(--ink3);font-size:.8rem;text-align:center;padding:24px 0">Belum ada data</div>
        <?php else: ?>
            <?php foreach ($topProduk as $i => $tp): ?>
            <div class="tp-item">
                <div class="tp-rank <?= $i < 3 ? 'r'.($i+1) : '' ?>"><?= $i+1 ?></div>
                <div class="tp-name" title="<?= esc($tp['nama_produk']) ?>"><?= esc($tp['nama_produk']) ?></div>
                <div class="tp-qty"><?= number_format($tp['total_qty']) ?> pcs</div>
            </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<!-- ═══ TABEL TRANSAKSI ═══ -->
<div class="table-card" style="position:relative">
    <!-- Summary Bar -->
    <div class="summary-bar">
        <div class="sb-item"><span class="sk">Total Transaksi</span><span class="sv" id="sumTrx">—</span></div>
        <div class="sb-item"><span class="sk">Total Omzet</span><span class="sv" id="sumOmzet">—</span></div>
        <div class="sb-item"><span class="sk">Internal</span><span class="sv" id="sumInternal">—</span></div>
        <div class="sb-item"><span class="sk">TikTok</span><span class="sv" id="sumTiktok">—</span></div>
        <div class="sb-item"><span class="sk">Tunai</span><span class="sv" id="sumTunai">—</span></div>
        <div class="sb-item"><span class="sk">Transfer</span><span class="sv" id="sumTransfer">—</span></div>
        <div class="sb-item"><span class="sk">QRIS</span><span class="sv" id="sumQris">—</span></div>
        <div class="sb-item"><span class="sk">Diskon</span><span class="sv" id="sumDiskon">—</span></div>
    </div>

    <div class="table-head-bar">
        <div class="th-info">
            <i class="bi bi-list-ul" style="color:var(--blue)"></i>
            Riwayat Transaksi
            <span class="trx-count" id="trxCount">0 data</span>
        </div>
        <!-- Channel breakdown dari filter periode (diisi JS) -->
        <div id="channelBreakdownBadges" style="display:flex;gap:6px;flex-wrap:wrap;"></div>
    </div>

    <div class="table-wrap" style="position:relative">
        <div class="loading-overlay" id="tableLoader"><div class="spinner"></div></div>
        <table class="lp-table">
            <thead>
                <tr>
                    <th>No. Transaksi / Order ID</th>
                    <th>Waktu</th>
                    <th>Channel</th>
                    <th>Metode</th>
                    <th>Sumber</th>
                    <th>Item / Qty</th>
                    <th>Subtotal</th>
                    <th>Diskon</th>
                    <th>Total</th>
                    <th>Catatan</th>
                    <th></th>
                </tr>
            </thead>
            <tbody id="tableBody">
                <tr><td colspan="11" class="table-empty">
                    <i class="bi bi-hourglass-split"></i>
                    <p>Memuat data…</p>
                </td></tr>
            </tbody>
        </table>
    </div>

    <div class="paging-bar">
        <span id="pagingInfo" style="font-size:.76rem;color:var(--ink3)">—</span>
        <div class="paging-btns" id="pagingBtns"></div>
    </div>
</div>

<!-- Modal + Toast -->
<div id="detailModal" style="display:none"></div>
<div id="toastContainer"></div>

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

<?= $this->section('js') ?>
<script>
const BASE_URL = '<?= base_url() ?>';

let allRows   = [];
let curPage   = 1;
const PER_PAGE = 20;
let chartInst = null;

// ── Utils ──────────────────────────────────────────────────────────────
function rp(n) { return 'Rp ' + Math.round(n || 0).toLocaleString('id-ID'); }

function fmtDate(s) {
    if (!s) return '—';
    const d = new Date(s.replace(' ', 'T'));
    if (isNaN(d)) return s;
    return d.toLocaleDateString('id-ID', { day: '2-digit', month: 'short', year: 'numeric' })
         + ' ' + d.toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit' });
}

// ── Toast ───────────────────────────────────────────────────────────────
function showToast(msg, type = 'success', duration = 3500) {
    const wrap = document.getElementById('toastContainer');
    const el   = document.createElement('div');
    el.className = 'toast ' + type;
    const icon = type === 'success'
        ? '<i class="bi bi-check-circle-fill"></i>'
        : '<i class="bi bi-exclamation-triangle-fill"></i>';
    el.innerHTML = icon + '<span>' + msg + '</span>';
    wrap.appendChild(el);
    setTimeout(() => { el.classList.add('hide'); setTimeout(() => el.remove(), 300); }, duration);
}

// ── Badge helpers ───────────────────────────────────────────────────────
function chanBadge(c) {
    const map = {
        ecer:        ['chan-pos',      'Kasir POS'],
        reseller:    ['chan-reseller', 'Reseller'],
        maklon:      ['chan-maklon',   'Maklon'],
        marketplace: ['chan-online',   'Marketplace'],
    };
    const key  = (c || '').toLowerCase();
    const [cls, lbl] = map[key] || ['chan-pos', c];
    return `<span class="badge-chan ${cls}">${lbl}</span>`;
}

function metBadge(m) {
    if (!m) return '<span class="badge-met met-other">—</span>';
    const lower = m.toLowerCase();
    let cls = 'met-other';
    if (lower === 'tunai')                                          cls = 'met-tunai';
    else if (lower.includes('transfer') || lower.includes('bank')) cls = 'met-transfer';
    else if (lower === 'qris')                                      cls = 'met-qris';
    else if (lower === 'cod')                                       cls = 'met-cod';
    return `<span class="badge-met ${cls}">${m}</span>`;
}

function sourceBadge(source) {
    if (source === 'tiktok') return `<span class="badge-tiktok">TikTok</span>`;
    return `<span style="font-size:.65rem;color:var(--ink3)">Internal</span>`;
}

// ── Filter params ───────────────────────────────────────────────────────
function getFilterParams() {
    return new URLSearchParams({
        tgl_mulai: document.getElementById('tglMulai').value,
        tgl_akhir: document.getElementById('tglAkhir').value,
        channel:   document.getElementById('selChannel').value,
        metode:    document.getElementById('selMetode').value,
        search:    document.getElementById('srchInput').value.trim(),
    });
}

// ── Metode Bayar Dinamis ─────────────────────────────────────────────────
async function loadMetodeOptions() {
    const sel = document.getElementById('selMetode');
    sel.disabled = true;

    const labelMap = {
        'tunai':         '💵 Tunai',
        'transfer':      '🏦 Transfer',
        'Transfer Bank': '🏦 Transfer Bank',
        'Bank Transfer': '🏦 Bank Transfer',
        'qris':          '📱 QRIS',
        'QRIS':          '📱 QRIS',
        'cod':           '🚚 COD',
        'COD':           '🚚 COD',
    };

    try {
        const res  = await fetch(BASE_URL + 'laporan-penjualan/metode-list');
        const data = await res.json();

        sel.innerHTML = '<option value="">Semua Metode</option>';

        if (data.success && Array.isArray(data.data) && data.data.length > 0) {
            data.data.forEach(m => {
                const opt       = document.createElement('option');
                opt.value       = m;
                opt.textContent = labelMap[m] ?? ('💳 ' + m);
                sel.appendChild(opt);
            });
        } else {
            // Fallback
            const fallback = ['tunai','transfer','Transfer Bank','Bank Transfer','qris','COD'];
            fallback.forEach(m => {
                const opt = document.createElement('option');
                opt.value = m;
                opt.textContent = labelMap[m] ?? m;
                sel.appendChild(opt);
            });
        }
    } catch (e) {
        console.warn('Gagal memuat metode bayar, pakai fallback:', e);
        sel.innerHTML = `
            <option value="">Semua Metode</option>
            <option value="tunai">💵 Tunai</option>
            <option value="transfer">🏦 Transfer</option>
            <option value="Transfer Bank">🏦 Transfer Bank</option>
            <option value="Bank Transfer">🏦 Bank Transfer</option>
            <option value="qris">📱 QRIS</option>
            <option value="COD">🚚 COD</option>
        `;
    } finally {
        sel.disabled = false;
    }
}

// Highlight select jika ada nilai
document.addEventListener('change', e => {
    if (e.target.tagName === 'SELECT') {
        e.target.classList.toggle('has-value', e.target.value !== '');
    }
});

// ── Export ───────────────────────────────────────────────────────────────
function handleExport(e) {
    e.preventDefault();
    const btn      = document.getElementById('btnExport');
    const tglMulai = document.getElementById('tglMulai').value;
    const tglAkhir = document.getElementById('tglAkhir').value;

    if (!tglMulai || !tglAkhir) {
        showToast('Pilih rentang tanggal terlebih dahulu.', 'error'); return;
    }
    if (tglMulai > tglAkhir) {
        showToast('Tanggal mulai tidak boleh lebih besar dari tanggal akhir.', 'error'); return;
    }

    const params = new URLSearchParams({
        tgl_mulai: tglMulai,
        tgl_akhir: tglAkhir,
        channel:   document.getElementById('selChannel').value,
        metode:    document.getElementById('selMetode').value,
    });

    btn.classList.add('loading');
    btn.querySelector('.export-text').textContent = 'Menyiapkan file…';
    showToast('Sedang membuat file Excel, harap tunggu…', 'success', 5000);

    let iframe = document.getElementById('exportFrame');
    if (!iframe) {
        iframe = document.createElement('iframe');
        iframe.id    = 'exportFrame';
        iframe.style.display = 'none';
        document.body.appendChild(iframe);
    }
    iframe.src = BASE_URL + 'laporan-penjualan/export-xlsx?' + params.toString();

    setTimeout(() => {
        btn.classList.remove('loading');
        btn.querySelector('.export-text').textContent = 'Export Excel (.xlsx)';
    }, 5000);
}

// ── Load Data (AJAX utama) ───────────────────────────────────────────────
async function loadData() {
    document.getElementById('tableLoader').style.display = 'flex';
    document.getElementById('chartLoader').style.display = 'flex';

    try {
        const res  = await fetch(BASE_URL + 'laporan-penjualan/data?' + getFilterParams().toString());
        const data = await res.json();
        if (!data.success) throw new Error(data.error || 'Gagal memuat');

        allRows = data.rows || [];
        curPage = 1;

        renderTable();
        renderSummary(data.summary          || {});
        renderChart(data.chartData           || []);
        renderChannelBadges(data.channelBreakdown || []);

    } catch (e) {
        console.error(e);
        showToast('Gagal memuat data: ' + e.message, 'error');
        document.getElementById('tableBody').innerHTML =
            `<tr><td colspan="11" class="table-empty">
                <i class="bi bi-exclamation-triangle"></i><p>${e.message}</p>
            </td></tr>`;
    } finally {
        document.getElementById('tableLoader').style.display = 'none';
        document.getElementById('chartLoader').style.display = 'none';
    }
}

// ── Render Table ─────────────────────────────────────────────────────────
function renderTable() {
    const total = allRows.length;
    const pages = Math.ceil(total / PER_PAGE) || 1;
    if (curPage > pages) curPage = pages;

    const start = (curPage - 1) * PER_PAGE;
    const slice = allRows.slice(start, start + PER_PAGE);

    document.getElementById('trxCount').textContent = total + ' data';
    document.getElementById('pagingInfo').textContent =
        total === 0
            ? 'Tidak ada data'
            : `Menampilkan ${start + 1}–${Math.min(start + PER_PAGE, total)} dari ${total}`;

    if (!slice.length) {
        document.getElementById('tableBody').innerHTML =
            `<tr><td colspan="11" class="table-empty">
                <i class="bi bi-inbox"></i><p>Tidak ada transaksi pada periode ini</p>
            </td></tr>`;
        renderPaging(pages);
        return;
    }

    document.getElementById('tableBody').innerHTML = slice.map(r => `
        <tr>
            <td><span class="no-trx">${r.no_transaksi}</span></td>
            <td><span class="date-cell">${fmtDate(r.created_at)}</span></td>
            <td>${chanBadge(r.channel)}</td>
            <td>${metBadge(r.metode_bayar)}</td>
            <td>${sourceBadge(r.source)}</td>
            <td style="text-align:center;font-family:var(--mono);font-size:.75rem">
                ${r.jumlah_item ?? '—'} item / ${r.total_qty ?? 0} pcs
            </td>
            <td class="rp-cell">${rp(r.subtotal)}</td>
            <td style="font-family:var(--mono);font-size:.74rem;color:var(--amber)">
                ${r.diskon > 0 ? rp(r.diskon) : '—'}
            </td>
            <td class="rp-cell" style="color:var(--green)">${rp(r.total)}</td>
            <td style="max-width:140px;overflow:hidden;text-overflow:ellipsis;
                       color:var(--ink3);font-size:.74rem" title="${r.catatan || ''}">
                ${r.catatan || '—'}
            </td>
            <td>
                <button class="btn-detail"
                    onclick="showDetail('${r.source_id}','${r.source}')">
                    <i class="bi bi-eye"></i> Detail
                </button>
            </td>
        </tr>
    `).join('');

    renderPaging(pages);
}

// ── Pagination ────────────────────────────────────────────────────────────
function renderPaging(pages) {
    const btn = document.getElementById('pagingBtns');
    if (pages <= 1) { btn.innerHTML = ''; return; }
    let html = `<button onclick="goPage(${curPage - 1})" ${curPage === 1 ? 'disabled' : ''}>‹</button>`;
    for (let i = 1; i <= pages; i++) {
        if (pages > 7 && Math.abs(i - curPage) > 2 && i !== 1 && i !== pages) {
            if (i === 2 || i === pages - 1) html += `<button disabled>…</button>`;
            continue;
        }
        html += `<button class="${i === curPage ? 'active' : ''}" onclick="goPage(${i})">${i}</button>`;
    }
    html += `<button onclick="goPage(${curPage + 1})" ${curPage === pages ? 'disabled' : ''}>›</button>`;
    btn.innerHTML = html;
}
function goPage(p) { curPage = p; renderTable(); }

// ── Summary Bar ───────────────────────────────────────────────────────────
function renderSummary(s) {
    document.getElementById('sumTrx').textContent      = parseInt(s.total_transaksi || 0).toLocaleString('id-ID') + ' trx';
    document.getElementById('sumOmzet').textContent    = rp(s.total_omzet);
    document.getElementById('sumInternal').textContent = rp(s.omzet_internal);
    document.getElementById('sumTiktok').textContent   = rp(s.omzet_tiktok);
    document.getElementById('sumTunai').textContent    = rp(s.kas_tunai);
    document.getElementById('sumTransfer').textContent = rp(s.transfer);
    document.getElementById('sumQris').textContent     = rp(s.qris);
    document.getElementById('sumDiskon').textContent   = rp(s.total_diskon);
}

// ── Channel Breakdown Badges ──────────────────────────────────────────────
function renderChannelBadges(breakdown) {
    const wrap = document.getElementById('channelBreakdownBadges');
    if (!breakdown || breakdown.length === 0) { wrap.innerHTML = ''; return; }

    const colors = { Ecer:'#2563eb', Reseller:'#7c3aed', Maklon:'#d97706', marketplace:'#059669' };
    const labels = { Ecer:'Kasir POS', Reseller:'Reseller', Maklon:'Maklon', marketplace:'Marketplace' };

    wrap.innerHTML = breakdown.map(ch => {
        const color = colors[ch.channel] || '#6b7280';
        const label = labels[ch.channel] || ch.channel;
        return `<span style="font-size:.67rem;font-weight:700;padding:3px 9px;border-radius:5px;
                    background:${color}18;color:${color};border:1px solid ${color}40">
                    ${label}: ${parseInt(ch.total_trx).toLocaleString('id-ID')} trx
                </span>`;
    }).join('');
}

// ── Chart (multi-dataset) ─────────────────────────────────────────────────
function renderChart(data) {
    const ctx    = document.getElementById('omzetChart').getContext('2d');
    const labels = data.map(d => {
        const dt = new Date(d.tgl);
        return dt.toLocaleDateString('id-ID', { day: '2-digit', month: 'short' });
    });

    if (chartInst) chartInst.destroy();

    chartInst = new Chart(ctx, {
        type: 'bar',
        data: {
            labels,
            datasets: [
                {
                    label:           'Total',
                    data:            data.map(d => parseFloat(d.omzet || 0)),
                    backgroundColor: 'rgba(37,99,235,.18)',
                    borderColor:     '#2563eb',
                    borderWidth:     2,
                    borderRadius:    6,
                    order:           2,
                },
                {
                    label:           'Internal',
                    data:            data.map(d => parseFloat(d.omzet_internal || 0)),
                    backgroundColor: 'rgba(124,58,237,.55)',
                    borderColor:     '#7c3aed',
                    borderWidth:     0,
                    borderRadius:    4,
                    order:           1,
                },
                {
                    label:           'TikTok',
                    data:            data.map(d => parseFloat(d.omzet_tiktok || 0)),
                    backgroundColor: 'rgba(233,30,140,.55)',
                    borderColor:     '#e91e8c',
                    borderWidth:     0,
                    borderRadius:    4,
                    order:           1,
                },
            ]
        },
        options: {
            responsive: true,
            interaction: { mode: 'index', intersect: false },
            plugins: {
                legend: {
                    display: false  // pakai legend custom di HTML
                },
                tooltip: {
                    callbacks: {
                        label: ctx => ' ' + ctx.dataset.label + ': ' + rp(ctx.parsed.y)
                    }
                }
            },
            scales: {
                y: {
                    ticks: {
                        callback: v => 'Rp ' + (v / 1000).toFixed(0) + 'K',
                        font: { family: 'DM Mono', size: 10 },
                        color: '#6b7280',
                    },
                    grid: { color: 'rgba(0,0,0,.05)' }
                },
                x: {
                    ticks: { font: { family: 'DM Mono', size: 10 }, color: '#6b7280' },
                    grid:  { display: false }
                }
            }
        }
    });
}

// ── Detail Modal ──────────────────────────────────────────────────────────
async function showDetail(id, source) {
    const modal = document.getElementById('detailModal');
    modal.style.display = '';
    modal.innerHTML = `
        <div class="modal-backdrop">
            <div class="modal-box" style="display:flex;align-items:center;justify-content:center;min-height:200px">
                <div class="spinner"></div>
            </div>
        </div>`;

    try {
        const res  = await fetch(BASE_URL + 'laporan-penjualan/detail/' + encodeURIComponent(id));
        const data = await res.json();
        if (!data.success) throw new Error(data.error);

        const h     = data.header;
        const items = data.items || [];

        const isTiktok = (source === 'tiktok' || h.source === 'tiktok');

        const extraTiktok = isTiktok ? `
            <div class="mm-row">
                <span class="mk">Buyer</span>
                <span class="mv">${h.buyer_username || '—'}</span>
            </div>
            <div class="mm-row">
                <span class="mk">Status Pesanan</span>
                <span class="mv">${h.status_pesanan || '—'}</span>
            </div>
            <div class="mm-row">
                <span class="mk">Kurir</span>
                <span class="mv">${h.shipping_provider || '—'}</span>
            </div>
            <div class="mm-row">
                <span class="mk">No. Resi</span>
                <span class="mv">${h.tracking_id || '—'}</span>
            </div>` : '';

        const sourcLabel = isTiktok
            ? '<span class="badge-tiktok" style="font-size:.7rem;padding:2px 8px">TikTok</span>'
            : '<span style="font-size:.72rem;color:var(--ink3)">Internal</span>';

        modal.innerHTML = `
        <div class="modal-backdrop" id="detailBackdrop">
            <div class="modal-box">
                <div class="modal-title">
                    <i class="bi bi-receipt" style="color:var(--blue)"></i>
                    Detail Transaksi ${sourcLabel}
                </div>
                <div class="modal-no">${h.no_transaksi}</div>

                <div class="modal-meta">
                    <div class="mm-row">
                        <span class="mk">Waktu</span>
                        <span class="mv">${fmtDate(h.created_at)}</span>
                    </div>
                    <div class="mm-row">
                        <span class="mk">Channel</span>
                        <span class="mv">${h.channel}</span>
                    </div>
                    <div class="mm-row">
                        <span class="mk">Metode</span>
                        <span class="mv">${h.metode_bayar}</span>
                    </div>
                    <div class="mm-row">
                        <span class="mk">Subtotal</span>
                        <span class="mv">${rp(h.subtotal)}</span>
                    </div>
                    <div class="mm-row">
                        <span class="mk">Bayar</span>
                        <span class="mv">${rp(h.bayar)}</span>
                    </div>
                    <div class="mm-row">
                        <span class="mk">Kembalian</span>
                        <span class="mv">${rp(h.kembalian)}</span>
                    </div>
                    <div class="mm-row" style="grid-column:1/-1">
                        <span class="mk">Catatan</span>
                        <span class="mv" style="font-family:var(--sans);font-weight:500">${h.catatan || '—'}</span>
                    </div>
                    ${extraTiktok}
                </div>

                <div class="modal-items-title">Item Produk (${items.length})</div>
                <table class="modal-items-table">
                    <thead>
                        <tr>
                            <th>Produk</th>
                            <th style="text-align:center">Qty</th>
                            <th style="text-align:right">Harga Satuan</th>
                            ${isTiktok ? '<th style="text-align:right">Diskon</th>' : ''}
                            <th style="text-align:right">Subtotal</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${items.length === 0
                            ? `<tr><td colspan="${isTiktok ? 5 : 4}" style="text-align:center;color:var(--ink3);padding:16px">
                                Tidak ada item</td></tr>`
                            : items.map(it => {
                                // Field names sesuai DB schema
                                const qty        = parseInt(it.qty ?? it.quantity ?? 0);
                                const qtyRetur   = parseInt(it.sku_quantity_of_return ?? 0);
                                const qtyNet     = parseInt(it.qty_net ?? (qty - qtyRetur));
                                const harga      = parseFloat(it.harga_satuan ?? it.harga_jual ?? it.sku_unit_original_price ?? 0);
                                const subtotal   = parseFloat(it.subtotal ?? it.sku_subtotal_after_discount ?? 0);
                                const nama       = it.nama_produk ?? it.nama_produk_raw ?? '—';
                                const kode       = it.kode_produk ?? it.seller_sku ?? '';
                                const variasi    = it.variasi_raw ?? it.kombinasi_produk ?? '';
                                const diskonPlat = parseFloat(it.sku_platform_discount ?? 0);
                                const diskonSell = parseFloat(it.sku_seller_discount    ?? 0);
                                const totalDiskon = diskonPlat + diskonSell;
                                const settlement  = parseFloat(it.sku_settlement_amt ?? 0);

                                const qtyDisplay = qtyRetur > 0
                                    ? `<span style="color:var(--ink)">${qtyNet}</span>
                                       <span style="font-size:.62rem;color:var(--red);display:block">
                                           (${qty} - retur ${qtyRetur})
                                       </span>`
                                    : `${qty}`;

                                const diskonCell = isTiktok
                                    ? `<td style="text-align:right;font-family:var(--mono);font-size:.72rem;color:var(--amber)">
                                           ${totalDiskon > 0
                                               ? `<span title="Platform: ${rp(diskonPlat)} | Seller: ${rp(diskonSell)}">
                                                      - ${rp(totalDiskon)}
                                                  </span>`
                                               : '—'}
                                       </td>`
                                    : '';

                                return `<tr>
                                    <td>
                                        <div style="font-weight:600;font-size:.78rem">${nama}</div>
                                        ${kode    ? `<div style="font-size:.65rem;color:var(--blue);font-family:var(--mono)">${kode}</div>` : ''}
                                        ${variasi ? `<div style="font-size:.65rem;color:var(--ink3)">${variasi}</div>` : ''}
                                        ${settlement > 0 && isTiktok
                                            ? `<div style="font-size:.62rem;color:var(--green);font-family:var(--mono)">
                                                   settle: ${rp(settlement)}
                                               </div>`
                                            : ''}
                                    </td>
                                    <td style="text-align:center;font-family:var(--mono);font-weight:700;vertical-align:top">
                                        ${qtyDisplay}
                                    </td>
                                    <td style="text-align:right;font-family:var(--mono);font-size:.76rem">${rp(harga)}</td>
                                    ${diskonCell}
                                    <td style="text-align:right;font-family:var(--mono);font-weight:700">${rp(subtotal)}</td>
                                </tr>`;
                            }).join('')
                        }
                    </tbody>
                </table>

                ${h.diskon > 0 ? `
                <div style="display:flex;justify-content:space-between;font-size:.8rem;
                            padding:4px 0;color:var(--amber)">
                    <span>Diskon (Platform + Seller)</span>
                    <span style="font-family:var(--mono);font-weight:600">- ${rp(h.diskon)}</span>
                </div>` : ''}

                <div class="modal-total-row">
                    <span>Total</span>
                    <span class="mv">${rp(h.total)}</span>
                </div>

                <button class="modal-close" onclick="closeDetail()">
                    <i class="bi bi-x-lg"></i> Tutup
                </button>
            </div>
        </div>`;

        document.getElementById('detailBackdrop').addEventListener('click', e => {
            if (e.target === e.currentTarget) closeDetail();
        });

    } catch (e) {
        modal.innerHTML = `
        <div class="modal-backdrop">
            <div class="modal-box" style="text-align:center;padding:40px">
                <i class="bi bi-exclamation-triangle" style="font-size:2rem;color:var(--red)"></i>
                <p style="margin-top:12px;color:var(--ink3)">${e.message}</p>
                <button class="modal-close" onclick="closeDetail()" style="margin-top:16px">Tutup</button>
            </div>
        </div>`;
    }
}

function closeDetail() {
    document.getElementById('detailModal').style.display = 'none';
    document.getElementById('detailModal').innerHTML     = '';
}

// ── Reset Filter ───────────────────────────────────────────────────────────
function resetFilter() {
    document.getElementById('tglMulai').value   = '<?= date('Y-m-01') ?>';
    document.getElementById('tglAkhir').value   = '<?= date('Y-m-d') ?>';
    document.getElementById('selChannel').value = '';
    document.getElementById('selMetode').value  = '';
    document.getElementById('srchInput').value  = '';
    document.querySelectorAll('select.has-value').forEach(s => s.classList.remove('has-value'));
    loadData();
}

// Enter di search field → langsung filter
document.getElementById('srchInput').addEventListener('keydown', e => {
    if (e.key === 'Enter') loadData();
});

// ── Keyboard shortcut: Escape tutup modal ──────────────────────────────────
document.addEventListener('keydown', e => {
    if (e.key === 'Escape') closeDetail();
});

// ── Init ───────────────────────────────────────────────────────────────────
loadMetodeOptions().then(() => loadData());
</script>
<?= $this->endSection() ?>