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

<?= $this->section('content') ?>
<style>
    /* ===== Modern Premium Design Tokens ===== */
    :root {
        --primary: #4f46e5;
        --primary-hover: #4338ca;
        --primary-light: #eeebff;
        --success: #10b981;
        --warning: #f59e0b;
        --danger: #ef4444;
        --bg-body: #f8fafc;
        --card-bg: #ffffff;
        --border-color: #e2e8f0;
        --text-main: #0f172a;
        --text-sub: #64748b;
        --radius-lg: 16px;
        --radius-md: 12px;
        --radius-sm: 8px;
        --transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
    }

    body { 
        background-color: var(--bg-body) !important; 
        color: var(--text-main);
        font-family: 'Inter', system-ui, -apple-system, sans-serif;
    }

    /* Modern Utilities & Layout Adjustments */
    .section-title { font-weight: 700; color: var(--text-main); letter-spacing: -0.02em; }
    .card-premium {
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: var(--radius-lg);
        box-shadow: 0 4px 6px -1px rgba(0,0,0,0.02), 0 2px 4px -1px rgba(0,0,0,0.02);
        transition: var(--transition);
    }

    /* Product Grid Modern Layout */
    .product-grid-container {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(190px, 1fr));
        gap: 16px;
    }
    
    .product-card {
        padding: 12px;
        border-radius: var(--radius-md);
        border: 1px solid var(--border-color);
        background: var(--card-bg);
        cursor: pointer;
        display: flex;
        flex-direction: column;
        height: 100%;
        position: relative;
        overflow: hidden;
        transition: var(--transition);
    }
    .product-card:hover {
        border-color: var(--primary);
        transform: translateY(-4px);
        box-shadow: 0 12px 20px -8px rgba(79, 70, 229, 0.15);
    }
    .product-card:active { transform: translateY(-1px); }

    /* Custom Product Card Special Style */
    .product-card.custom-card {
        border: 2px dashed #c7d2fe;
        background: #fbfbff;
        align-items: center;
        justify-content: center;
        min-height: 220px;
        text-align: center;
        color: var(--primary);
        font-weight: 600;
    }
    .product-card.custom-card:hover {
        background: var(--primary-light);
        border-color: var(--primary);
    }
    .product-card.custom-card i { font-size: 2rem; margin-bottom: 8px; }

    /* Product Thumbnail Enhancement */
    .product-card .thumb { 
        border-radius: var(--radius-sm); 
        margin-bottom: 12px; 
        height: 130px; 
        background-size: cover; 
        background-position: center;
        background-color: #f1f5f9;
        display: flex;
        align-items: center;
        justify-content: center;
        color: var(--text-sub);
        font-size: 1.75rem;
    }

    .product-card .body { display: flex; flex-direction: column; flex-grow: 1; justify-content: space-between; }
    .product-card .name { font-weight: 600; font-size: 0.95rem; line-height: 1.4; color: var(--text-main); display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; height: 2.8em; }
    .product-card .harga { font-weight: 700; font-size: 1rem; color: var(--primary); }

    /* Modern Dynamic Badges */
    .badge-premium { padding: 6px 10px; border-radius: 6px; font-size: 0.75rem; font-weight: 700; letter-spacing: 0.03em; }
    .badge-ready { background-color: #d1fae5; color: #065f46; }
    .badge-po { background-color: #fef3c7; color: #92400e; }
    .badge-custom { background-color: var(--primary-light); color: var(--primary); }

    /* Cart Element Styling */
    .cart-list { max-height: 480px; overflow-y: auto; padding-right: 4px; }
    .cart-item {
        border: 1px solid var(--border-color);
        border-radius: var(--radius-md);
        padding: 14px;
        background: #fff;
        margin-bottom: 12px;
        transition: var(--transition);
    }
    .cart-item:hover { border-color: #cbd5e1; }
    .cart-item-top { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 8px; }
    .cart-item-name { font-weight: 600; font-size: 0.9rem; color: var(--text-main); max-width: 85%; }
    .cart-item-harga { font-size: 0.8rem; color: var(--text-sub); margin-top: 2px; }
    
    .btn-remove { background: none; border: none; color: var(--text-sub); transition: var(--transition); padding: 0 4px; }
    .btn-remove:hover { color: var(--danger); }

    /* Quantity Styling */
    .qty-control { display: flex; align-items: center; background: #f1f5f9; border-radius: var(--radius-sm); padding: 3px; }
    .qty-control button {
        background: #ffffff;
        border: none;
        border-radius: 6px;
        width: 28px; height: 28px;
        display: flex; align-items: center; justify-content: center;
        font-weight: 600; color: var(--text-main);
        box-shadow: 0 1px 3px rgba(0,0,0,0.05);
        transition: var(--transition);
    }
    .qty-control button:hover { background: #e2e8f0; }
    .qty-value { font-weight: 600; font-size: 0.9rem; min-width: 32px; text-align: center; }

    /* Custom Product Fields Styling Inside Cart */
    .custom-fields { display: flex; flex-direction: column; gap: 8px; margin: 10px 0; padding: 10px; background: #f8fafc; border-radius: var(--radius-sm); border: 1px inset #f1f5f9; }

    /* Summary Block Elements */
    .totals-box { background: #f8fafc; border-radius: var(--radius-md); padding: 16px; border: 1px solid var(--border-color); }
    .row-line { display: flex; justify-content: space-between; margin-bottom: 10px; font-size: 0.9rem; color: var(--text-sub); }
    .row-line:last-child { margin-bottom: 0; }
    .row-line.grand-total { border-top: 1px dashed var(--border-color); padding-top: 12px; margin-top: 12px; color: var(--text-main); }
    .row-line.grand-total strong { font-size: 1.3rem; color: var(--primary); }

    /* Forms Premium Focus UI */
    .form-control:focus, .form-select:focus {
        border-color: var(--primary);
        box-shadow: 0 0 0 4px rgba(79, 70, 229, 0.12);
    }
    .form-label { font-weight: 600; font-size: 0.8rem; text-transform: uppercase; letter-spacing: 0.05em; color: var(--text-sub); }

    /* Radio Engine UI Group */
    .btn-check:checked + .btn-outline-success { background-color: #d1fae5 !important; color: #065f46 !important; border-color: #34d399 !important; }
    .btn-check:checked + .btn-outline-warning { background-color: #fef3c7 !important; color: #92400e !important; border-color: #fbbf24 !important; }

    /* Scrollbar Style */
    ::-webkit-scrollbar { width: 6px; height: 6px; }
    ::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 10px; }
    ::-webkit-scrollbar-thumb:hover { background: #94a3b8; }

    /* Disabled State Look Styling */
    .disabled-look { opacity: 0.5; pointer-events: none; }
</style>

<div class="container-fluid py-4">
    <!-- Top Action Headers -->
    <div class="row align-items-center mb-4 g-3">
        <div class="col-sm-8">
            <h3 class="section-title mb-1"><?= esc($title) ?></h3>
            <div class="d-flex align-items-center gap-2">
                <span class="badge bg-white text-secondary border px-3 py-2 rounded-pill shadow-sm fs-7">
                    <i class="bi bi-receipt me-1 text-primary"></i> No. Order: <strong><?= esc($order_no) ?></strong>
                </span>
            </div>
        </div>
        <div class="col-sm-4 text-sm-end">
            <a href="<?= site_url('admin/orders') ?>" class="btn btn-white bg-white border border-slate-200 text-secondary rounded-3 px-3 shadow-sm transition">
                <i class="bi bi-arrow-left me-1"></i> Kembali
            </a>
        </div>
    </div>

    <!-- MAIN FORM INTERFACE -->
    <form id="orderForm" method="post" action="<?= site_url('admin/orders/store') ?>" autocomplete="off" onsubmit="return buildHiddenInputs(event)">
        <?= csrf_field() ?>

        <!-- Responsive Flex Grid Layout Wrapper -->
        <div class="row g-4">
            
            <!-- LEFT AREA: SEARCH & PRODUCT LIST SECTIONS -->
            <div class="col-12 col-lg-7 col-xl-8">
                <!-- Advanced Search Box Area Component -->
                <div class="card-premium p-3 mb-4">
                    <div class="input-group input-group-lg">
                        <span class="input-group-text bg-transparent border-end-0 text-muted px-3">
                            <i class="bi bi-search"></i>
                        </span>
                        <input
                            type="text"
                            id="searchProduct"
                            class="form-control border-start-0 fs-6 ps-1"
                            placeholder="Cari produk berdasarkan nama, status po, atau ketik 'custom'..."
                            oninput="filterProducts()"
                        >
                    </div>
                </div>

                <!-- Products Flexible Grid Container Matrix -->
                <div class="product-grid-container" id="productGrid">
                    <!-- Custom Variable Product Interactive Unit Card -->
                    <div class="product-card custom-card shadow-sm" data-name="produk custom" data-stock="custom" data-custom="1" onclick="addCustomToCart()">
                        <i class="bi bi-plus-circle-dashed"></i>
                        <span>Produk Custom</span>
                    </div>

                    <!-- Server Render Loop Elements -->
                    <?php foreach ($products as $p): ?>
                        <?php
                            // Data lama pernah menyimpan satuan seperti "pcs" pada
                            // kolom ini. Selain PO, seluruh produk diperlakukan ready.
                            $stockType = strtolower((string) ($p['stock_type'] ?? 'ready')) === 'po' ? 'po' : 'ready';
                            $badgeClass = $stockType === 'po' ? 'badge-po' : 'badge-ready';
                            $badgeText  = $stockType === 'po' ? 'PO' : 'READY';
                        ?>
                        <div
                            class="product-card shadow-sm"
                            data-name="<?= esc(strtolower($p['nama_product'])) ?>"
                            data-id="<?= esc($p['id_product']) ?>"
                            data-harga="<?= esc($p['harga'] ?? 0) ?>"
                            data-stock="<?= esc($stockType) ?>"
                            onclick="addToCart('<?= esc($p['id_product'], 'js') ?>')"
                        >
                            <?php $photoName = $p['product_photo'] ?? $p['image'] ?? null; ?>
                            <div class="thumb"
                                <?php if (!empty($photoName)): ?>
                                    style="background-image:url('<?= esc(base_url('uploads/products/' . $photoName)) ?>')"
                                <?php endif; ?>
                            >
                                <?php if (empty($photoName)): ?>
                                    <i class="bi bi-box-seam text-muted opacity-50"></i>
                                <?php endif; ?>
                            </div>
                            <div class="body">
                                <div class="name" title="<?= esc($p['nama_product']) ?>"><?= esc($p['nama_product']) ?></div>
                                <div class="d-flex justify-content-between align-items-center mt-3 pt-2 border-top border-light">
                                    <span class="harga">Rp <?= number_format($p['harga'] ?? 0, 0, ',', '.') ?></span>
                                    <span class="badge-premium <?= $badgeClass ?>"><?= $badgeText ?></span>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>

                    <!-- Empty States Layout View -->
                    <div id="noProductFound" class="text-muted text-center py-5 d-none bg-white border rounded-3 w-100 shadow-sm" style="grid-column: 1 / -1;">
                        <i class="bi bi-patch-question fs-1 d-block mb-2 text-muted opacity-50"></i>
                        <span class="fw-medium">Produk tidak ditemukan atau kata kunci tidak sesuai.</span>
                    </div>
                </div>
            </div>

            <!-- RIGHT AREA: CUSTOMER IDENTITY MODULE & TRANSACTION BASKET PANEL -->
            <div class="col-12 col-lg-5 col-xl-4">
                
                <!-- CUSTOMER PROFILES AND PARAMS PANEL -->
                <div class="card-premium p-4 mb-4">
                    <h5 class="fw-bold mb-3 d-flex align-items-center gap-2 border-bottom pb-2">
                        <i class="bi bi-person-bounding-box text-primary"></i> Data Customer
                    </h5>

                    <!-- Transaction Order References -->
                    <div class="mb-3">
                        <label class="form-label">No Order Reference</label>
                        <input
                            type="text"
                            class="form-control bg-light fw-semibold text-muted"
                            value="<?= esc($order_no) ?>"
                            readonly>
                        <input
                            type="hidden"
                            name="order_number"
                            value="<?= esc($order_no) ?>">
                    </div>

                    <!-- Client Structural Inputs -->
                    <div class="mb-3">
                        <label class="form-label">Nama Customer <span class="text-danger">*</span></label>
                        <input
                            type="text"
                            name="customer_name"
                            class="form-control"
                            placeholder="Ketik nama lengkap customer..."
                            value="<?= old('customer_name') ?>"
                            required>
                    </div>

                    <!-- Contact Context Processing Units -->
                    <div class="row g-2 mb-3">
                        <div class="col-12">
                            <label class="form-label">No HP WhatsApp</label>
                            <input
                                type="text"
                                name="customer_phone"
                                class="form-control"
                                placeholder="Contoh: 08123456789"
                                value="<?= old('customer_phone') ?>">
                        </div>
                        <div class="col-12 mt-2">
                            <label class="form-label">Alamat Email (Opsional)</label>
                            <input
                                type="email"
                                name="customer_email"
                                class="form-control"
                                placeholder="name@domain.com"
                                value="<?= old('customer_email') ?>">
                        </div>
                    </div>

                    <!-- Operational Type Switching Engine -->
                    <div class="mb-3">
                        <label class="form-label d-block mb-2">Jenis Order Modality</label>
                        <div class="btn-group w-100" role="group">
                            <input
                                type="radio"
                                class="btn-check"
                                id="typeReady"
                                name="order_type"
                                value="ready"
                                checked
                                onchange="toggleOrderType()">
                            <label class="btn btn-outline-success border border-end-0 py-2 fw-semibold" for="typeReady">
                                <i class="bi bi-box-seam me-1"></i> Ready Stock
                            </label>

                            <input
                                type="radio"
                                class="btn-check"
                                id="typePo"
                                name="order_type"
                                value="po"
                                onchange="toggleOrderType()">
                            <label class="btn btn-outline-warning border py-2 fw-semibold" for="typePo">
                                <i class="bi bi-hourglass-split me-1"></i> Pre-Order (PO)
                            </label>
                        </div>
                    </div>

                    <!-- Production Processing Timeline Targets Matrix -->
                    <div class="mb-3 p-3 bg-light rounded-3 border" id="targetDateWrap">
                        <label class="form-label mb-1">Target Penyelesaian Produksi</label>
                        <input
                            type="date"
                            id="targetDate"
                            name="target_date"
                            class="form-control shadow-sm mb-2"
                            value="<?= old('target_date', $defaultTargetDate ?? date('Y-m-d')) ?>"
                            disabled>

                        <?php if (!empty($monthlyPoLimit)): ?>
                            <div class="d-flex gap-2 align-items-start text-muted mt-2 fs-7">
                                <i class="bi bi-info-circle-fill text-warning mt-0.5"></i>
                                <span>
                                    Kapasitas PO: <strong><?= $monthlyPoUsed ?? 0 ?> / <?= $monthlyPoLimit ?> unit</strong> periode ini. Sisa kuota digunakan lebih dahulu, lalu kelebihannya dijadwalkan otomatis pada bulan berikutnya.
                                </span>
                            </div>
                        <?php endif; ?>
                    </div>

                    <!-- Status Adaptive Visual Dynamic Hints -->
                    <div class="alert alert-info py-2 px-3 border-0 bg-light-primary text-primary d-flex align-items-center gap-2 fs-7 mb-0" id="orderInfo">
                        <i class="bi bi-info-circle-fill fs-6"></i>
                        <span>Order Ready Stock harus melunasi pembayaran instan tanpa target produksi tambahan.</span>
                    </div>
                </div>

                <!-- DYNAMIC BASKET OR CART DATA MODULE -->
                <div class="card-premium p-4">
                    <h5 class="fw-bold mb-3 d-flex justify-content-between align-items-center border-bottom pb-2">
                        <span class="d-flex align-items-center gap-2">
                            <i class="bi bi-bag-check text-primary"></i> Keranjang Belanja
                        </span>
                        <span class="badge bg-primary rounded-pill fs-7 px-2.5" id="cartCount">0 Item</span>
                    </h5>

                    <!-- Virtual Live Items Stream Stack Container -->
                    <div class="cart-list mb-4">
                        <!-- Initial Standard State View Message Component -->
                        <div class="text-center text-muted py-5" id="emptyCartMsg">
                            <i class="bi bi-basket3 fs-1 text-muted opacity-25 d-block mb-2"></i>
                            <span class="fs-7 fw-medium">Keranjang kosong. Pilih item dari grid kiri.</span>
                        </div>
                        
                        <!-- WADAH BARU: Elemen List Produk Yang Sebenarnya -->
                        <div id="cartItemsWrapper"></div>
                    </div>

                    <!-- Financial Summary Matrices Stack Component -->
                    <div class="totals-box mb-4">
                        <div class="row-line">
                            <span>Unique Line Items</span>
                            <strong id="txtItem" class="text-dark">0</strong>
                        </div>
                        <div class="row-line">
                            <span>Total Accumulative Qty</span>
                            <strong id="txtQty" class="text-dark">0</strong>
                        </div>
                        <div class="row-line">
                            <span>Subtotal Item Value</span>
                            <strong id="txtSubtotal" class="text-dark">Rp 0</strong>
                        </div>
                        <div class="row-line grand-total">
                            <span class="fw-bold">Total Pembayaran</span>
                            <strong id="txtTotal">Rp 0</strong>
                        </div>
                    </div>

                    <!-- Billing Method Intermediary Engine Interfaces -->
                    <div class="mb-3">
                        <label class="form-label">Metode Pembayaran</label>
                        <select
                            class="form-select form-select-md"
                            id="paymentMethod"
                            name="id_payment_method">
                            <option value="">-- Pilih Saluran Pembayaran --</option>
                            <?php foreach($paymentMethods as $pm): ?>
                                <option value="<?= $pm['id_payment_method'] ?>">
                                    <?= esc($pm['nama_metode']) ?>
                                </option>
                            <?php endforeach ?>
                        </select>
                        <div class="invalid-feedback">
                            * Wajib memilih saluran valid jika jumlah bayar bernilai positif (> 0).
                        </div>
                    </div>

                    <!-- Client Direct Payment Injections Controls -->
                    <div class="mb-4">
                        <label class="form-label">Jumlah Uang Dibayar (Cash/Transfer)</label>
                        <div class="input-group">
                            <span class="input-group-text bg-light border-end-0 text-muted fw-semibold">Rp</span>
                            <input
                                type="number"
                                class="form-control border-start-0 fw-bold"
                                id="jumlahBayar"
                                name="jumlah_bayar"
                                min="0"
                                value="0"
                                oninput="onPaidChange()">
                        </div>
                        <small class="text-muted d-block mt-1 fs-7 text-end" id="readyPaidHint">
                            * Sistem otomatis mengunci pelunasan untuk Ready Stock.
                        </small>
                    </div>

                    <!-- Settlement Verification Parameters -->
                    <div class="totals-box bg-white border mb-4">
                        <div class="row-line align-items-center mb-2">
                            <span>Jumlah Diterima</span>
                            <span id="txtPaid" class="fw-semibold text-dark">Rp 0</span>
                        </div>
                        <div class="row-line align-items-center mb-2">
                            <span>Sisa Piutang / Kembalian</span>
                            <span id="txtRemaining" class="fw-bold text-danger">Rp 0</span>
                        </div>
                        <div class="row-line align-items-center">
                            <span>Status Likuiditas</span>
                            <span class="badge-premium bg-secondary text-white" id="badgePaymentStatus">UNPAID</span>
                        </div>
                    </div>

                    <!-- Auxiliary Workflow Custom Notes Textarea Element -->
                    <div class="mb-4">
                        <label class="form-label">Catatan Tambahan & Instruksi Khusus</label>
                        <textarea
                            class="form-control"
                            rows="3"
                            name="notes"
                            placeholder="Tulis detail pesanan khusus, instruksi finishing produksi, atau detail logistik pengiriman barang..."><?= old('notes') ?></textarea>
                    </div>

                    <!-- Core Storage Logic Engine Injections Variables (Hidden Frameworks) -->
                    <input type="hidden" name="total" id="totalInput">
                    <input type="hidden" name="payment_status" id="paymentStatus">
                    <div id="hiddenItemsContainer"></div>

                    <!-- System Critical Command Action Triggers Box Buttons -->
                    <div class="d-flex flex-column gap-2">
                        <button
                            type="button"
                            class="btn btn-light text-danger border border-danger-subtle py-2.5 rounded-3 fw-medium transition shadow-sm fs-7"
                            onclick="clearCart()">
                            <i class="bi bi-trash3 me-1"></i> Kosongkan Isi Keranjang
                        </button>
                        <button
                            type="submit"
                            class="btn btn-primary py-3 rounded-3 fw-bold transition shadow"
                            id="btnSubmit"
                            disabled>
                            <i class="bi bi-cloud-arrow-up-fill me-1"></i> Simpan Transaksi Order
                        </button>
                    </div>

                </div>

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

<script>
// ============================================================
// DATA ENGINE POINTERS 
// ============================================================
const PRODUCTS = <?= json_encode($products) ?>;

// ============================================================
// CORE DATA STATE LIFECYCLE MANAGEMENT
// ============================================================
let cart = [];
let customCounter = 0;

// ============================================================
// SEARCH REAL-TIME ALGORITHMS & UI RENDERS FILTER ENGINE
// ============================================================
const productGrid = document.getElementById('productGrid');
const searchInput = document.getElementById('searchProduct');
const noProduct = document.getElementById('noProductFound');

function filterProducts() {
    const keyword = searchInput.value.trim().toLowerCase();
    const cards = productGrid.querySelectorAll('.product-card[data-name]');
    let visible = 0;

    cards.forEach(card => {
        const name = (card.dataset.name || '').toLowerCase();
        const stock = (card.dataset.stock || '').toLowerCase();
        const custom = (card.dataset.custom || '0');
        let show = true;

        if (keyword !== '') {
            show = name.includes(keyword) ||
                   stock.includes(keyword) ||
                   (keyword === 'custom' && custom === '1') ||
                   (keyword === 'ready' && stock === 'ready') ||
                   (keyword === 'po' && stock === 'po');
        }

        card.style.display = show ? '' : 'none';
        if (show) visible++;
    });

    noProduct.classList.toggle('d-none', visible > 0 || keyword === '');
}

// ============================================================
// COMPATIBILITY ACCELERATED KEYBOARD LISTENERS CONTROLLERS
// ============================================================
searchInput.addEventListener('keydown', function(e){
    if(e.key !== 'Enter') return;
    e.preventDefault();
    const first = productGrid.querySelector('.product-card[style=""], .product-card:not([style])');
    if(first) first.click();
});

window.addEventListener('load', () => {
    searchInput.focus();
    toggleOrderType(); // Initialize layouts
});

// ============================================================
// QUANTITY MODIFIER & ADD-TO-CART TRANSLATION INTERACTIVE INTERFACES
// ============================================================
function addToCart(productId) {
    const product = PRODUCTS.find(p => String(p.id_product) === String(productId));
    if (!product) return;

    const stock = parseInt(product.stok || 0);
    const stockType = String(product.stock_type || 'ready').toLowerCase() === 'po' ? 'po' : 'ready';
    const isCustom = parseInt(product.is_custom || 0);

    if (stockType === 'ready' && stock <= 0) {
        alert('Stok unit produk habis total.');
        return;
    }

    const existing = cart.find(item => !item.isCustom && String(item.id_product) === String(productId));

    if (existing) {
        if (stockType === 'ready' && existing.qty >= stock) {
            alert('Permintaan kuantitas melampaui sisa stok gudang.');
            return;
        }
        existing.qty++;
    } else {
        cart.push({
            key: 'p_' + productId,
            id_product: productId,
            name: product.nama_product,
            harga: parseFloat(product.harga || 0),
            qty: 1,
            description: product.description || '',
            isCustom: false,
            editable: isCustom === 1,
            stock_type: stockType,
            stock: stock
        });
    }
    renderCart();
}

// Satu produk PO menjadikan seluruh transaksi sebagai Pre-Order. Produk ready
// tetap dapat berada di keranjang, tetapi diproses pada alur PO yang sama.
function synchronizeOrderTypeWithCart() {
    const hasPoProduct = cart.some(item => !item.isCustom && item.stock_type === 'po');
    const readyInput = document.getElementById('typeReady');
    const readyLabel = document.querySelector('label[for="typeReady"]');
    const poInput = document.getElementById('typePo');

    readyInput.disabled = hasPoProduct;
    readyLabel.classList.toggle('disabled', hasPoProduct);

    if (hasPoProduct) {
        poInput.checked = true;
    }
}

function addCustomToCart() {
    customCounter++;
    cart.push({
        key: 'custom_' + customCounter,
        id_product: 'custom_' + customCounter,
        name: '',
        harga: 0,
        qty: 1,
        description: '',
        isCustom: true,
        stock_type: 'custom',
        stock: 0
    });
    renderCart();
}

function changeQty(key, delta) {
    const item = cart.find(i => i.key === key);
    if (!item) return;

    const nextQty = item.qty + delta;
    if (nextQty < 1) return;

    if (!item.isCustom && item.stock_type === 'ready' && nextQty > item.stock) {
        alert('Permintaan kuantitas melampaui sisa stok gudang.');
        return;
    }

    item.qty = nextQty;
    renderCart();
}

function updateCustomField(key, field, value) {
    const item = cart.find(i => i.key === key);
    if (!item) return;

    if (field === 'harga') {
        item[field] = parseFloat(value) || 0;
        calculateTotals();
        return;
    }

    item[field] = value;

    if (field === 'name') {
        const cartItem = document.querySelector(`.cart-item[data-item-key="${key}"]`);
        if (cartItem) {
            cartItem.querySelector('.cart-item-name').innerHTML = escapeHtml(item.name) || '<i class="text-muted fs-7">Produk custom tanpa nama</i>';
        }
    }
    calculateTotals(); 
}

function removeItem(key) {
    cart = cart.filter(i => i.key !== key);
    renderCart();
}

function clearCart() {
    if(cart.length === 0) return;
    if(confirm('Apakah Anda yakin ingin mengosongkan isi keranjang ini?')) {
        cart = [];
        renderCart();
    }
}

function formatRupiah(num) {
    num = Math.round(parseFloat(num) || 0);
    return 'Rp ' + num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, '.');
}

function escapeHtml(str) {
    if (!str) return '';
    const div = document.createElement('div');
    div.textContent = str;
    return div.innerHTML;
}

// ============================================================
// UPGRADED PREMIUM DYNAMIC BASKET DOM COMPONENT RENDERS MATRIX
// ============================================================
function renderCart() {
    synchronizeOrderTypeWithCart();
    toggleOrderType();

    const wrapper = document.getElementById('cartItemsWrapper');
    const emptyMsg = document.getElementById('emptyCartMsg');

    if (cart.length === 0) {
        // Jika keranjang kosong, bersihkan wrapper dan tampilkan pesan kosong
        wrapper.innerHTML = '';
        emptyMsg.style.display = 'block';
    } else {
        // HANYA bersihkan wrapper, JANGAN bersihkan cartList, agar emptyMsg tidak terhapus dari HTML!
        wrapper.innerHTML = '';
        emptyMsg.style.display = 'none';

        cart.forEach(item => {
            const subtotal = item.qty * item.harga;
            const div = document.createElement('div');
            div.className = 'cart-item shadow-sm';
            div.dataset.itemKey = item.key;

            let fieldsHtml = '';
            if (item.isCustom) {
                fieldsHtml = `
                    <div class="custom-fields">
                        <input type="text" class="form-control form-control-sm" placeholder="Nama produk custom..."
                            value="${escapeHtml(item.name)}"
                            oninput="updateCustomField('${item.key}', 'name', this.value)">
                        <div class="input-group input-group-sm">
                            <span class="input-group-text bg-light border-end-0">Rp</span>
                            <input type="number" min="0" class="form-control border-start-0" placeholder="Harga satuan..."
                                value="${item.harga}"
                                oninput="updateCustomField('${item.key}', 'harga', this.value)">
                        </div>
                        <textarea class="form-control form-control-sm" rows="2" placeholder="Deskripsi/Spesifikasi detail kustomisasi..."
                            oninput="updateCustomField('${item.key}', 'description', this.value)">${escapeHtml(item.description)}</textarea>
                    </div>
                `;
            }

            div.innerHTML = `
                <div class="cart-item-top">
                    <div>
                        <div class="cart-item-name">${item.isCustom ? (escapeHtml(item.name) || '<i class="text-muted fs-7">Produk custom tanpa nama</i>') : escapeHtml(item.name)}</div>
                        <div class="cart-item-harga fw-medium text-primary">${formatRupiah(item.harga)} <span class="text-muted fw-normal">/ unit</span></div>
                    </div>
                    <button type="button" class="btn-remove" onclick="removeItem('${item.key}')" title="Hapus Item">
                        <i class="bi bi-x-circle-fill"></i>
                    </button>
                </div>

                ${fieldsHtml}

                <div class="d-flex justify-content-between align-items-center mt-3 pt-2 border-top border-light">
                    <div class="qty-control shadow-sm">
                        <button type="button" onclick="changeQty('${item.key}', -1)"><i class="bi bi-dash"></i></button>
                        <span class="qty-value">${item.qty}</span>
                        <button type="button" onclick="changeQty('${item.key}', 1)"><i class="bi bi-plus"></i></button>
                    </div>
                    <div class="subtotal fw-bold text-dark">${formatRupiah(subtotal)}</div>
                </div>
            `;
            wrapper.appendChild(div);
        });
    }

    document.getElementById('cartCount').textContent = cart.reduce((sum, i) => sum + i.qty, 0) + ' Item';
    calculateTotals();
}

// ============================================================
// FINANCIAL MATHEMATIC COMPUTATIONAL BLOCK & SECURITY VERIFICATIONS
// ============================================================
function calculateTotals() {
    const subtotal = cart.reduce((sum, i) => sum + (i.qty * i.harga), 0);
    const total = subtotal;

    document.getElementById('txtItem').textContent = cart.length;
    document.getElementById('txtQty').textContent = cart.reduce((sum, i) => sum + i.qty, 0);
    document.getElementById('txtSubtotal').textContent = formatRupiah(subtotal);
    document.getElementById('txtTotal').textContent = formatRupiah(total);
    document.getElementById('totalInput').value = total;

    const orderType = document.querySelector('input[name="order_type"]:checked').value;
    const paidInput = document.getElementById('jumlahBayar');

    // Jika Ready Stock, paksa nilai pembayaran sama dengan total (lunas)
    if (orderType === 'ready') {
        paidInput.value = total;
        paidInput.readOnly = true;
    } else {
        // Jika PO, buka kunci agar bisa bayar DP (sebagian) atau 0
        paidInput.readOnly = false;
    }

    updateRemainingAndStatus(total);

    const btn = document.getElementById('btnSubmit');
    btn.disabled = cart.length === 0 || total <= 0;
}

function updateRemainingAndStatus(total) {
    total = typeof total === 'number' ? total : parseFloat(document.getElementById('totalInput').value || 0);
    const paid = parseFloat(document.getElementById('jumlahBayar').value || 0);
    const paymentMethod = document.getElementById('paymentMethod');

    let remaining = total - paid;
    if (remaining < 0) remaining = 0;

    document.getElementById('txtPaid').textContent = formatRupiah(paid);
    document.getElementById('txtRemaining').textContent = formatRupiah(remaining);

    const badge = document.getElementById('badgePaymentStatus');
    badge.className = 'badge-premium'; 

    if (paid <= 0) {
        badge.textContent = 'UNPAID';
        badge.classList.add('bg-danger', 'text-white');
        paymentMethod.required = false;
        paymentMethod.classList.remove('is-invalid');
    } else if (paid < total) {
        badge.textContent = 'PARTIAL';
        badge.classList.add('bg-warning', 'text-dark');
        paymentMethod.required = true;
        if (!paymentMethod.value) {
            paymentMethod.classList.add('is-invalid');
        } else {
            paymentMethod.classList.remove('is-invalid');
        }
    } else {
        badge.textContent = 'PAID';
        badge.classList.add('bg-success', 'text-white');
        paymentMethod.required = true;
        if (!paymentMethod.value) {
            paymentMethod.classList.add('is-invalid');
        } else {
            paymentMethod.classList.remove('is-invalid');
        }
    }

    const paymentStatusInput = document.getElementById('paymentStatus');
    if (paymentStatusInput) {
        paymentStatusInput.value = badge.textContent.toLowerCase();
    }
}

function onPaidChange() {
    updateRemainingAndStatus();
}

// ============================================================
// SYSTEM INTERACTION LAYER CONTROLLERS FOR WORKFLOW ENGINE
// ============================================================
function toggleOrderType() {
    synchronizeOrderTypeWithCart();

    const orderType = document.querySelector('input[name="order_type"]:checked').value;
    const targetDateWrap = document.getElementById('targetDateWrap');
    const targetDateInput = document.getElementById('targetDate');
    const readyHint = document.getElementById('readyPaidHint');
    const orderInfo = document.getElementById('orderInfo');

    if (orderType === 'ready') {
        targetDateWrap.classList.add('disabled-look');
        targetDateInput.disabled = true;
        readyHint.style.display = 'block';
        orderInfo.className = "alert alert-info py-2 px-3 border-0 bg-light-primary text-primary d-flex align-items-center gap-2 fs-7 mb-0";
        orderInfo.innerHTML = `<i class="bi bi-info-circle-fill fs-6"></i> <span>Order Ready Stock harus melunasi pembayaran instan tanpa target produksi tambahan.</span>`;
    } else {
        targetDateWrap.classList.remove('disabled-look');
        targetDateInput.disabled = false;
        readyHint.style.display = 'none';
        orderInfo.className = "alert alert-warning py-2 px-3 border-0 text-warning d-flex align-items-center gap-2 fs-7 mb-0";
        const containsPoProduct = cart.some(item => !item.isCustom && item.stock_type === 'po');
        const reason = containsPoProduct
            ? 'Keranjang memuat produk PO, sehingga seluruh order otomatis diproses sebagai Pre-Order.'
            : 'Mode Pre-Order aktif. Anda diperbolehkan menerima pembayaran bertahap (Down Payment / Uang Muka).';
        orderInfo.innerHTML = `<i class="bi bi-exclamation-triangle-fill fs-6"></i> <span>${reason}</span>`;
    }

    // Panggil ulang kalkulasi agar jika berpindah dari PO ke Ready, 
    // Field 'Jumlah Dibayar' otomatis mengikuti harga total.
    calculateTotals();
}

// ============================================================
// SYSTEM CRITICAL SUBMIT ENGINES: BUILD POST DATA MATRIX
// ============================================================
function buildHiddenInputs(event) {
    const container = document.getElementById('hiddenItemsContainer');
    container.innerHTML = '';

    // Validasi dan pembagian kuota dilakukan di server agar tetap benar saat
    // ada order lain masuk bersamaan. Kelebihan PO tidak ditolak: sistem
    // otomatis membaginya ke bulan berikutnya.

    // Validasi produk kustom tanpa nama
    let validationFailed = false;
    cart.forEach((item) => {
        if (item.isCustom && !item.name.trim()) {
            alert('Kesalahan data: Terdapat unit Item Produk Custom yang belum memiliki nama identitas.');
            validationFailed = true;
        }
    });

    if(validationFailed) {
        event.preventDefault();
        return false;
    }

    // Format array POST persis seperti yang diminta Controller CI4 (product[], qty[], price[]).
    // Gunakan DOM API agar karakter khusus pada nama/deskripsi custom tidak merusak value input.
    const appendHiddenInput = (name, value) => {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = name;
        input.value = value ?? '';
        container.appendChild(input);
    };

    cart.forEach((item) => {
        appendHiddenInput('product[]', item.id_product);
        appendHiddenInput('qty[]', item.qty);
        appendHiddenInput('price[]', item.harga);
        appendHiddenInput('product_name[]', item.name);
        appendHiddenInput('description[]', item.description);
        appendHiddenInput('is_custom[]', item.isCustom ? '1' : '0');
    });
    
    // Tambahkan input konfirmasi jika melebihi 5 barang (sesuai controller)
    if (orderType === 'po' && cart.length > 5) {
        appendHiddenInput('po_bulk_confirmed', '1');
    }
    
    return true;
}
</script>

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