<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Penjualan #{{ $sale->id }} — 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://cdnjs.cloudflare.com/ajax/libs/cleave.js/1.6.0/cleave.min.js"></script>
    <style>
        :root {
            --ink:       #0f172a;
            --ink-2:     #334155;
            --ink-3:     #64748b;
            --surface:   #ffffff;
            --surface-2: #f8fafc;
            --surface-3: #f1f5f9;
            --border:    #e2e8f0;
            --blue:      #1d4ed8;
            --blue-soft: #eff6ff;
            --amber:     #d97706;
            --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); }

        /* ── FORM CARD ── */
        .form-card {
            background: var(--surface);
            border: 1px solid var(--border);
            border-radius: var(--r);
            overflow: hidden;
            margin-bottom: 14px;
        }
        .form-card-header {
            background: var(--ink);
            color: #fff;
            padding: 10px 18px;
            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: 15px; }
        .form-card-body { padding: 16px 18px; }

        /* ── TIPE 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: #fff; }
        .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; }

        /* ── 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-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; }
        .search-produk:focus { border-color: var(--blue); }
        .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.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); }

        /* ── WARNING BANNER ── */
        .edit-warning {
            background: #fffbeb;
            border: 1px solid #fde68a;
            border-radius: 8px;
            padding: 10px 16px;
            margin-bottom: 16px;
            font-size: 12px;
            color: #92400e;
            display: flex;
            align-items: center;
            gap: 9px;
        }
        .edit-warning i { font-size: 18px; flex-shrink: 0; }

        /* ── BUTTONS ── */
        .btn-save {
            background: var(--blue);
            color: #fff; border: none;
            padding: 10px 28px; border-radius: 8px;
            font-size: 13px; font-weight: 700;
            cursor: pointer; font-family: 'Inter', sans-serif;
            display: inline-flex; align-items: center; gap: 7px;
            transition: opacity .15s;
        }
        .btn-save:hover { opacity: .9; }
        .btn-cancel {
            background: var(--surface); color: var(--ink-2);
            border: 1px solid var(--border);
            padding: 10px 20px; border-radius: 8px;
            font-size: 13px; font-weight: 500;
            text-decoration: none; font-family: 'Inter', sans-serif;
            display: inline-flex; align-items: center; gap: 6px;
            transition: background .15s;
        }
        .btn-cancel:hover { background: var(--surface-3); color: var(--ink); }

        /* ── DELETE ZONE ── */
        .delete-zone {
            background: #fef2f2;
            border: 1px solid #fecaca;
            border-radius: 8px;
            padding: 14px 18px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 16px;
            flex-wrap: wrap;
        }
        .delete-zone-text { font-size: 12px; color: #991b1b; }
        .delete-zone-text strong { display: block; margin-bottom: 2px; }
        .btn-delete {
            background: #dc2626; color: #fff; border: none;
            padding: 8px 18px; border-radius: 7px;
            font-size: 12px; font-weight: 700;
            cursor: pointer; font-family: 'Inter', sans-serif;
            display: inline-flex; align-items: center; gap: 6px;
            transition: opacity .15s; white-space: nowrap;
        }
        .btn-delete:hover { opacity: .88; }
    </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 align-items-center gap-3 py-3 mb-1">
                <a href="/input?tab=riwayat" class="btn-cancel" style="padding:6px 14px;font-size:12px">
                    <i class="ti ti-arrow-left" style="font-size:14px"></i> Kembali
                </a>
                <div>
                    <h5 style="font-size:16px;font-weight:700;margin:0;color:var(--ink)">Edit Penjualan</h5>
                    <div style="font-size:11px;color:var(--ink-3)">Order #{{ $sale->id }} · {{ \Carbon\Carbon::parse($sale->tgl)->format('d F Y') }}</div>
                </div>
            </div>

            {{-- WARNING: hanya bisa edit status pending --}}
            <div class="edit-warning">
                <i class="ti ti-alert-triangle" style="color:#d97706"></i>
                <div>
                    <strong>Perhatian</strong>
                    Halaman ini hanya untuk data dengan status <strong>Pending</strong>. Pastikan data yang diubah sudah benar sebelum disimpan.
                </div>
            </div>

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

            {{-- FORM EDIT --}}
            <form action="/update/{{ $sale->id }}" method="POST" id="formEdit">
                @csrf @method('PUT')
                <input type="hidden" name="admin_id" value="{{ auth()->user()->id }}">

                <div class="row g-3">

                    {{-- KOLOM KIRI --}}
                    <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>-- Pilih --</option>
                                            @php $csNames = ['Andini','Bening','Debby','Devita','Elsa','Fifah','Gibran','Juli','Nurdin','Putri','Resa','Rianah','Riyan Hardi','Sultan','Tami','Wilah','Yuni','Zena','Zura']; @endphp
                                            @foreach($csNames as $n)
                                                <option value="{{ $n }}" @selected($sale->nama_cs == $n)>{{ $n }}</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="{{ $sale->tgl }}" 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>
                                            <option value="" disabled>-- Pilih --</option>
                                            @foreach($channels as $ch)
                                                <option value="{{ $ch->id }}" @selected($sale->channel_id == $ch->id)>{{ $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 }}" @selected($sale->status_bayar == $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" value="{{ $sale->tipe_pembelian }}">
                                <div class="row g-2">
                                    @foreach([
                                        ['NL-CS', 'New Leads', 'Harga Customer'],
                                        ['NL-RS', 'New Leads', 'Harga Reseller'],
                                        ['NEW',   'New', 'Customer Baru'],
                                        ['RC-CS', 'Repeat Customer', 'Harga Customer'],
                                        ['RC-RS', 'Repeat Customer', 'Harga Reseller'],
                                        ['REPEAT','Repeat', 'Customer Lama'],
                                    ] as [$kode, $label, $sub])
                                    <div class="col-4">
                                        <div class="tipe-btn {{ $sale->tipe_pembelian == $kode ? 'active' : '' }}"
                                             onclick="pilihTipe('{{ $kode }}')" id="tipe_{{ $kode }}">
                                            <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">
                                    <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)
                                            @php
                                                $existingQty = 0;
                                                if($sale->detail_produk) {
                                                    $dp = is_array($sale->detail_produk) ? $sale->detail_produk : json_decode($sale->detail_produk, true);
                                                    $found = collect($dp)->firstWhere('kode', $p->kode);
                                                    $existingQty = $found['qty'] ?? 0;
                                                }
                                            @endphp
                                            <div class="produk-row {{ $existingQty > 0 ? 'selected-produk' : '' }}" 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="{{ $existingQty }}" 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>
                    </div>

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

                        {{-- 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>
                                <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>

                        {{-- 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" value="{{ $sale->nominal_gmv }}">
                                        </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" value="{{ $sale->biaya_kirim ?? 0 }}">
                                        </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-12">
                                        <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 @selected($sale->jasa_kirim == $jk)>{{ $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" value="{{ $sale->nama_pemesan }}" 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" value="{{ $sale->no_telp_pemesan }}" 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" value="{{ $sale->nama_penerima }}" 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" value="{{ $sale->no_telp_penerima }}" 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" value="{{ $sale->nama_transfer }}" placeholder="Nama rekening pengirim">
                                    </div>
                                </div>
                            </div>
                        </div>

                        {{-- Alamat --}}
                        <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">{{ $sale->alamat }}</textarea>
                                    </div>
                                    <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" value="{{ $sale->provinsi }}">
                                    </div>
                                    <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" value="{{ $sale->kota }}">
                                    </div>
                                    <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" value="{{ $sale->kecamatan }}">
                                    </div>
                                    <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" value="{{ $sale->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" value="{{ $sale->nomor_resi }}" 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" value="{{ $sale->catatan }}">
                                    </div>
                                </div>
                            </div>
                        </div>

                        {{-- ACTION BUTTONS --}}
                        <div class="d-flex gap-2 mb-4">
                            <button type="submit" class="btn-save">
                                <i class="ti ti-device-floppy" style="font-size:16px"></i> Simpan Perubahan
                            </button>
                            <a href="/input?tab=riwayat" class="btn-cancel">Batal</a>
                        </div>

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

            {{-- DANGER ZONE: HAPUS --}}
            <div class="delete-zone mb-5">
                <div class="delete-zone-text">
                    <strong><i class="ti ti-trash" style="font-size:13px;vertical-align:-1px"></i> Hapus Data Ini</strong>
                    Tindakan ini tidak bisa dibatalkan. Data penjualan #{{ $sale->id }} akan dihapus permanen.
                </div>
                <form action="/hapus/{{ $sale->id }}" method="POST" onsubmit="return confirm('Yakin ingin menghapus data #{{ $sale->id }}? Tindakan ini tidak dapat dibatalkan.')">
                    @csrf @method('DELETE')
                    <button type="submit" class="btn-delete">
                        <i class="ti ti-trash" style="font-size:14px"></i> Hapus Permanen
                    </button>
                </form>
            </div>

        </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: ','
});

// Set nilai awal dari database
cleaveNominal.setRawValue({{ $sale->nominal_gmv }});
cleaveKirim.setRawValue({{ $sale->biaya_kirim ?? 0 }});
updateGrandTotal();
updateCart();

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) {
    document.querySelectorAll('.tipe-btn').forEach(el => el.classList.remove('active'));
    document.getElementById('tipe_' + kode).classList.add('active');
    document.getElementById('tipe_val').value = kode;
}

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 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 qty = tipe === 'pouch' ? qtyEfektifPouch : qtyEfektifToples;
    if (mp3 > 0 && qty >= mp3 && hp3 > 0) return hp3;
    if (mp2 > 0 && qty >= mp2 && hp2 > 0) return hp2;
    if (mp1 > 0 && qty >= mp1 && hp1 > 0) return hp1;
    return harga;
}

function getTierLabel(inp, qtyEfektifToples, qtyEfektifPouch) {
    var tipe = inp.dataset.tipe;
    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 '';
    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"]');
    var qtyEfektifToples = 0, 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 });
            var label = document.getElementById('harga_label_' + kode);
            if (label) label.innerHTML = 'Rp' + harga.toLocaleString('id-ID') + getTierLabel(inp, qtyEfektifToples, qtyEfektifPouch);
        } else {
            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';
    } else {
        cartEmpty.style.display = 'none';
        cartItems.style.display = 'block';
        cartTotal.style.display = 'flex';
        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');
    }
}

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';
    });
    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';
    });
}

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 = '');
        return;
    }
    document.querySelectorAll('.produk-card').forEach(card => {
        card.style.display = (card.dataset.kategori === kat) ? '' : 'none';
    });
}

