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

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

<style>
    /* ===== MODERN SAAS DESIGN SYSTEM TOKENS ===== */
    :root {
        /* Light Mode Defaults */
        --bg-body: #f8fafc;
        --bg-card: #ffffff;
        --bg-card-hover: #f1f5f9;
        --bg-input: #ffffff;
        --bg-accent: #f1f5f9;
        --border-color: #e2e8f0;
        --border-hover: #cbd5e1;
        --text-main: #0f172a;
        --text-sub: #64748b;
        --primary: #4f46e5;
        --primary-hover: #4338ca;
        --primary-light: rgba(79, 70, 229, 0.08);
        --primary-border: rgba(79, 70, 229, 0.25);
        --success: #10b981;
        --warning: #f59e0b;
        --danger: #ef4444;
        --info: #06b6d4;
        --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
        --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.07), 0 2px 4px -2px rgba(0, 0, 0, 0.05);
        --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.05);
        --radius-lg: 16px;
        --radius-md: 12px;
        --radius-sm: 8px;
        --transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
    }

    /* Auto-switch Dark Mode */
    @media (prefers-color-scheme: dark) {
        :root {
            --bg-body: #0b0f19;
            --bg-card: #151e2e;
            --bg-card-hover: #1e293b;
            --bg-input: #0f172a;
            --bg-accent: #1e293b;
            --border-color: #243044;
            --border-hover: #334155;
            --text-main: #f8fafc;
            --text-sub: #94a3b8;
            --primary-light: rgba(79, 70, 229, 0.18);
            --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.3);
            --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.4);
            --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.5);
        }
    }

    [data-bs-theme="dark"] {
        --bg-body: #0b0f19;
        --bg-card: #151e2e;
        --bg-card-hover: #1e293b;
        --bg-input: #0f172a;
        --bg-accent: #1e293b;
        --border-color: #243044;
        --border-hover: #334155;
        --text-main: #f8fafc;
        --text-sub: #94a3b8;
        --primary-light: rgba(79, 70, 229, 0.18);
        --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.3);
        --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.4);
        --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.5);
    }

    /* Outer Wrapper Protection */
    body, .content-wrapper, .main-content, .content, .page-content, main, .edit-order-workspace {
        background-color: var(--bg-body) !important;
        color: var(--text-main) !important;
        transition: var(--transition);
    }

    /* Cards & Components */
    .card-premium {
        background: var(--bg-card);
        border: 1px solid var(--border-color);
        border-radius: var(--radius-lg);
        box-shadow: var(--shadow-md);
        transition: var(--transition);
    }

    /* Product Matrix Grid */
    .product-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
        gap: 14px;
        max-height: calc(100vh - 250px);
        overflow-y: auto;
        padding-right: 4px;
    }

    .product-card {
        position: relative;
        border: 1px solid var(--border-color);
        border-radius: var(--radius-md);
        background: var(--bg-card);
        cursor: pointer;
        overflow: hidden;
        display: flex;
        flex-direction: column;
        height: 100%;
        width: 100%;
        text-align: left;
        padding: 0;
        transition: var(--transition);
    }

    .product-card:hover {
        border-color: var(--primary);
        transform: translateY(-3px);
        box-shadow: var(--shadow-lg);
    }

    /* Thumbnail Gambar Produk */
    .product-card .thumb {
        height: 120px;
        background-color: var(--bg-accent);
        display: flex;
        align-items: center;
        justify-content: center;
        color: var(--text-sub);
        font-size: 28px;
        border-bottom: 1px solid var(--border-color);
        position: relative;
        overflow: hidden;
    }

    .product-card .thumb img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        transition: var(--transition);
    }

    .product-card:hover .thumb img {
        transform: scale(1.08);
    }

    .product-card .body {
        padding: 12px;
        display: flex;
        flex-direction: column;
        flex-grow: 1;
        justify-content: space-between;
    }

    .product-card .name {
        font-size: 13.5px;
        font-weight: 600;
        color: var(--text-main);
        line-height: 1.35;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        min-height: 36px;
    }

    .product-card .price {
        color: var(--primary);
        font-weight: 700;
        font-size: 14px;
        margin-top: 8px;
    }

    /* Badge Indikator Keranjang */
    .cart-indicator-badge {
        position: absolute;
        top: 8px;
        right: 8px;
        background: var(--primary);
        color: #ffffff;
        font-size: 11px;
        font-weight: 700;
        padding: 3px 8px;
        border-radius: 20px;
        box-shadow: var(--shadow-md);
        display: none;
        z-index: 2;
    }

    /* Sticky Cart Side Panel */
    .cart-panel {
        position: sticky;
        top: 1.5rem;
        border: 1px solid var(--border-color);
        border-radius: var(--radius-lg);
        background: var(--bg-card);
        padding: 1.25rem;
        box-shadow: var(--shadow-md);
    }

    .cart-list {
        max-height: 340px;
        overflow-y: auto;
        padding-right: 2px;
        display: flex;
        flex-direction: column;
        gap: 12px;
    }

    .cart-item {
        border: 1px solid var(--border-color);
        border-radius: var(--radius-md);
        padding: 12px;
        background: var(--bg-card);
        transition: var(--transition);
    }

    .cart-item:hover {
        border-color: var(--border-hover);
    }

    .cart-item-top {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        gap: 8px;
    }

    .cart-item-name {
        font-weight: 600;
        font-size: 13.5px;
        color: var(--text-main);
        line-height: 1.3;
    }

    .cart-item-price {
        color: var(--text-sub);
        font-size: 12px;
        margin-top: 2px;
    }

    .btn-remove {
        border: 0;
        background: none;
        color: var(--text-sub);
        transition: var(--transition);
        padding: 2px 6px;
        border-radius: var(--radius-sm);
    }

    .btn-remove:hover {
        color: var(--danger);
        background: rgba(239, 68, 68, 0.1);
    }

    .cart-custom-input {
        background-color: var(--bg-input) !important;
        border: 1px solid var(--border-color) !important;
        color: var(--text-main) !important;
        font-size: 12px;
        border-radius: var(--radius-sm);
    }

    /* Quantity Controls */
    .qty-control {
        display: flex;
        align-items: center;
        gap: 4px;
        background: var(--bg-accent);
        padding: 2px 4px;
        border-radius: var(--radius-sm);
        border: 1px solid var(--border-color);
    }

    .qty-control button {
        width: 24px;
        height: 24px;
        padding: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 4px;
        font-weight: bold;
        background: var(--bg-card);
        border: 1px solid var(--border-color);
        color: var(--text-main);
        transition: var(--transition);
    }

    .qty-control button:hover {
        background: var(--primary);
        color: #ffffff;
        border-color: var(--primary);
    }

    .qty-control strong {
        min-width: 24px;
        text-align: center;
        font-size: 12.5px;
        color: var(--text-main);
    }

    /* Rincian Subtotal & Total */
    .summary-row {
        display: flex;
        justify-content: space-between;
        margin: 6px 0;
        font-size: 13.5px;
        color: var(--text-sub);
    }

    .summary-row strong {
        color: var(--text-main);
    }

    .summary-row.total-row {
        border-top: 1px dashed var(--border-color);
        padding-top: 10px;
        margin-top: 10px;
        font-size: 16px;
    }

    .summary-row.total-row strong {
        color: var(--primary);
        font-size: 18px;
    }

    /* Form Controls */
    .form-control, .form-select {
        background-color: var(--bg-input) !important;
        border-color: var(--border-color) !important;
        color: var(--text-main) !important;
        border-radius: var(--radius-sm);
        padding: 0.5rem 0.75rem;
        font-size: 13.5px;
    }

    .form-control:focus, .form-select:focus {
        border-color: var(--primary) !important;
        box-shadow: 0 0 0 3px var(--primary-light) !important;
    }

    .form-control::placeholder {
        color: var(--text-sub) !important;
        opacity: 0.6;
    }

    .form-label {
        font-weight: 600;
        font-size: 12.5px;
        color: var(--text-sub) !important;
        margin-bottom: 4px;
    }

    /* Scrollbar Aesthetics */
    ::-webkit-scrollbar { width: 5px; }
    ::-webkit-scrollbar-thumb { background: var(--border-color); border-radius: 10px; }
    ::-webkit-scrollbar-thumb:hover { background: var(--text-sub); }

    @media (max-width: 992px) {
        .product-grid { max-height: 380px; }
        .cart-panel { position: static; margin-top: 1.5rem; }
    }
