<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Input Penjualan — Loves Semprong</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@tabler/icons-webfont@latest/tabler-icons.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;600&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/cleave.js/1.6.0/cleave.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <style>
            select:disabled {
            background: #f1f5f9;
            color: #94a3b8;
            opacity: 1;
        }
        
        :root {
            --ink:       #0f172a;
            --ink-2:     #334155;
            --ink-3:     #64748b;
            --surface:   #ffffff;
            --surface-2: #f8fafc;
            --surface-3: #f1f5f9;
            --border:    #e2e8f0;
            --blue:      #1d4ed8;
            --blue-soft: #eff6ff;
            --r:         10px;
            --mono:      'JetBrains Mono', monospace;
        }
        * { box-sizing: border-box; }
        body { background: var(--surface-3); font-family: 'Inter', sans-serif; font-size: 12px; color: var(--ink); }

        /* ── CARDS ── */
        .form-card {
            background: var(--surface);
            border: 1px solid var(--border);
            border-radius: var(--r);
            overflow: hidden;
            margin-bottom: 12px;
        }
        .form-card-header {
            background: var(--ink);
            color: #fff;
            padding: 9px 16px;
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: .05em;
            display: flex;
            align-items: center;
            gap: 7px;
        }
        .form-card-header i { font-size: 14px; }
        .form-card-body { padding: 14px 16px; }

        /* ── SECTION LABEL ── */
        .section-label {
            font-size: 10px;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: .06em;
            color: var(--ink-3);
            padding: 4px 0 6px;
            border-bottom: 1px solid var(--border);
            margin-bottom: 10px;
            margin-top: 4px;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        /* ── TIPE PEMBELIAN BUTTONS ── */
        .tipe-btn {
            border: 1.5px solid var(--border);
            border-radius: 8px;
            padding: 8px 10px;
            cursor: pointer;
            text-align: center;
            transition: all .15s;
            background: var(--surface);
        }
        .tipe-btn:hover { border-color: var(--blue); background: var(--blue-soft); }
        .tipe-btn.active { border-color: var(--blue); background: var(--blue); color: white; }
        .tipe-btn .code { font-size: 12px; font-weight: 700; font-family: var(--mono); }
        .tipe-btn .label { font-size: 9px; font-weight: 600; margin-top: 2px; }
        .tipe-btn .sub { font-size: 8px; opacity: .75; }
        .tipe-btn.disabled-tipe { opacity: .35; cursor: not-allowed; pointer-events: none; border-color: #e2e8f0; background: #f8fafc; }

        /* ── PRODUK LIST ── */
        .produk-card {
            border: 1px solid var(--border);
            border-radius: 8px;
            padding: 10px 12px;
            background: var(--surface);
            margin-bottom: 8px;
        }
        .kategori-title {
            font-size: 10px;
            font-weight: 700;
            text-transform: uppercase;
            color: var(--ink-3);
            margin-bottom: 6px;
            letter-spacing: .04em;
        }
        .produk-row {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 4px 0;
            border-bottom: 1px solid var(--surface-3);
        }
        .produk-row:last-child { border-bottom: none; }
        .produk-nama { font-size: 11px; color: var(--ink-2); flex: 1; }
        .produk-harga { font-size: 10px; color: var(--ink-3); margin: 0 8px; white-space: nowrap; font-family: var(--mono); }
        .qty-ctrl { display: flex; align-items: center; gap: 4px; }
        .qty-ctrl button {
            width: 22px; height: 22px;
            border: 1px solid var(--border);
            border-radius: 5px;
            background: var(--surface);
            font-weight: 700;
            cursor: pointer;
            font-size: 14px;
            line-height: 1;
            display: flex; align-items: center; justify-content: center;
            color: var(--ink-2);
        }
        .qty-ctrl button:hover { background: var(--surface-3); }
        .qty-ctrl input {
            width: 40px; text-align: center;
            border: 1px solid var(--border);
            border-radius: 5px;
            padding: 2px 0;
            font-size: 12px;
            font-weight: 600;
            font-family: var(--mono);
        }
        .qty-ctrl input:focus { outline: none; border-color: var(--blue); }
        .selected-produk { background: var(--blue-soft); border-color: #bfdbfe !important; }
        .selected-produk .produk-nama { color: var(--blue); font-weight: 600; }

        /* ── SEARCH ── */
        .search-produk {
            border: 1.5px solid var(--border);
            border-radius: 7px;
            padding: 6px 10px;
            width: 100%;
            font-size: 12px;
            margin-bottom: 8px;
            font-family: 'Inter', sans-serif;
            outline: none;
            transition: border-color .15s;
        }
        .search-produk:focus { border-color: var(--blue); }

        /* ── KATEGORI TABS ── */
        .kategori-tab {
            font-size: 10px;
            padding: 3px 10px;
            border-radius: 20px;
            cursor: pointer;
            border: 1px solid var(--border);
            background: var(--surface);
            color: var(--ink-3);
            font-weight: 500;
            transition: all .15s;
        }
        .kategori-tab:hover { background: var(--surface-3); color: var(--ink); }
        .kategori-tab.active { background: var(--ink); color: white; border-color: var(--ink); }

        /* ── CART ── */
        .cart-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 5px 0;
            border-bottom: 1px solid var(--surface-3);
            font-size: 11px;
        }
        .cart-item:last-child { border-bottom: none; }
        .cart-total {
            font-weight: 700;
            font-size: 13px;
            color: var(--blue);
            margin-top: 8px;
            padding-top: 8px;
            border-top: 1.5px solid var(--border);
        }

        /* ── TABS ── */
        .nav-tabs .nav-link {
            font-size: 12px;
            font-weight: 600;
            border-radius: 8px 8px 0 0;
            color: var(--ink-3);
        }
        .nav-tabs .nav-link.active { background: var(--ink); color: white; border-color: var(--ink); }
        .nav-tabs .nav-link:not(.active):hover { color: var(--ink); background: var(--surface-3); }

        /* ── HISTORY TABLE ── */
        .tbl-history { font-size: 11px; width: 100%; border-collapse: collapse; }
        .tbl-history th {
            background: var(--ink);
            color: white;
            font-size: 10px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: .04em;
            padding: 8px 10px;
            white-space: nowrap;
        }
        .tbl-history td { padding: 8px 10px; border-bottom: 1px solid var(--surface-3); vertical-align: middle; }
        .tbl-history tr:hover td { background: var(--surface-2); }
        .tbl-history tr:last-child td { border-bottom: none; }

        /* ── STATUS BADGE ── */
        .s-badge {
            font-size: 9px;
            font-weight: 700;
            padding: 2px 8px;
            border-radius: 20px;
            text-transform: uppercase;
            letter-spacing: .03em;
        }

        /* ── SUBMIT BTN ── */
        .btn-submit {
            background: var(--blue);
            color: white;
            border: none;
            width: 100%;
            padding: 11px;
            border-radius: 8px;
            font-size: 13px;
            font-weight: 700;
            cursor: pointer;
            font-family: 'Inter', sans-serif;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 7px;
            transition: opacity .15s;
        }
        .btn-submit:hover { opacity: .9; }
    </style>
</head>
<body>
@include('layouts.navbar')

<div class="container-fluid px-3 pb-5">
    <div class="row justify-content-center">
        <div class="col-xl-11">

            {{-- PAGE HEADER --}}
            <div class="d-flex justify-content-between align-items-center py-3 mb-1">
                <div>
                    <h5 style="font-size:16px;font-weight:700;margin:0;color:var(--ink)">Input Penjualan</h5>
                    <div style="font-size:11px;color:var(--ink-3)">{{ date('d F Y') }}</div>
                </div>
            </div>

            @if(session('success'))
                <div class="alert border-0 py-2 mb-3" style="background:#f0fdf4;color:#166534;font-size:12px;border-radius:8px">
                    <i class="ti ti-circle-check" style="font-size:14px;vertical-align:-2px"></i> {{ session('success') }}
                </div>
            @endif
            @if(session('error'))
                <div class="alert border-0 py-2 mb-3" style="background:#fef2f2;color:#991b1b;font-size:12px;border-radius:8px">
                    <i class="ti ti-alert-circle" style="font-size:14px;vertical-align:-2px"></i> {{ session('error') }}
                </div>
            @endif

            {{-- TABS --}}
            <ul class="nav nav-tabs mb-0" id="mainTab">
                <li class="nav-item">
                    <button class="nav-link {{ request('tab') == 'riwayat' ? '' : 'active' }}" data-bs-toggle="tab" data-bs-target="#tabForm">
                        <i class="ti ti-pencil" style="font-size:13px;vertical-align:-2px;margin-right:4px"></i> Input Data
                    </button>
                </li>
                <li class="nav-item">
                    <button class="nav-link {{ request('tab') == 'riwayat' ? 'active' : '' }}" data-bs-toggle="tab" data-bs-target="#tabRiwayat">
                        <i class="ti ti-list" style="font-size:13px;vertical-align:-2px;margin-right:4px"></i> Riwayat Input
                        <span style="background:#475569;color:#fff;font-size:9px;padding:1px 6px;border-radius:10px;margin-left:4px">{{ count($history) }}</span>
                    </button>
                </li>
            </ul>

            <div class="tab-content">

            {{-- TAB FORM --}}
            <div class="tab-pane fade {{ request('tab') == 'riwayat' ? '' : 'show active' }}" id="tabForm">
            <form action="/simpan" method="POST" id="formInput">
                @csrf
                <input type="hidden" name="admin_id" value="{{ auth()->user()->id }}">

                <div class="row g-3 pt-3">

                    {{-- KOLOM KIRI: Info + Produk --}}
                    <div class="col-lg-7">

                        {{-- Info Dasar --}}
                        <div class="form-card">
                            <div class="form-card-header">
                                <i class="ti ti-info-circle"></i> Informasi Dasar
                            </div>
                            <div class="form-card-body">
                                <div class="row g-2">
                                    <div class="col-6 col-md-3">
                                        <label class="form-label fw-bold mb-1" style="font-size:11px">Nama CS <span style="color:#dc2626">*</span></label>
                                        <select name="nama_cs" class="form-select form-select-sm" required>
                                            <option value="" disabled selected>-- Pilih --</option>
                                            @foreach($csNames as $cs)
                                                <option value="{{ $cs->nama }}">{{ $cs->nama }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col-6 col-md-3">
                                        <label class="form-label fw-bold mb-1" style="font-size:11px">Tanggal <span style="color:#dc2626">*</span></label>
                                        <input type="date" name="tgl" class="form-control form-control-sm" value="{{ date('Y-m-d') }}" required>
                                    </div>
                                    <div class="col-6 col-md-3">
                                        <label class="form-label fw-bold mb-1" style="font-size:11px">Channel <span style="color:#dc2626">*</span></label>
                                        <select name="channel_id" class="form-select form-select-sm" required onchange="updateTipePembelian(this)">
                                            <option value="" disabled selected>-- Pilih --</option>
                                            @foreach($channels as $ch)
                                                <option value="{{ $ch->id }}" data-nama="{{ strtolower($ch->nama_channel) }}">{{ $ch->nama_channel }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col-6 col-md-3">
                                        <label class="form-label fw-bold mb-1" style="font-size:11px">Status Bayar</label>
                                        <select name="status_bayar" class="form-select form-select-sm">
                                            <option value="">-- Pilih --</option>
                                            @foreach(['Success','Pending','Transfer'] as $sb)
                                                <option value="{{ $sb }}">{{ $sb }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>

                        {{-- Tipe Pembelian --}}
                        <div class="form-card">
                            <div class="form-card-header">
                                <i class="ti ti-tag"></i> Tipe Pembelian <span style="color:#f87171;margin-left:2px">*</span>
                            </div>
                            <div class="form-card-body">
                                <input type="hidden" name="tipe_pembelian" id="tipe_val">
                                <div class="row g-2">
                                    @foreach([
                                        ['NL-CS', 'New Leads', 'Harga Customer', true],
                                        ['NL-RS', 'New Leads', 'Harga Reseller', true],
                                        ['NEW',   'New', 'Customer Baru', false],
                                        ['RC-CS', 'Repeat Customer', 'Harga Customer', true],
                                        ['RC-RS', 'Repeat Customer', 'Harga Reseller', true],
                                        ['REPEAT','Repeat', 'Customer Lama', false],
                                    ] as [$kode, $label, $sub, $qontakOnly])
                                    <div class="col-4">
                                        <div class="tipe-btn {{ $qontakOnly ? 'qontak-only' : '' }}"
                                             onclick="pilihTipe('{{ $kode }}')"
                                             id="tipe_{{ $kode }}"
                                             title="{{ $qontakOnly ? 'Hanya untuk channel Qontak/BOT' : '' }}">
                                            <div class="code">{{ $kode }}</div>
                                            <div class="label">{{ $label }}</div>
                                            <div class="sub">{{ $sub }}</div>
                                        </div>
                                    </div>
                                    @endforeach
                                </div>
                            </div>
                        </div>

                        {{-- Pilih Produk --}}
                        <div class="form-card">
                            <div class="form-card-header">
                                <i class="ti ti-package"></i> Pilih Produk
                            </div>
                            <div class="form-card-body">
                                <input type="text" class="search-produk" placeholder="Cari nama produk..." id="searchProduk" oninput="filterProduk(this.value)">
                                <div class="d-flex flex-wrap gap-1 mb-2" id="tabKategori">
                                    <span class="kategori-tab active" onclick="filterKategori('', this)">Semua</span>
                                    @foreach($labelKategori as $k => $label)
                                        @if(isset($products[$k]))
                                        <span class="kategori-tab" onclick="filterKategori('{{ $k }}', this)">{{ $label }}</span>
                                        @endif
                                    @endforeach
                                </div>
                                <div style="max-height:340px;overflow-y:auto" id="produkList">
                                    @foreach($labelKategori as $k => $label)
                                        @if(isset($products[$k]))
                                        <div class="produk-card" data-kategori="{{ $k }}">
                                            <div class="kategori-title">{{ $label }}</div>
                                            @foreach($products[$k] as $p)
                                            <div class="produk-row" id="row_{{ $p->kode }}" data-nama="{{ strtolower($p->nama) }}">
                                                <span class="produk-nama">{{ $p->nama }}</span>
                                                <span class="produk-harga" id="harga_label_{{ $p->kode }}">{{ $p->harga > 0 ? 'Rp'.number_format($p->harga,0,',','.') : '-' }}</span>
                                                <div class="qty-ctrl">
                                                    <button type="button" onclick="changeQty('{{ $p->kode }}', -1)">−</button>
                                                    <input type="number" id="qty_{{ $p->kode }}" name="qty_produk[{{ $p->kode }}]"
                                                           value="0" min="0"
                                                           data-harga="{{ $p->harga }}"
                                                           data-harga-p1="{{ $p->harga_p1 ?? 0 }}"
                                                           data-harga-p2="{{ $p->harga_p2 ?? 0 }}"
                                                           data-harga-p3="{{ $p->harga_p3 ?? 0 }}"
                                                           data-min-p1="{{ $p->min_p1 ?? 0 }}"
                                                           data-min-p2="{{ $p->min_p2 ?? 0 }}"
                                                           data-min-p3="{{ $p->min_p3 ?? 0 }}"
                                                           data-tipe="{{ $p->tipe_harga ?? 'other' }}"
                                                           data-konversi="{{ $p->konversi_toples ?? 0 }}"
                                                           data-nama="{{ $p->nama }}"
                                                           onchange="updateCart()" oninput="updateCart()">
                                                    <button type="button" onclick="changeQty('{{ $p->kode }}', 1)">+</button>
                                                </div>
                                            </div>
                                            @endforeach
                                        </div>
                                        @endif
                                    @endforeach
                                </div>
                            </div>
                        </div>

                        {{-- CART --}}
                        <div class="form-card">
                            <div class="form-card-header">
                                <i class="ti ti-shopping-cart"></i> Keranjang Pesanan
                            </div>
                            <div class="form-card-body">
                                <div id="cartEmpty" class="text-center py-3" style="font-size:11px;color:var(--ink-3)">
                                    <i class="ti ti-shopping-cart-off" style="font-size:24px;display:block;margin-bottom:4px;opacity:.4"></i>
                                    Belum ada produk dipilih
                                </div>

                                {{-- TIER INDICATOR --}}
                                <div id="tierIndicator" style="display:none;margin-bottom:10px">
                                    <div style="font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:#64748b;margin-bottom:6px">Status Tier</div>
                                    <div style="display:flex;gap:6px;flex-wrap:wrap">
                                        <div id="tierToples" style="flex:1;background:#f8fafc;border:1px solid #e2e8f0;border-radius:7px;padding:6px 10px;font-size:10px">
                                            <div style="color:#64748b;margin-bottom:2px">🧁 Toples</div>
                                            <div id="tierToplesVal" style="font-weight:700;color:#0f172a">0 toples</div>
                                            <div id="tierToplesLabel" style="font-size:9px;margin-top:2px"></div>
                                        </div>
                                        <div id="tierPouch" style="flex:1;background:#f8fafc;border:1px solid #e2e8f0;border-radius:7px;padding:6px 10px;font-size:10px">
                                            <div style="color:#64748b;margin-bottom:2px">👜 Pouch</div>
                                            <div id="tierPouchVal" style="font-weight:700;color:#0f172a">0 pcs</div>
                                            <div id="tierPouchLabel" style="font-size:9px;margin-top:2px"></div>
                                        </div>
                                    </div>
                                </div>

                                <div id="cartItems" style="display:none;max-height:160px;overflow-y:auto"></div>
                                <div class="cart-total d-flex justify-content-between" id="cartTotal" style="display:none!important">
                                    <span>Total GMV</span>
                                    <span id="cartTotalVal">Rp 0</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    {{-- KOLOM KANAN: Order Info --}}
                    <div class="col-lg-5">

                        {{-- Nominal & Pengiriman --}}
                        <div class="form-card">
                            <div class="form-card-header">
                                <i class="ti ti-cash"></i> Nominal & Pengiriman
                            </div>
                            <div class="form-card-body">
                                <div class="row g-2">
                                    <div class="col-12">
                                        <label class="fw-bold mb-1" style="font-size:11px">Nominal GMV <span style="color:#dc2626">*</span></label>
                                        <div class="input-group input-group-sm">
                                            <span class="input-group-text" style="background:var(--blue);color:#fff;border-color:var(--blue)">Rp</span>
                                            <input type="text" id="nominal_tampilan" class="form-control fw-bold" placeholder="0" required>
                                            <input type="hidden" name="nominal_gmv" id="nominal_asli">
                                        </div>
                                    </div>
                                    <div class="col-6">
                                        <label class="fw-bold mb-1" style="font-size:11px">Biaya Kirim</label>
                                        <div class="input-group input-group-sm">
                                            <span class="input-group-text">Rp</span>
                                            <input type="text" id="kirim_tampilan" class="form-control" placeholder="0">
                                            <input type="hidden" name="biaya_kirim" id="kirim_asli">
                                        </div>
                                    </div>
                                    <div class="col-6">
                                        <label class="fw-bold mb-1" style="font-size:11px">Grand Total</label>
                                        <div class="input-group input-group-sm">
                                            <span class="input-group-text">Rp</span>
                                            <input type="text" id="grand_total_tampil" class="form-control fw-bold" style="background:var(--surface-2);color:var(--blue)" readonly>
                                        </div>
                                    </div>
                                    <div class="col-6">
                                        <label class="fw-bold mb-1" style="font-size:11px">Jasa Kirim</label>
                                        <select name="jasa_kirim" class="form-select form-select-sm">
                                            <option value="">-- Pilih --</option>
                                            @foreach(['Driver Internal - Pusat','NCS'] as $jk)
                                                <option>{{ $jk }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>

                        {{-- Info Pemesan --}}
                        <div class="form-card">
                            <div class="form-card-header">
                                <i class="ti ti-user"></i> Info Pemesan
                            </div>
                            <div class="form-card-body">
                                <div class="row g-2">
                                    <div class="col-6">
                                        <label class="fw-bold mb-1" style="font-size:11px">Nama Pemesan</label>
                                        <input type="text" name="nama_pemesan" class="form-control form-control-sm" placeholder="Nama lengkap">
                                    </div>
                                    <div class="col-6">
                                        <label class="fw-bold mb-1" style="font-size:11px">No Telp Pemesan</label>
                                        <input type="text" name="no_telp_pemesan" class="form-control form-control-sm" placeholder="08xx">
                                    </div>
                                    <div class="col-6">
                                        <label class="fw-bold mb-1" style="font-size:11px">Nama Penerima</label>
                                        <input type="text" name="nama_penerima" class="form-control form-control-sm" placeholder="Jika berbeda">
                                    </div>
                                    <div class="col-6">
                                        <label class="fw-bold mb-1" style="font-size:11px">No Telp Penerima</label>
                                        <input type="text" name="no_telp_penerima" class="form-control form-control-sm" placeholder="08xx">
                                    </div>
                                    <div class="col-12">
                                        <label class="fw-bold mb-1" style="font-size:11px">Nama Transfer</label>
                                        <input type="text" name="nama_transfer" class="form-control form-control-sm" placeholder="Nama transfer">
                                    </div>
                                </div>
                            </div>
                        </div>

                        {{-- Alamat Pengiriman --}}
                        <div class="form-card">
                            <div class="form-card-header">
                                <i class="ti ti-map-pin"></i> Alamat Pengiriman
                            </div>
                            <div class="form-card-body">
                                <div class="row g-2">
                                    <div class="col-12">
                                        <label class="fw-bold mb-1" style="font-size:11px">Alamat Lengkap</label>
                                        <textarea name="alamat" class="form-control form-control-sm" rows="2" placeholder="Jl. ..."></textarea>
                                    </div>
                        {{-- Provinsi --}}
                        <div class="col-6">
                            <label class="fw-bold mb-1" style="font-size:11px">Provinsi</label>
                            <select id="sel_provinsi" class="form-control form-control-sm">
                                 <option value="">-- Pilih Provinsi --</option>
                            </select>
                            <input type="hidden" name="provinsi" id="val_provinsi">
                        </div>

                        {{-- Kota/Kab --}}
                        <div class="col-6">
                            <label class="fw-bold mb-1" style="font-size:11px">Kota/Kab</label>
                            <select id="sel_kota" class="form-control form-control-sm" disabled>
                                <option value="">-- Pilih Kota/Kab --</option>
                            </select>
                            <input type="hidden" name="kota" id="val_kota">
                        </div>

                        {{-- Kecamatan --}}
                        <div class="col-6">
                            <label class="fw-bold mb-1" style="font-size:11px">Kecamatan</label>
                            <select id="sel_kecamatan" class="form-control form-control-sm" disabled>
                                <option value="">-- Pilih Kecamatan --</option>
                            </select>
                            <input type="hidden" name="kecamatan" id="val_kecamatan">
                        </div>

                        {{-- Kelurahan --}}
                        <div class="col-6">
                            <label class="fw-bold mb-1" style="font-size:11px">Kelurahan</label>
                            <select id="sel_kelurahan" class="form-control form-control-sm" disabled>
                                <option value="">-- Pilih Kelurahan --</option>
                            </select>
                            <input type="hidden" name="kelurahan" id="val_kelurahan">
                        </div>
                                    <div class="col-6">
                                        <label class="fw-bold mb-1" style="font-size:11px">Nomor Resi</label>
                                        <input type="text" name="nomor_resi" class="form-control form-control-sm" placeholder="Isi setelah kirim">
                                    </div>
                                    <div class="col-6">
                                        <label class="fw-bold mb-1" style="font-size:11px">Catatan</label>
                                        <input type="text" name="catatan" class="form-control form-control-sm" placeholder="Catatan tambahan">
                                    </div>
                                </div>
                            </div>
                        </div>

                        <button type="submit" class="btn-submit">
                            <i class="ti ti-device-floppy" style="font-size:16px"></i> Simpan Data Penjualan
                        </button>
                    </div>
                </div>
            </form>
            </div>{{-- end tab form --}}

            {{-- TAB RIWAYAT --}}
            <div class="tab-pane fade {{ request('tab') == 'riwayat' ? 'show active' : '' }}" id="tabRiwayat">
                <div class="form-card mt-3">
                    <div class="table-responsive">
                        <table class="tbl-history">
                            <thead>
                                <tr>
                                    <th>Tgl</th>
                                    <th>CS</th>
                                    <th>Channel</th>
                                    <th>Pemesan</th>
                                    <th>Produk</th>
                                    <th style="text-align:right">GMV</th>
                                    <th style="text-align:right">Grand Total</th>
                                    <th style="text-align:center">Status</th>
                                    <th style="text-align:center;width:120px">Aksi</th>
                                    <th style="text-align:center;width:110px">Invoice</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse($history as $h)
                                <tr data-id="{{ $h->id }}" style="transition: background .4s">
                                    <td style="font-family:var(--mono);font-size:10.5px">{{ \Carbon\Carbon::parse($h->tgl)->format('d/m/Y') }}</td>
                                    <td style="font-weight:600">{{ $h->nama_cs }}</td>
                                    <td>{{ $h->channel->nama_channel ?? '-' }}</td>
                                    <td style="font-weight:600">{{ $h->nama_pemesan ?? '-' }}</td>
                                    <td>
                                        @if($h->detail_produk)
                                            @php $dp = is_array($h->detail_produk) ? $h->detail_produk : json_decode($h->detail_produk, true); @endphp
                                            <span style="font-size:10px;color:var(--ink-3)">
                                                {{ collect($dp)->map(fn($p) => $p['nama'].' x'.$p['qty'])->take(2)->implode(', ') }}
                                                {{ count($dp) > 2 ? '+'.(count($dp)-2).' lagi' : '' }}
                                            </span>
                                        @else
                                            <span style="color:var(--ink-3);font-size:10px">-</span>
                                        @endif
                                    </td>
                                    <td style="text-align:right;font-weight:600;color:#dc2626;font-family:var(--mono)">Rp{{ number_format($h->nominal_gmv,0,',','.') }}</td>
                                    <td style="text-align:right;font-weight:600;font-family:var(--mono)">Rp{{ number_format($h->grand_total ?? $h->nominal_gmv,0,',','.') }}</td>
                                    <td style="text-align:center">
                                        @php $sc = match($h->status) {
                                            'pending'    => ['#fef3c7','#92400e'],
                                            'dikemas'    => ['#dbeafe','#1e40af'],
                                            'dikirim'    => ['#d1fae5','#065f46'],
                                            'selesai'    => ['#0f172a','#fff'],
                                            'dibatalkan' => ['#fee2e2','#991b1b'],
                                            default      => ['#f1f5f9','#475569'],
                                        }; @endphp
                                        <span class="s-badge" style="background:{{ $sc[0] }};color:{{ $sc[1] }}">{{ $h->status }}</span>
                                    </td>
                                    {{-- KOLOM EDIT / HAPUS --}}
                                    <td style="text-align:center;vertical-align:middle">
                                        @if($h->status=='pending')
                                        <div style="display:flex;align-items:center;justify-content:center;gap:4px">
                                            <a href="/edit/{{ $h->id }}"
                                               style="display:inline-flex;align-items:center;gap:3px;font-size:10px;font-weight:600;padding:3px 10px;border-radius:6px;border:1px solid #bfdbfe;background:#eff6ff;color:#1d4ed8;text-decoration:none">
                                                <i class="ti ti-pencil" style="font-size:11px"></i> Edit
                                            </a>
                                            <form action="/hapus/{{ $h->id }}" method="POST" onsubmit="return confirm('Hapus data #{{ $h->id }}?')" style="margin:0">
                                                @csrf @method('DELETE')
                                                <button type="submit"
                                                    style="display:inline-flex;align-items:center;gap:3px;font-size:10px;font-weight:600;padding:3px 10px;border-radius:6px;border:1px solid #fecaca;background:#fef2f2;color:#dc2626;cursor:pointer;font-family:'Inter',sans-serif">
                                                    <i class="ti ti-trash" style="font-size:11px"></i> Hapus
                                                </button>
                                            </form>
                                        </div>
                                        @elseif($h->status=='selesai')
                                            <span style="display:inline-flex;align-items:center;gap:4px;font-size:10px;font-weight:600;color:#16a34a;background:#f0fdf4;border:1px solid #bbf7d0;padding:3px 10px;border-radius:6px">
                                                <i class="ti ti-circle-check" style="font-size:11px"></i> Selesai
                                            </span>
                                        @elseif($h->status=='dibatalkan')
                                            <span style="display:inline-flex;align-items:center;gap:4px;font-size:10px;font-weight:600;color:#dc2626;background:#fef2f2;border:1px solid #fecaca;padding:3px 10px;border-radius:6px">
                                                <i class="ti ti-circle-x" style="font-size:11px"></i> Dibatalkan
                                            </span>
                                        @else
                                            <span style="font-size:10px;color:var(--ink-3)">Diproses</span>
                                        @endif
                                    </td>
                                    {{-- KOLOM INVOICE --}}
                                    <td style="text-align:center;vertical-align:middle">
                                        <div style="display:inline-flex;flex-direction:column;align-items:center;gap:4px">
                                            @if($h->nomor_invoice)
                                                <span style="font-family:var(--mono);font-size:10px;font-weight:700;color:var(--ink);background:var(--surface-3);border:1px solid var(--border);border-radius:5px;padding:2px 7px;letter-spacing:.3px">
                                                    {{ $h->nomor_invoice }}
                                                </span>
                                            @endif
                                            <a href="/invoice/{{ $h->id }}" target="_blank"
                                               style="display:inline-flex;align-items:center;gap:3px;font-size:10px;font-weight:600;padding:2px 8px;border-radius:5px;border:1px solid #bfdbfe;background:#eff6ff;color:#1d4ed8;text-decoration:none"
                                               title="Lihat Invoice">
                                                <i class="ti ti-receipt" style="font-size:11px"></i> Lihat
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                                @empty
                                <tr>
                                    <td colspan="10" class="text-center py-4" style="color:var(--ink-3)">Belum ada data.</td>
                                </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>{{-- end tab riwayat --}}

            </div>{{-- end tab-content --}}
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
var cleaveNominal = new Cleave('#nominal_tampilan', {
    numeral: true, numeralThousandsGroupStyle: 'thousand',
    delimiter: '.', numeralDecimalMark: ','
});
var cleaveKirim = new Cleave('#kirim_tampilan', {
    numeral: true, numeralThousandsGroupStyle: 'thousand',
    delimiter: '.', numeralDecimalMark: ','
});

function updateGrandTotal() {
    var nom = parseInt(cleaveNominal.getRawValue()) || 0;
    var kir = parseInt(cleaveKirim.getRawValue()) || 0;
    document.getElementById('nominal_asli').value = nom;
    document.getElementById('kirim_asli').value = kir;
    document.getElementById('grand_total_tampil').value = (nom + kir).toLocaleString('id-ID');
}
document.getElementById('nominal_tampilan').addEventListener('input', updateGrandTotal);
document.getElementById('kirim_tampilan').addEventListener('input', updateGrandTotal);

function autoNominal(total) {
    cleaveNominal.setRawValue(total);
    document.getElementById('nominal_asli').value = total;
    updateGrandTotal();
}

function pilihTipe(kode) {
    // Cek kalau tipe ini disabled
    var btn = document.getElementById('tipe_' + kode);
    if (btn && btn.classList.contains('disabled-tipe')) return;

    document.querySelectorAll('.tipe-btn').forEach(el => el.classList.remove('active'));
    btn.classList.add('active');
    document.getElementById('tipe_val').value = kode;
}

function updateTipePembelian(select) {
    var selectedOption = select.options[select.selectedIndex];
    var namaCh = selectedOption ? selectedOption.getAttribute('data-nama') : '';
    var isQontak = namaCh && namaCh.includes('qontak');

    // Reset tipe yang aktif kalau tipe itu tidak tersedia
    var currentTipe = document.getElementById('tipe_val').value;
    var qontakOnly = ['NL-CS','NL-RS','RC-CS','RC-RS'];

    document.querySelectorAll('.tipe-btn.qontak-only').forEach(btn => {
        if (isQontak) {
            btn.classList.remove('disabled-tipe');
        } else {
            btn.classList.add('disabled-tipe');
            btn.classList.remove('active');
            // Reset tipe jika yang dipilih adalah qontak-only
            if (qontakOnly.includes(currentTipe)) {
                document.getElementById('tipe_val').value = '';
            }
        }
    });
}

function changeQty(kode, delta) {
    var input = document.getElementById('qty_' + kode);
    if (!input) return;
    var val = Math.max(0, parseInt(input.value || 0) + delta);
    input.value = val;
    updateRowStyle(kode, val);
    updateCart();
}

function updateRowStyle(kode, qty) {
    var row = document.getElementById('row_' + kode);
    if (row) {
        if (qty > 0) row.classList.add('selected-produk');
        else row.classList.remove('selected-produk');
    }
}

function hitungHargaEfektif(inp, qtyEfektifToples, qtyEfektifPouch) {
    var tipe      = inp.dataset.tipe;
    var konversi  = parseFloat(inp.dataset.konversi) || 0;
    var harga     = parseInt(inp.dataset.harga) || 0;
    var hp1       = parseInt(inp.dataset.hargaP1) || 0;
    var hp2       = parseInt(inp.dataset.hargaP2) || 0;
    var hp3       = parseInt(inp.dataset.hargaP3) || 0;
    var mp1       = parseInt(inp.dataset.minP1) || 0;
    var mp2       = parseInt(inp.dataset.minP2) || 0;
    var mp3       = parseInt(inp.dataset.minP3) || 0;

    if (tipe === 'other') return harga;

    var qtyEfektif = tipe === 'pouch' ? qtyEfektifPouch : qtyEfektifToples;

    if (mp3 > 0 && qtyEfektif >= mp3 && hp3 > 0) return hp3;
    if (mp2 > 0 && qtyEfektif >= mp2 && hp2 > 0) return hp2;
    if (mp1 > 0 && qtyEfektif >= mp1 && hp1 > 0) return hp1;

    return harga;
}

function getTierLabel(inp, qtyEfektifToples, qtyEfektifPouch) {
    var tipe     = inp.dataset.tipe;
    var mp1      = parseInt(inp.dataset.minP1) || 0;
    var mp2      = parseInt(inp.dataset.minP2) || 0;
    var mp3      = parseInt(inp.dataset.minP3) || 0;
    var hp1      = parseInt(inp.dataset.hargaP1) || 0;
    var hp2      = parseInt(inp.dataset.hargaP2) || 0;
    var hp3      = parseInt(inp.dataset.hargaP3) || 0;

    if (tipe === 'other') return '';
    var qty = tipe === 'pouch' ? qtyEfektifPouch : qtyEfektifToples;

    if (mp3 > 0 && qty >= mp3 && hp3 > 0) return ' <span style="background:#7c3aed;color:#fff;font-size:8px;padding:1px 5px;border-radius:4px;font-weight:700">PASUKAN</span>';
    if (mp2 > 0 && qty >= mp2 && hp2 > 0) return ' <span style="background:#0369a1;color:#fff;font-size:8px;padding:1px 5px;border-radius:4px;font-weight:700">RESELLER</span>';
    if (mp1 > 0 && qty >= mp1 && hp1 > 0) return ' <span style="background:#15803d;color:#fff;font-size:8px;padding:1px 5px;border-radius:4px;font-weight:700">DROPSHIP</span>';
    return '';
}

function updateCart() {
    var inputs = document.querySelectorAll('[name^="qty_produk"]');

    // Hitung total qty efektif toples dan pouch
    var qtyEfektifToples = 0;
    var qtyEfektifPouch  = 0;
    inputs.forEach(function(inp) {
        var qty      = parseInt(inp.value) || 0;
        var tipe     = inp.dataset.tipe;
        var konversi = parseFloat(inp.dataset.konversi) || 0;
        if (qty > 0 && tipe === 'toples' && konversi > 0) {
            qtyEfektifToples += qty * konversi;
        }
        if (qty > 0 && tipe === 'pouch') {
            qtyEfektifPouch += qty;
        }
    });

    var items = [], total = 0;
    inputs.forEach(function(inp) {
        var qty  = parseInt(inp.value) || 0;
        var kode = inp.id.replace('qty_', '');
        updateRowStyle(kode, qty);

        if (qty > 0) {
            var harga = hitungHargaEfektif(inp, qtyEfektifToples, qtyEfektifPouch);
            var sub   = harga * qty;
            total    += sub;
            items.push({ nama: inp.dataset.nama, qty, harga, sub });

            // Update label harga di baris produk (qty > 0)
            var label = document.getElementById('harga_label_' + kode);
            if (label) {
                label.innerHTML = 'Rp' + harga.toLocaleString('id-ID') + getTierLabel(inp, qtyEfektifToples, qtyEfektifPouch);
            }
        } else {
            // qty=0: tampilkan harga normal saja, tanpa badge tier
            var label = document.getElementById('harga_label_' + kode);
            if (label) {
                var hargaNormal = parseInt(inp.dataset.harga) || 0;
                label.innerHTML = hargaNormal > 0 ? 'Rp' + hargaNormal.toLocaleString('id-ID') : '-';
            }
        }
        });

    var cartItems    = document.getElementById('cartItems');
    var cartEmpty    = document.getElementById('cartEmpty');
    var cartTotal    = document.getElementById('cartTotal');
    var cartTotalVal = document.getElementById('cartTotalVal');

    if (items.length === 0) {
        cartEmpty.style.display = 'block';
        cartItems.style.display = 'none';
        cartTotal.style.display = 'none';
        document.getElementById('tierIndicator').style.display = 'none';
    } else {
        cartEmpty.style.display = 'none';
        cartItems.style.display = 'block';
        cartTotal.style.display = 'flex';
        document.getElementById('tierIndicator').style.display = 'block';

        // Update tier indicator toples
        var tierToplesVal   = document.getElementById('tierToplesVal');
        var tierToplesLabel = document.getElementById('tierToplesLabel');
        var tierPouchVal    = document.getElementById('tierPouchVal');
        var tierPouchLabel  = document.getElementById('tierPouchLabel');

        tierToplesVal.textContent = qtyEfektifToples + ' toples';
        tierPouchVal.textContent  = qtyEfektifPouch + ' pcs';

        // Label tier toples
        var tierToples = getTierLabelText(qtyEfektifToples, 'toples');
        tierToplesLabel.innerHTML = tierToples;
        document.getElementById('tierToples').style.borderColor = tierToples ? '#E8748A' : '#e2e8f0';

        // Label tier pouch
        var tierPouch = getTierLabelText(qtyEfektifPouch, 'pouch');
        tierPouchLabel.innerHTML = tierPouch;
        document.getElementById('tierPouch').style.borderColor = tierPouch ? '#7B3F1E' : '#e2e8f0';

        cartItems.innerHTML = items.map(i =>
            `<div class="cart-item">
                <span>${i.nama} <strong>x${i.qty}</strong></span>
                <span style="color:var(--blue);font-weight:600">Rp${i.sub.toLocaleString('id-ID')}</span>
            </div>`
        ).join('');
        cartTotalVal.textContent = 'Rp ' + total.toLocaleString('id-ID');
    }
    autoNominal(total);
}

function getTierLabelText(qty, tipe) {
    // Ambil semua produk dengan tipe yang sama untuk cek min
    var inputs = document.querySelectorAll('[name^="qty_produk"]');
    var mp1 = 0, mp2 = 0, mp3 = 0;
    inputs.forEach(function(inp) {
        if (inp.dataset.tipe === tipe) {
            mp1 = mp1 || (parseInt(inp.dataset.minP1) || 0);
            mp2 = mp2 || (parseInt(inp.dataset.minP2) || 0);
            mp3 = mp3 || (parseInt(inp.dataset.minP3) || 0);
        }
    });
    if (!mp1 && !mp2 && !mp3) return '';

    if (mp3 > 0 && qty >= mp3) return '<span style="background:#7c3aed;color:#fff;padding:1px 6px;border-radius:4px;font-weight:700">PASUKAN</span>';
    if (mp2 > 0 && qty >= mp2) return '<span style="background:#0369a1;color:#fff;padding:1px 6px;border-radius:4px;font-weight:700">RESELLER</span>';
    if (mp1 > 0 && qty >= mp1) return '<span style="background:#15803d;color:#fff;padding:1px 6px;border-radius:4px;font-weight:700">DROPSHIP</span>';

    if (mp1 > 0) {
        var sisa = mp1 - qty;
        return '<span style="color:#64748b">Tambah ' + sisa + ' lagi → DROPSHIP</span>';
    }
    return '';
}
function filterProduk(q) {
    q = q.toLowerCase().trim();
    if (q === '') {
        document.querySelectorAll('.produk-row').forEach(r => r.style.display = '');
        document.querySelectorAll('.produk-card').forEach(c => c.style.display = '');
        return;
    }
    document.querySelectorAll('.produk-row').forEach(row => {
        row.style.display = (row.dataset.nama || '').toLowerCase().includes(q) ? '' : 'none';
    });
    var firstVisible = null;
    document.querySelectorAll('.produk-card').forEach(card => {
        var visible = Array.from(card.querySelectorAll('.produk-row')).some(r => r.style.display !== 'none');
        card.style.display = visible ? '' : 'none';
        if (visible && !firstVisible) firstVisible = card;
    });
    if (firstVisible) firstVisible.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}

function filterKategori(kat, el) {
    document.querySelectorAll('.kategori-tab').forEach(t => t.classList.remove('active'));
    el.classList.add('active');
    document.getElementById('searchProduk').value = '';
    document.querySelectorAll('.produk-row').forEach(r => r.style.display = '');
    if (!kat) {
        document.querySelectorAll('.produk-card').forEach(c => c.style.display = '');
        document.getElementById('produkList').scrollTop = 0;
        return;
    }
    document.querySelectorAll('.produk-card').forEach(card => {
        card.style.display = (card.dataset.kategori === kat) ? '' : 'none';
    });
    var target = document.querySelector('.produk-card[data-kategori="' + kat + '"]');
    if (target) target.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}

document.getElementById('formInput').addEventListener('submit', function(e) {
    document.getElementById('nominal_asli').value = cleaveNominal.getRawValue();
    document.getElementById('kirim_asli').value = cleaveKirim.getRawValue();
    if (!document.getElementById('tipe_val').value) {
        e.preventDefault();
        alert('Pilih tipe pembelian terlebih dahulu!');
        return;
    }
    if (!parseInt(cleaveNominal.getRawValue())) {
        e.preventDefault();
        alert('Nominal GMV tidak boleh 0!');
    }
});

// ── WILAYAH INDONESIA ──
const API = '/api/wilayah';

fetch(`${API}/provinces`)
    .then(r => r.json())
    .then(data => {
    const sel = document.getElementById('sel_provinsi');
    sel.innerHTML = '<option value="">-- Pilih Provinsi --</option>';
    data.forEach(p => {
        sel.innerHTML += `<option value="${p.id}" data-nama="${p.name}">${p.name}</option>`;
    });
});

$('#sel_provinsi').on('change', function() { loadKota(); });
$('#sel_kota').on('change', function() { loadKecamatan(); });
$('#sel_kecamatan').on('change', function() { loadKelurahan(); });
$('#sel_kelurahan').on('change', function() { setKelurahan(); });

function loadKota() {
    const id = document.getElementById('sel_provinsi').value;
    const sel = document.getElementById('sel_provinsi');
    document.getElementById('val_provinsi').value = sel.options[sel.selectedIndex]?.getAttribute('data-nama') || '';

    const selKota = document.getElementById('sel_kota');
    selKota.innerHTML = '<option value="">-- Pilih Kota/Kab --</option>';
    selKota.disabled = true;
    document.getElementById('sel_kecamatan').innerHTML = '<option value="">-- Pilih Kecamatan --</option>';
    document.getElementById('sel_kecamatan').disabled = true;
    document.getElementById('sel_kelurahan').innerHTML = '<option value="">-- Pilih Kelurahan --</option>';
    document.getElementById('sel_kelurahan').disabled = true;

    if (!id) return;
    fetch(`${API}/regencies/${id}`)
        .then(r => r.json())
        .then(data => {
            data.forEach(k => {
                selKota.innerHTML += `<option value="${k.id}" data-nama="${k.name}">${k.name}</option>`;
            });
            selKota.disabled = false;
        });
}

function loadKecamatan() {
    const sel = document.getElementById('sel_kota');
    const id = sel.value;
    document.getElementById('val_kota').value = sel.options[sel.selectedIndex]?.getAttribute('data-nama') || '';

    const selKec = document.getElementById('sel_kecamatan');
    selKec.innerHTML = '<option value="">-- Pilih Kecamatan --</option>';
    selKec.disabled = true;
    document.getElementById('sel_kelurahan').innerHTML = '<option value="">-- Pilih Kelurahan --</option>';
    document.getElementById('sel_kelurahan').disabled = true;

    if (!id) return;
    fetch(`${API}/districts/${id}`)
        .then(r => r.json())
        .then(data => {
            data.forEach(k => {
                selKec.innerHTML += `<option value="${k.id}" data-nama="${k.name}">${k.name}</option>`;
            });
            selKec.disabled = false;
        });
}

function loadKelurahan() {
    const sel = document.getElementById('sel_kecamatan');
    const id = sel.value;
    document.getElementById('val_kecamatan').value = sel.options[sel.selectedIndex]?.getAttribute('data-nama') || '';

    const selKel = document.getElementById('sel_kelurahan');
    selKel.innerHTML = '<option value="">-- Pilih Kelurahan --</option>';
    selKel.disabled = true;

    if (!id) return;
    fetch(`${API}/villages/${id}`)
        .then(r => r.json())
        .then(data => {
            data.forEach(k => {
                selKel.innerHTML += `<option value="${k.id}" data-nama="${k.name}">${k.name}</option>`;
            });
            selKel.disabled = false;
        });
}

function setKelurahan() {
    const sel = document.getElementById('sel_kelurahan');
    document.getElementById('val_kelurahan').value = sel.options[sel.selectedIndex]?.getAttribute('data-nama') || '';
}

// ── HIGHLIGHT BARIS DARI NOTIF ──
(function() {
    const params = new URLSearchParams(window.location.search);
    const highlightId = params.get('highlight');
    if (!highlightId) return;

    // Pastikan tab riwayat aktif
    const tabBtn = document.querySelector('[data-bs-target="#tabRiwayat"]');
    if (tabBtn) {
        const tab = new bootstrap.Tab(tabBtn);
        tab.show();
    }

    // Tunggu tab render lalu scroll & highlight
    setTimeout(() => {
        const row = document.querySelector(`tr[data-id="${highlightId}"]`);
        if (!row) return;

        row.scrollIntoView({ behavior: 'smooth', block: 'center' });
        row.style.background = '#fef9c3';
        row.querySelectorAll('td').forEach(td => td.style.background = '#fef9c3');

        // Fade out highlight setelah 2.5 detik
        setTimeout(() => {
            row.style.background = '';
            row.querySelectorAll('td').forEach(td => td.style.background = '');
        }, 2500);
    }, 400);
})();
</script>
</body>
</html>