// ── WILAYAH: restore nilai lama dari DB ──
const API = '/api/wilayah';
const savedProvinsi   = @json($sale->provinsi ?? '');
const savedKota       = @json($sale->kota ?? '');
const savedKecamatan  = @json($sale->kecamatan ?? '');
const savedKelurahan  = @json($sale->kelurahan ?? '');

function selectByNama(sel, nama) {
    for (let i = 0; i < sel.options.length; i++) {
        if ((sel.options[i].getAttribute('data-nama') || '').toLowerCase() === nama.toLowerCase()) {
            sel.value = sel.options[i].value;
            return sel.options[i].value;
        }
    }
    return null;
}

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>`;
        });
        if (savedProvinsi) {
            const provId = selectByNama(sel, savedProvinsi);
            if (provId) loadKota(provId);
        }
    });

function loadKota(provId) {
    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 (!provId) return;

    const selProv = document.getElementById('sel_provinsi');
    document.getElementById('val_provinsi').value = selProv.options[selProv.selectedIndex]?.getAttribute('data-nama') || savedProvinsi;

    fetch(`${API}/regencies/${provId}`)
        .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;
            if (savedKota) {
                const kotaId = selectByNama(selKota, savedKota);
                document.getElementById('val_kota').value = savedKota;
                if (kotaId) loadKecamatan(kotaId);
            }
        });
}

function loadKecamatan(kotaId) {
    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 (!kotaId) return;

    fetch(`${API}/districts/${kotaId}`)
        .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;
            if (savedKecamatan) {
                const kecId = selectByNama(selKec, savedKecamatan);
                document.getElementById('val_kecamatan').value = savedKecamatan;
                if (kecId) loadKelurahan(kecId);
            }
        });
}

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

    if (!kecId) return;

    fetch(`${API}/villages/${kecId}`)
        .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;
            if (savedKelurahan) {
                selectByNama(selKel, savedKelurahan);
                document.getElementById('val_kelurahan').value = savedKelurahan;
            }
        });
}

// Event listeners untuk perubahan manual
document.getElementById('sel_provinsi').addEventListener('change', function() {
    loadKota(this.value);
});
document.getElementById('sel_kota').addEventListener('change', function() {
    loadKecamatan(this.value);
});
document.getElementById('sel_kecamatan').addEventListener('change', function() {
    loadKelurahan(this.value);
});
document.getElementById('sel_kelurahan').addEventListener('change', function() {
    const sel = document.getElementById('sel_kelurahan');
    document.getElementById('val_kelurahan').value = sel.options[sel.selectedIndex]?.getAttribute('data-nama') || '';
});

document.getElementById('formEdit').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!');
    }
});
</script>
</body>
</html>