</style>

<?php
    // Normalisasi awal data item dari database
    $initialItems = array_map(static function (array $item): array {
        $isCustom = empty($item['id_product']) || $item['id_product'] === 'custom';
        return [
            'key'         => $isCustom ? 'custom_' . uniqid() : 'p_' . $item['id_product'],
            'id_product'  => $isCustom ? 'custom' : (string) $item['id_product'],
            'name'        => $item['product_name'] ?? ($isCustom ? 'Item Custom' : 'Produk'),
            'description' => $item['description'] ?? '',
            'harga'       => (float) ($item['price'] ?? 0),
            'qty'         => (int) ($item['qty'] ?? 1),
            'isCustom'    => $isCustom,
            'stock_type'  => $isCustom ? 'custom' : strtolower((string) ($item['stock_type'] ?? 'ready'))
        ];
    }, $items ?? []);
?>

<div class="container-fluid py-4 edit-order-workspace">

    <!-- PAGE HEADER -->
    <div class="d-flex flex-column flex-sm-row justify-content-between align-items-sm-center mb-4 gap-3">
        <div>
            <div class="d-flex align-items-center gap-2">
                <h3 class="fw-bold mb-0 text-main">Edit Order</h3>
                <span class="badge bg-primary-subtle text-primary border border-primary-subtle fs-6 px-2.5 py-1 rounded-pill">
                    <?= esc($order['order_number']) ?>
                </span>
            </div>
            <p class="text-muted mb-0 small mt-1">Sesuaikan keranjang belanja, status pesanan, dan detail informasi pelanggan.</p>
        </div>
        <div class="d-flex gap-2">
            <a href="<?= base_url('admin/orders/show/' . $order['id_order']) ?>" class="btn btn-outline-secondary px-3 rounded-pill btn-sm d-inline-flex align-items-center gap-1 fw-medium">
                <i class="bi bi-arrow-left"></i> Kembali ke Detail
            </a>
        </div>
    </div>

    <!-- FLASH MESSAGES -->
    <?php if (session()->getFlashdata('error')): ?>
        <div class="alert alert-danger alert-dismissible fade show rounded-3 shadow-sm border-0 mb-4" role="alert">
            <div class="d-flex align-items-center gap-2">
                <i class="bi bi-exclamation-triangle-fill fs-5"></i>
                <div><?= session()->getFlashdata('error') ?></div>
            </div>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <?php if (session()->getFlashdata('errors')): ?>
        <div class="alert alert-danger alert-dismissible fade show rounded-3 shadow-sm border-0 mb-4" role="alert">
            <div class="fw-bold mb-1 d-flex align-items-center gap-2">
                <i class="bi bi-exclamation-octagon-fill"></i> Terdapat kesalahan pengisian:
            </div>
            <ul class="mb-0 ps-3 small">
                <?php foreach (session()->getFlashdata('errors') as $error): ?>
                    <li><?= esc($error) ?></li>
                <?php endforeach; ?>
            </ul>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <!-- MAIN FORM WRAPPER -->
    <form id="orderForm" action="<?= base_url('admin/orders/update/' . $order['id_order']) ?>" method="post" autocomplete="off" onsubmit="return handleFormSubmit(event)">
        <?= csrf_field() ?>

        <div class="row g-4">
            
            <!-- SEKSI KIRI: KATALOG & PRODUK MATRIX -->
            <div class="col-12 col-lg-7 col-xl-8">
                
                <!-- Search & Custom Action Bar -->
                <div class="card-premium p-3 mb-3">
                    <div class="row g-2 align-items-center">
                        <div class="col">
                            <div class="input-group">
                                <span class="input-group-text bg-transparent border-end-0 text-muted"><i class="bi bi-search"></i></span>
                                <input id="searchProduct" class="form-control border-start-0 ps-1" placeholder="Cari produk berdasarkan nama...">
                                <button type="button" id="btnClearSearch" class="btn btn-link text-muted text-decoration-none d-none" onclick="clearSearch()">
                                    <i class="bi bi-x-circle-fill"></i>
                                </button>
                            </div>
                        </div>
                        <div class="col-auto">
                            <button type="button" class="btn btn-outline-primary btn-sm rounded-3 py-2 px-3 fw-semibold d-flex align-items-center gap-1.5" onclick="addCustomToCart()">
                                <i class="bi bi-plus-lg"></i> Custom Item
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Product Cards Grid (With Improved Image Support) -->
                <div id="productGrid" class="product-grid">
                    <?php foreach ($products as $product): ?>
                        <div class="product-card" 
                             id="product-card-<?= $product['id_product'] ?>"
                             data-id="<?= (int) $product['id_product'] ?>" 
                             data-name="<?= esc(strtolower($product['nama_product'])) ?>" 
                             onclick="addToCart(<?= (int) $product['id_product'] ?>)">
                            
                            <!-- In-Cart Counter Pill -->
                            <span class="cart-indicator-badge" id="badge-qty-<?= $product['id_product'] ?>">0</span>

                           <div class="thumb">
                                <?php 
                                    // Autodeteksi kolom nama foto
                                    $rawPhoto = $product['product_photo'] 
                                            ?? $product['foto'] 
                                            ?? $product['gambar'] 
                                            ?? $product['image'] 
                                            ?? null;
                                ?>

                                <?php if (!empty($rawPhoto)): ?>
                                    <?php 
                                        // Normalisasi URL
                                        $imgUrl = filter_var($rawPhoto, FILTER_VALIDATE_URL) 
                                            ? $rawPhoto 
                                            : base_url('uploads/products/' . $rawPhoto); // GANTI KE $rawPhoto DI SINI
                                    ?>
                                    <img src="<?= esc($imgUrl) ?>" 
                                        alt="<?= esc($product['nama_product'] ?? 'Product Image') ?>" 
                                        loading="lazy" 
                                        onerror="this.style.display='none'; this.nextElementSibling.classList.remove('d-none');">
                                    <!-- Fallback jika gambar gagal terload/link broken -->
                                    <i class="bi bi-box-seam opacity-40 d-none"></i>
                                <?php else: ?>
                                    <!-- Fallback jika data foto memang kosong -->
                                    <i class="bi bi-box-seam opacity-40"></i>
                                <?php endif; ?>
                            </div>


                            <div class="body">
                                <div class="name" title="<?= esc($product['nama_product']) ?>"><?= esc($product['nama_product']) ?></div>
                                <div class="price">Rp <?= number_format((float) $product['harga'], 0, ',', '.') ?></div>
                            </div>
                        </div>
                    <?php endforeach ?>
                </div>

                <!-- Empty State Search -->
                <div id="noProduct" class="text-muted text-center py-5 d-none card-premium">
                    <i class="bi bi-search fs-2 d-block mb-2 opacity-40"></i>
                    <span class="fw-medium">Produk tidak ditemukan.</span>
                    <p class="small text-muted mb-0">Coba kata kunci lain atau gunakan tombol "Custom Item".</p>
                </div>
            </div>

            <!-- SEKSI KANAN: KERANJANG BELANJA & METADATA -->
            <div class="col-12 col-lg-5 col-xl-4">
                <aside class="cart-panel">
                    
                    <!-- Header Keranjang -->
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <div class="d-flex align-items-center gap-2">
                            <i class="bi bi-bag-check-fill text-primary fs-5"></i>
                            <strong class="text-main fs-6">Keranjang Belanja</strong>
                        </div>
                        <div class="d-flex align-items-center gap-2">
                            <span id="cartCount" class="badge bg-primary px-2.5 py-1 rounded-pill">0 item</span>
                            <button type="button" class="btn btn-sm btn-link text-danger text-decoration-none p-0 ms-1" onclick="clearCart()" title="Kosongkan Keranjang">
                                <i class="bi bi-trash"></i>
                            </button>
                        </div>
                    </div>

                    <!-- Item List Stream -->
                    <div id="cartList" class="cart-list"></div>
                    
                    <!-- State Keranjang Kosong -->
                    <div id="emptyCart" class="text-muted text-center py-4 bg-accent rounded-3 border border-dashed mb-3">
                        <i class="bi bi-basket opacity-40 d-block fs-3 mb-1"></i>
                        <span class="small fw-medium">Keranjang masih kosong.</span>
                    </div>

                    <!-- Rincian Biaya -->
                    <div class="border-top pt-3 mt-2">
                        <div class="summary-row">
                            <span>Subtotal</span>
                            <strong id="subtotalText">Rp 0</strong>
                        </div>
                        <div class="summary-row total-row">
                            <strong class="text-main">Total Tagihan</strong>
                            <strong id="totalText">Rp 0</strong>
                        </div>
                    </div>

                    <hr class="my-3">

                    <!-- INFORMASI PELANGGAN & STATUS -->
                    <h6 class="fw-bold text-main mb-3 d-flex align-items-center gap-1.5">
                        <i class="bi bi-person-vcard text-muted"></i> Informasi Pelanggan & Status
                    </h6>

                    <div class="mb-2.5">
                        <label class="form-label">Nama Pelanggan <span class="text-danger">*</span></label>
                        <input class="form-control" name="customer_name" value="<?= esc($order['customer_name']) ?>" placeholder="Masukkan nama..." required>
                    </div>

                    <div class="row g-2 mb-2.5">
                        <div class="col-6">
                            <label class="form-label">No. WhatsApp</label>
                            <input class="form-control" name="customer_phone" value="<?= esc($order['customer_phone'] ?? '') ?>" placeholder="0812345...">
                        </div>
                        <div class="col-6">
                            <label class="form-label">Email</label>
                            <input type="email" class="form-control" name="customer_email" value="<?= esc($order['customer_email'] ?? '') ?>" placeholder="email@domain.com">
                        </div>
                    </div>

                    <div class="row g-2 mb-2.5">
                        <div class="col-6">
                            <label class="form-label">Tipe Order</label>
                            <select class="form-select" name="order_type" id="orderTypeSelect" onchange="handleOrderTypeChange()">
                                <option value="ready" <?= ($order['order_type'] ?? '') === 'ready' ? 'selected' : '' ?>>Ready Stock</option>
                                <option value="po" <?= ($order['order_type'] ?? '') === 'po' ? 'selected' : '' ?>>Pre-Order (PO)</option>
                            </select>
                        </div>
                        <div class="col-6">
                            <label class="form-label">Target Selesai</label>
                            <input type="date" class="form-control" name="target_date" id="targetDateInput" value="<?= esc($order['target_date'] ?? '') ?>">
                            <?php if (($order['order_type'] ?? '') === 'po'): ?>
                                <small class="d-block text-muted mt-1" style="font-size: 0.72rem;">
                                    Jadwal kapasitas akan dihitung ulang otomatis saat disimpan.
                                </small>
                            <?php endif; ?>
                        </div>
                    </div>

                    <?php if (($order['order_type'] ?? '') === 'po' && !empty($productionSchedules)): ?>
                        <div class="mb-3 p-2.5 rounded-3 border bg-light">
                            <div class="small fw-bold text-primary mb-1.5">
                                <i class="bi bi-calendar-range me-1"></i> Alokasi Produksi Bulanan
                            </div>
                            <?php if (($monthlyPoLimit ?? 0) > 0): ?>
                                <div class="small text-muted mb-1">Batas: <?= (int) $monthlyPoLimit ?> unit per bulan</div>
                            <?php endif; ?>
                            <?php foreach ($productionSchedules as $schedule): ?>
                                <div class="d-flex justify-content-between small text-muted">
                                    <span><?= esc(date('m/Y', strtotime($schedule['scheduled_month']))) ?></span>
                                    <strong><?= (int) $schedule['quantity'] ?> unit</strong>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>

                    <div class="mb-2.5">
                        <label class="form-label">Status Alur Order</label>
                        <select class="form-select fw-semibold" name="order_status" id="orderStatusSelect" onchange="updateStatusColor()">
                            <option value="waiting_payment" <?= ($order['order_status'] ?? '') === 'waiting_payment' ? 'selected' : '' ?>>Menunggu Pembayaran</option>
                            <option value="production" <?= ($order['order_status'] ?? '') === 'production' ? 'selected' : '' ?>>Proses Produksi</option>
                            <option value="completed" <?= ($order['order_status'] ?? '') === 'completed' ? 'selected' : '' ?>>Selesai</option>
                            <option value="cancelled" <?= ($order['order_status'] ?? '') === 'cancelled' ? 'selected' : '' ?>>Dibatalkan</option>
                        </select>
                    </div>

                    <div class="mb-4">
                        <label class="form-label">Catatan Pesanan</label>
                        <textarea class="form-control" name="notes" rows="2" placeholder="Catatan instruksi khusus..."><?= esc($order['notes'] ?? '') ?></textarea>
                    </div>

                    <!-- Hidden Inputs Container -->
                    <input type="hidden" name="total" id="totalInput" value="0">
                    <div id="hiddenItems"></div>

                    <!-- Submit Button -->
                    <button id="saveButton" class="btn btn-primary w-100 py-2.5 fw-bold shadow-sm rounded-3 d-flex align-items-center justify-content-center gap-2" type="submit">
                        <i class="bi bi-cloud-arrow-up-fill fs-5"></i> Simpan Perubahan Order
                    </button>
                </aside>
            </div>
        </div>
    </form>
</div>

<!-- JAVASCRIPT ENGINE -->
<script>
// Load Master Data & Initial State
const PRODUCTS = <?= json_encode($products, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) ?>;
let cart = <?= json_encode($initialItems, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) ?>;
let customCounter = 0;

const rupiah = value => 'Rp ' + Math.round(Number(value) || 0).toLocaleString('id-ID');

// Helper Escape HTML
function escapeHtml(str) {
    const div = document.createElement('div');
    div.textContent = str || '';
    return div.innerHTML;
}

// Tambah Produk dari Katalag Grid
function addToCart(productId) {
    const product = PRODUCTS.find(item => String(item.id_product) === String(productId));
    if (!product) return;

    const existing = cart.find(item => !item.isCustom && String(item.id_product) === String(productId));
    if (existing) {
        existing.qty++;
    } else {
        cart.push({
            key: 'p_' + product.id_product,
            id_product: String(product.id_product),
            name: product.nama_product,
            description: product.description || '',
            harga: Number(product.harga || 0),
            qty: 1,
            isCustom: false,
            stock_type: String(product.stock_type || 'ready').toLowerCase()
        });
    }
    renderCart();
}

// Tambah Produk Custom
function addCustomToCart() {
    customCounter++;
    cart.push({
        key: 'custom_' + Date.now() + '_' + customCounter,
        id_product: 'custom',
        name: '',
        description: '',
        harga: 0,
        qty: 1,
        isCustom: true,
        stock_type: 'custom'
    });
    renderCart();
}

// Ubah Kuantitas
function changeQty(key, adjustment) {
    const item = cart.find(row => row.key === key);
    if (!item) return;
    
    item.qty += adjustment;
    if (item.qty < 1) {
        cart = cart.filter(row => row.key !== key);
    }
    renderCart();
}

// Update Input khusus Custom Item secara Live
function updateCustomField(key, field, value) {
    const item = cart.find(i => i.key === key);
    if (!item) return;

    if (field === 'harga') {
        item.harga = parseFloat(value) || 0;
    } else {
        item[field] = value;
    }
    
    if (field === 'name') {
        const cartItemEl = document.querySelector(`.cart-item[data-key="${key}"] .cart-item-name`);
        if (cartItemEl) {
            cartItemEl.innerHTML = escapeHtml(item.name) || '<i class="text-muted small">Custom item tanpa nama</i>';
        }
    }
    
    calculateTotalsOnly();
}

// Hapus Single Item
function removeItem(key) {
    cart = cart.filter(item => item.key !== key);
    renderCart();
}

// Clear Keranjang
function clearCart() {
    if (cart.length === 0) return;
    if (confirm('Kosongkan semua produk di keranjang?')) {
        cart = [];
        renderCart();
    }
}

// Kalkulasi Ringkasan Biaya
function calculateTotalsOnly() {
    const total = cart.reduce((sum, item) => sum + (item.qty * item.harga), 0);
    const totalQty = cart.reduce((sum, item) => sum + item.qty, 0);

    document.getElementById('cartCount').textContent = totalQty + ' item';
    document.getElementById('subtotalText').textContent = rupiah(total);
    document.getElementById('totalText').textContent = rupiah(total);
    document.getElementById('totalInput').value = total;

    const saveBtn = document.getElementById('saveButton');
    saveBtn.disabled = cart.length === 0;
}

// Synchronize Badges pada Product Matrix Grid
function updateProductGridBadges() {
    document.querySelectorAll('.cart-indicator-badge').forEach(badge => {
        badge.style.display = 'none';
        badge.textContent = '0';
    });

    cart.forEach(item => {
        if (!item.isCustom) {
            const badge = document.getElementById(`badge-qty-${item.id_product}`);
            if (badge) {
                badge.textContent = item.qty;
                badge.style.display = 'inline-block';
            }
        }
    });
}

// Render Utama Tampilan Keranjang
function renderCart() {
    handleOrderTypeChange();

    const list = document.getElementById('cartList');
    const empty = document.getElementById('emptyCart');
    list.innerHTML = '';

    if (cart.length === 0) {
        empty.classList.remove('d-none');
    } else {
        empty.classList.add('d-none');

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

            let customFieldsHtml = '';
            if (item.isCustom) {
                customFieldsHtml = `
                    <div class="mt-2 d-flex flex-column gap-1.5">
                        <input type="text" class="form-control cart-custom-input" placeholder="Nama item 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-transparent border-end-0 text-muted fs-7">Rp</span>
                            <input type="number" min="0" class="form-control cart-custom-input border-start-0" placeholder="Harga..."
                                value="${item.harga || ''}"
                                oninput="updateCustomField('${item.key}', 'harga', this.value)">
                        </div>
                        <input type="text" class="form-control cart-custom-input" placeholder="Deskripsi/catatan spesifikasi..."
                            value="${escapeHtml(item.description)}"
                            oninput="updateCustomField('${item.key}', 'description', this.value)">
                    </div>
                `;
            }

            row.innerHTML = `
                <div class="cart-item-top">
                    <div>
                        <div class="cart-item-name">
                            ${item.isCustom ? (escapeHtml(item.name) || '<i class="text-muted small">Custom item tanpa nama</i>') : escapeHtml(item.name)}
                        </div>
                        <div class="cart-item-price">${rupiah(item.harga)} / pcs</div>
                    </div>
                    <button type="button" class="btn-remove" onclick="removeItem('${item.key}')" title="Hapus Item">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>

                ${customFieldsHtml}

                <div class="d-flex justify-content-between align-items-center mt-2.5 pt-2 border-top border-dashed">
                    <div class="qty-control">
                        <button type="button" onclick="changeQty('${item.key}', -1)">−</button>
                        <strong>${item.qty}</strong>
                        <button type="button" onclick="changeQty('${item.key}', 1)">+</button>
                    </div>
                    <strong class="text-main fs-6">${rupiah(subtotal)}</strong>
                </div>
            `;

            list.appendChild(row);
        });
    }

    calculateTotalsOnly();
    updateProductGridBadges();
}

// PENCARIAN PRODUK
const searchInput = document.getElementById('searchProduct');
const btnClearSearch = document.getElementById('btnClearSearch');

searchInput.addEventListener('input', event => {
    const key = event.target.value.toLowerCase().trim();
    let visible = 0;

    btnClearSearch.classList.toggle('d-none', key.length === 0);

    document.querySelectorAll('.product-grid .product-card').forEach(card => {
        const name = (card.dataset.name || '').toLowerCase();
        const match = name.includes(key);
        card.classList.toggle('d-none', !match);
        if (match) visible++;
    });

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

function clearSearch() {
    searchInput.value = '';
    searchInput.dispatchEvent(new Event('input'));
    searchInput.focus();
}

// HANDLER TIPE ORDER & STATUS
function handleOrderTypeChange() {
    const typeSelect = document.getElementById('orderTypeSelect');
    const hasPoProduct = cart.some(item => !item.isCustom && item.stock_type === 'po');
    const readyOption = typeSelect.querySelector('option[value="ready"]');

    readyOption.disabled = hasPoProduct;
    if (hasPoProduct) {
        typeSelect.value = 'po';
    }

    const type = typeSelect.value;
    const targetInput = document.getElementById('targetDateInput');
    
    if (type === 'ready') {
        targetInput.disabled = true;
        targetInput.classList.add('opacity-50');
    } else {
        targetInput.disabled = false;
        targetInput.classList.remove('opacity-50');
    }
}

function updateStatusColor() {
    const select = document.getElementById('orderStatusSelect');
    const val = select.value;
    
    select.classList.remove('text-warning', 'text-info', 'text-success', 'text-danger');
    if (val === 'waiting_payment') select.classList.add('text-warning');
    else if (val === 'production') select.classList.add('text-info');
    else if (val === 'completed') select.classList.add('text-success');
    else if (val === 'cancelled') select.classList.add('text-danger');
}

// INJEKSI INPUT HIDDEN SEBELUM FORM DISUBMIT
function handleFormSubmit(event) {
    if (cart.length === 0) {
        event.preventDefault();
        alert('Keranjang belanja tidak boleh kosong! Pilih produk terlebih dahulu.');
        return false;
    }

    const container = document.getElementById('hiddenItems');
    container.innerHTML = '';

    cart.forEach(item => {
        const fields = [
            ['product[]', item.isCustom ? 'custom' : item.id_product],
            ['product_name[]', item.name || 'Produk Custom'],
            ['description[]', item.description || ''],
            ['qty[]', item.qty],
            ['price[]', item.harga]
        ];

        fields.forEach(([name, value]) => {
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = name;
            input.value = value;
            container.appendChild(input);
        });
    });

    return true;
}

// RUN INITIAL LIFECYCLE
window.addEventListener('DOMContentLoaded', () => {
    renderCart();
    handleOrderTypeChange();
    updateStatusColor();
});
</script>

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