<?php if (auth()->user()->role == 'customer'): ?>
    <div class="modal-header" style="background: #e5e7eb; color: #111827;">
        <h4 class="modal-title" style="color: #111827 !important;"><i class="fas fa-shopping-bag"></i> Buat Pesanan Custom Anda</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close" style="color: #111827; opacity: 0.9;">
            <span aria-hidden="true">×</span>
        </button>
    </div>
<?php else: ?>
    <div class="modal-header">
        <h4 class="modal-title">Tambah Pesanan Custom</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">×</span>
        </button>
    </div>
<?php endif; ?>
<div class="modal-body" style="max-height: 85vh; overflow-y: auto;">
    <?php if (auth()->user()->role == 'customer'): ?>
        <style>
            /* Custom styling untuk customer */
            .item-card .card-body {
                padding: 20px;
                background: #fafafa;
            }

            .form-control:focus {
                border-color: #667eea;
                box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
            }

            .btn-remove-item:hover {
                transform: scale(1.05);
                transition: all 0.2s;
            }

            .shadow-sm {
                box-shadow: 0 .125rem .25rem rgba(102, 126, 234, 0.2) !important;
            }
        </style>
    <?php else: ?>
        <style>
            /* Styling untuk admin/kasir - HANYA untuk form create */

            /* Scope semua styling ke dalam form create */
            #formCreateOrder .item-card .card-header {
                background-color: #007bff !important;
                color: #ffffff !important;
                display: flex !important;
                justify-content: space-between !important;
                align-items: center !important;
                padding: 1rem;
                border-bottom: 1px solid rgba(0, 0, 0, .125);
            }

            #formCreateOrder .item-card .card-header h5 {
                margin-bottom: 0;
                color: #ffffff !important;
                font-size: 1.25rem;
                font-weight: 500;
                flex: 0 0 auto;
            }

            #formCreateOrder .item-card .card-header .fas,
            #formCreateOrder .item-card .card-header .fa {
                color: #ffffff !important;
            }

            /* Button hapus item styling - posisi di kanan */
            #formCreateOrder .item-card .card-header .btn-danger {
                background-color: #dc3545 !important;
                border-color: #dc3545 !important;
                color: #ffffff !important;
                padding: 0.375rem 0.75rem;
                font-size: 0.875rem;
                margin-left: auto !important;
                flex-shrink: 0;
            }

            #formCreateOrder .item-card .card-header .btn-danger:hover {
                background-color: #c82333;
                border-color: #bd2130;
            }

            #formCreateOrder .item-card .card-header .btn-danger .fas,
            #formCreateOrder .item-card .card-header .btn-danger .fa {
                color: #ffffff !important;
            }

            /* Override icon color untuk button di dalam form create */
            #formCreateOrder .btn .fas,
            #formCreateOrder .btn .fa {
                color: inherit !important;
            }

            #formCreateOrder .btn-primary .fas,
            #formCreateOrder .btn-primary .fa {
                color: #ffffff !important;
            }

            #formCreateOrder .btn-success .fas,
            #formCreateOrder .btn-success .fa {
                color: #ffffff !important;
            }

            /* Button Pilih Model - hijau konsisten */
            #formCreateOrder div[id^="modelSelectSection_"] .btn {
                background-color: #28a745 !important;
                border-color: #28a745 !important;
                color: #ffffff !important;
            }

            #formCreateOrder div[id^="modelSelectSection_"] .btn:hover {
                background-color: #218838 !important;
                border-color: #1e7e34 !important;
            }

            #formCreateOrder div[id^="modelSelectSection_"] .btn .fas,
            #formCreateOrder div[id^="modelSelectSection_"] .btn .fa {
                color: #ffffff !important;
            }
        </style>
    <?php endif; ?>
    <form method="POST" action="<?= base_url('permintaan_custom/create') ?>" enctype="multipart/form-data" id="formCreateOrder">
        <?= csrf_field() ?>

        <!-- Customer Selection -->
        <?php if (auth()->user()->role != 'customer'): ?>
            <div class="card mb-3">
                <div class="card-header bg-info text-white">
                    <h6 class="mb-0"><i class="fas fa-user"></i> Informasi Customer</h6>
                </div>
                <div class="card-body">
                    <div class="form-group mb-0">
                        <label class="form-label" for="customer_search">Cari Customer <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <input type="text"
                                class="form-control"
                                id="customer_search"
                                placeholder="Ketik nama atau nomor telepon customer..."
                                autocomplete="off"
                                required>
                            <input type="hidden" name="id_customer" id="id_customer" required>
                            <div class="input-group-append">
                                <button type="button" class="btn btn-success" onclick="showAddCustomerModal(event)">
                                    <i class="fas fa-plus"></i> Tambah Baru
                                </button>
                            </div>
                        </div>
                        <div id="customer_search_results" class="list-group" style="position: absolute; z-index: 1000; width: calc(100% - 30px); display: none; max-height: 300px; overflow-y: auto;"></div>
                        <small class="form-text text-muted">Pilih customer dari hasil pencarian atau tambah customer baru</small>
                    </div>
                </div>
            </div>
        <?php else: ?>
            <input type="hidden" name="id_customer" value="<?= auth()->user()->user_id ?>">
        <?php endif ?>

        <!-- Tanggal & Catatan -->
        <div class="card mb-3">
            <?php if (auth()->user()->role == 'customer'): ?>
                <div class="card-header" style="background: #e5e7eb;">
                    <h6 class="mb-0" style="color: #111827 !important;"><i class="fas fa-calendar-check"></i> Informasi Pesanan</h6>
                </div>
            <?php else: ?>
                <div class="card-header bg-secondary text-white">
                    <h6 class="mb-0"><i class="fas fa-calendar"></i> Jadwal & Catatan</h6>
                </div>
            <?php endif; ?>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="form-label">Tanggal Order</label>
                            <input type="datetime-local" class="form-control" name="tanggal_order" value="<?= date('Y-m-d\TH:i') ?>" readonly required>
                        </div>
                    </div>
                    <div class="col-md-6 d-none">
                        <div class="form-group">
                            <label class="form-label">
                                Perkiraan Tanggal Pengambilan
                                <?php if (auth()->user()->role == 'customer'): ?>
                                    <small class="text-muted">(Akan dikonfirmasi kasir)</small>
                                <?php endif; ?>
                            </label>
                            <input type="date" class="form-control" name="tanggal_pengambilan" min="<?= date('Y-m-d', strtotime('+1 day')) ?>">
                            <small class="text-muted">Opsional - Kasir akan mengkonfirmasi tanggal pengambilan final</small>
                        </div>
                    </div>
                </div>
                <div class="form-group mb-0">
                    <label class="form-label">Catatan untuk Toko (Optional)</label>
                    <textarea class="form-control" name="catatan_pelanggan" placeholder="Catatan khusus untuk pesanan Anda" rows="2"></textarea>
                </div>
            </div>
        </div>

        <!-- STATUS PENGIRIMAN & ALAMAT -->
        <div class="card mb-3">
            <?php if (auth()->user()->role == 'customer'): ?>
                <div class="card-header" style="background: #e5e7eb;">
                    <h6 class="mb-0" style="color: #111827 !important;"><i class="fas fa-shipping-fast"></i> Pengiriman</h6>
                </div>
            <?php else: ?>
                <div class="card-header bg-secondary text-white">
                    <h6 class="mb-0"><i class="fas fa-shipping-fast"></i> Pengiriman</h6>
                </div>
            <?php endif; ?>
            <div class="card-body">
                <div class="form-group">
                    <label class="form-label">Status Pengiriman <span class="text-danger">*</span></label>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="custom-control custom-radio">
                                <input type="radio" class="custom-control-input" id="pengiriman_ambil" name="status_pengiriman" value="1" checked onchange="toggleAlamatPengiriman()">
                                <label class="custom-control-label" for="pengiriman_ambil">
                                    <i class="fas fa-store"></i> Ambil di Toko
                                </label>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="custom-control custom-radio">
                                <input type="radio" class="custom-control-input" id="pengiriman_kirim" name="status_pengiriman" value="2" onchange="toggleAlamatPengiriman()">
                                <label class="custom-control-label" for="pengiriman_kirim">
                                    <i class="fas fa-truck"></i> Kirim ke Alamat
                                </label>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="form-group mb-0" id="alamat_pengiriman_group" style="display: none;">
                    <label class="form-label">Alamat Pengiriman <span class="text-danger">*</span></label>
                    <textarea class="form-control" name="alamat_pengiriman" id="alamat_pengiriman_input" placeholder="Masukkan alamat lengkap untuk pengiriman" rows="3"></textarea>
                    <small class="text-muted">Harap cantumkan alamat lengkap, RT/RW, Kelurahan, Kecamatan, Kota, dan Kode Pos</small>
                </div>
            </div>
        </div>

        <div id="itemsContainer">
            <!-- Items will be added here -->
        </div>

        <!-- Add Item Button -->
        <div class="text-center mb-3">
            <?php if (auth()->user()->role == 'customer'): ?>
                <button type="button" class="btn btn-lg shadow-sm" id="btnAddItem" style="background: #e5e7eb; border: none; color: #111827 !important; border-radius: 25px; padding: 12px 40px;">
                    <i class="fas fa-plus-circle" style="color: #111827;"></i> Tambah Item
                </button>
            <?php else: ?>
                <button type="button" class="btn btn-success btn-lg" id="btnAddItem">
                    <i class="fas fa-plus-circle"></i> Tambah Item Pesanan
                </button>
            <?php endif; ?>
        </div>

        <!-- GRAND TOTAL -->
        <?php if (auth()->user()->role == 'customer'): ?>
            <div class="card shadow-sm" style="border: 2px solid #e5e7eb; border-radius: 15px;">
                <div class="card-header" style="background: #e5e7eb; border-radius: 13px 13px 0 0;">
                    <h5 class="mb-0" style="color: #111827 !important;"><i class="fas fa-calculator"></i> Total Belanja Anda</h5>
                </div>
            <?php else: ?>
                <div class="card border-primary">
                    <div class="card-header bg-primary text-white">
                        <h5 class="mb-0"><i class="fas fa-money-bill-wave"></i> TOTAL PEMBAYARAN</h5>
                    </div>
                <?php endif; ?>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-8">
                            <h3 class="mb-0">Grand Total:</h3>
                            <small class="text-muted">Total dari semua item pesanan</small>
                        </div>
                        <div class="col-md-4 text-right">
                            <h2 class="mb-0 text-primary font-weight-bold">Rp <span id="grandTotal">0</span></h2>
                        </div>
                    </div>
                    <hr>
                    <div class="row">
                        <div class="col-md-6">
                            <strong>Status Pembayaran:</strong>
                            <span class="badge badge-danger">Belum Dibayar</span>
                        </div>
                        <div class="col-md-6 text-right">
                            <small class="text-muted">Pembayaran dapat dilakukan setelah pesanan dikonfirmasi</small>
                        </div>
                    </div>
                </div>
                </div>

                <div class="modal-footer">
                    <?php if (auth()->user()->role == 'customer'): ?>
                        <button type="button" class="btn btn-lg" data-dismiss="modal" style="background: #e0e0e0; border: none; color: #111827 !important; border-radius: 20px; padding: 10px 30px;">
                            <i class="fas fa-times" style="color: #111827;"></i> Batal
                        </button>
                        <button type="submit" class="btn btn-lg shadow" style="background: #e5e7eb; border: none; color: #111827 !important; border-radius: 20px; padding: 10px 30px;">
                            <i class="fas fa-save" style="color: #111827;"></i> Simpan Pesanan
                        </button>
                    <?php else: ?>
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">
                            <i class="fas fa-times"></i> Batal
                        </button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> Simpan Pesanan
                        </button>
                    <?php endif; ?>
                </div>
    </form>
</div>

<!-- Include modal files -->
<?= $this->include('permintaan_custom/modal_select_model') ?>
<?= $this->include('permintaan_custom/modal_select_fabric') ?>
<?= $this->include('permintaan_custom/modal_custom_size') ?>

<script>
    // Gunakan window object untuk menghindari redeclaration error
    if (typeof window.itemCounter === 'undefined') window.itemCounter = 0;
    if (typeof window.currentEditingItemIndex === 'undefined') window.currentEditingItemIndex = null;
    if (typeof window.isFormInitialized === 'undefined') window.isFormInitialized = false;

    // Global reset function untuk dipanggil dari show_lg()
    window.resetFormState = function() {
        window.itemCounter = 0;
        window.currentEditingItemIndex = null;
        window.fabricCounters = {}; // Clear fabric counters
        window.currentEditingFabricIndex = null;
        window.isFormInitialized = false; // PENTING: Reset flag agar form di-initialize ulang

        // JANGAN clear DOM disini - biarkan HTML replacement yang handle
        // Hanya clear global functions untuk prevent conflict
        window.selectModelFromGrid = null;
        window.selectFabricFromGrid = null;
        window.saveCustomSize = null;
        window.deleteCustomSize = null;

        // Unbind event handlers dari modal sebelumnya
        $('#modalKasirOrder, #modal_lg, #detail_modal_lg').off('shown.bs.modal');
        $('#modalKasirOrder, #modal_lg, #detail_modal_lg').off('hidden.bs.modal');
    }; // Initialize form when parent modal is shown
    $('#modalKasirOrder, #modal_lg, #detail_modal_lg').on('shown.bs.modal', function(e) {
        // Only initialize if this is the parent modal being shown AND it's the direct target
        if ((e.target.id === 'modalKasirOrder' || e.target.id === 'modal_lg' || e.target.id === 'detail_modal_lg') && !window.isFormInitialized) {
            // Check if this modal contains the form (bukan child modal)
            if ($(e.target).find('#formCreateOrder').length > 0) {
                initializeForm();
                window.isFormInitialized = true;
            }
        }
    });

    // Reset form when parent modal is hidden - ONLY if it's the main modal
    $('#modalKasirOrder, #modal_lg, #detail_modal_lg').on('hidden.bs.modal', function(e) {
        // Pastikan ini adalah modal utama yang ditutup, bukan child modal
        if (e.target.id === 'detail_modal_lg' && $(e.target).find('#formCreateOrder').length > 0) {
            resetForm();
        }
    });

    // Prevent child modals from closing parent modal
    $('#modalSelectModel, #modalSelectFabric, #modalCustomSize, #modalAddCustomer').on('hide.bs.modal', function(e) {
        e.stopPropagation();
    });

    // Function to close specific modal only without affecting parent modal
    window.closeModalOnly = function(modalId) {
        $(`#${modalId}`).modal('hide');
    };

    // Setup global functions untuk CREATE form - MUST BE DEFINED BEFORE initializeForm()
    function setupGlobalFunctions() {
        // Override global functions from modal files
        window.selectModelFromGrid = function(kodeModel, namaModel, fotoModel, hargaModel) {
            if (window.currentEditingItemIndex !== null) {
                $(`#kode_model_${window.currentEditingItemIndex}`).val(kodeModel);
                $(`#harga_model_${window.currentEditingItemIndex}`).val(hargaModel || 0);
                $(`#modelPreviewImg_${window.currentEditingItemIndex}`).attr('src', '<?= base_url() ?>/' + fotoModel);
                $(`#modelPreviewName_${window.currentEditingItemIndex}`).text(namaModel);
                $(`#modelPreviewCode_${window.currentEditingItemIndex}`).text(kodeModel);
                $(`#modelPreviewPrice_${window.currentEditingItemIndex}`).text(formatRupiah(hargaModel || 0));
                $(`#modelPreview_${window.currentEditingItemIndex}`).show();
                $('#modalSelectModel').modal('hide');
                calculateItemTotal(window.currentEditingItemIndex);
            }
        };

        window.selectFabricFromGrid = function(kodeKain, jenisKain, warna, fotoKain, hargaKain) {
            if (window.currentEditingItemIndex !== null && window.currentEditingFabricIndex !== null) {
                console.log('Fabric selected:', {
                    kodeKain,
                    jenisKain,
                    warna,
                    fotoKain,
                    hargaKain
                });

                const itemIndex = window.currentEditingItemIndex;
                const fabricIndex = window.currentEditingFabricIndex;

                // Update the fabric item in the list
                const fabricItem = $(`#fabricItem_${itemIndex}_${fabricIndex}`);
                fabricItem.find('.fabric-name').text(jenisKain);
                fabricItem.find('.fabric-color').text(warna);
                fabricItem.find('.fabric-code').text(kodeKain);
                fabricItem.find('.fabric-price').text('Rp ' + formatRupiah(hargaKain) + '/m');
                fabricItem.find('.fabric-img').attr('src', '<?= base_url() ?>/' + fotoKain);

                // Update hidden inputs
                fabricItem.find('.fabric-kode-input').val(kodeKain);
                fabricItem.find('.fabric-harga-input').val(hargaKain || 0);

                // Mark as selected and change button to Edit
                fabricItem.attr('data-fabric-selected', 'true');
                fabricItem.find('.fabric-select-btn').removeClass('btn-success').addClass('btn-info');
                fabricItem.find('.fabric-select-btn').html('<i class="fas fa-edit"></i> Edit');

                $('#modalSelectFabric').modal('hide');
                window.currentEditingFabricIndex = null;
                calculateItemTotal(itemIndex);
            }
        };

        window.saveCustomSize = function(measurements) {
            if (window.currentEditingItemIndex !== null) {
                const labels = {
                    'lingkar_dada': 'Lingkar Dada',
                    'lingkar_pinggang': 'Lingkar Pinggang',
                    'lingkar_panggul': 'Lingkar Panggul',
                    'lebar_bahu': 'Lebar Bahu',
                    'panjang_lengan': 'Panjang Lengan',
                    'panjang_gamis': 'Panjang Gamis',
                    'catatan_detail': 'Catatan'
                };

                // Update display
                let html = '';
                for (let key in measurements) {
                    // Skip if value is 0, '0', null, undefined, or empty string
                    if (measurements[key] && measurements[key] !== '0' && measurements[key] !== 0) {
                        const label = labels[key] || key;
                        const unit = key === 'catatan_detail' ? '' : ' cm';
                        html += `<li>${label}: ${measurements[key]}${unit}</li>`;
                    }
                }

                // Show or hide based on data
                if (html) {
                    $(`#customMeasurementsList_${window.currentEditingItemIndex}`).html(html);
                    $(`#customMeasurements_${window.currentEditingItemIndex}`).show();
                    $(`#btnDeleteCustom_${window.currentEditingItemIndex}`).show();
                } else {
                    $(`#customMeasurements_${window.currentEditingItemIndex}`).hide();
                    $(`#btnDeleteCustom_${window.currentEditingItemIndex}`).hide();
                }

                // Update hidden inputs - always set values (empty if not provided)
                const itemCard = $(`.item-card[data-item-index="${window.currentEditingItemIndex}"]`);
                itemCard.find('#lingkar_dada_' + window.currentEditingItemIndex).val(measurements.lingkar_dada || '');
                itemCard.find('#lingkar_pinggang_' + window.currentEditingItemIndex).val(measurements.lingkar_pinggang || '');
                itemCard.find('#lingkar_panggul_' + window.currentEditingItemIndex).val(measurements.lingkar_panggul || '');
                itemCard.find('#lebar_bahu_' + window.currentEditingItemIndex).val(measurements.lebar_bahu || '');
                itemCard.find('#panjang_lengan_' + window.currentEditingItemIndex).val(measurements.panjang_lengan || '');
                itemCard.find('#panjang_gamis_custom_' + window.currentEditingItemIndex).val(measurements.panjang_gamis || '');
                itemCard.find('#catatan_detail_' + window.currentEditingItemIndex).val(measurements.catatan_detail || '');

                // Check if has custom size - if yes, ukuran_standar is optional
                const hasCustomSize = Object.values(measurements).some(val => val && val.toString().trim() !== '');
                const ukuranStandarSelect = $(`#ukuran_standar_${window.currentEditingItemIndex}`);

                if (hasCustomSize) {
                    // Clear standar selection and remove required when using custom
                    ukuranStandarSelect.val('').removeAttr('required');
                } else {
                    // Restore required if no custom measurements
                    ukuranStandarSelect.attr('required', 'required');
                }

                window.currentEditingItemIndex = null;
            }
        };

        window.deleteCustomSize = function(itemIndex) {
            if (confirm('Apakah Anda yakin ingin menghapus ukuran custom untuk item ini?')) {
                // Clear all custom measurement values
                $(`#lingkar_dada_${itemIndex}`).val('');
                $(`#lingkar_pinggang_${itemIndex}`).val('');
                $(`#lingkar_panggul_${itemIndex}`).val('');
                $(`#lebar_bahu_${itemIndex}`).val('');
                $(`#panjang_lengan_${itemIndex}`).val('');
                $(`#panjang_gamis_custom_${itemIndex}`).val('');
                $(`#catatan_detail_${itemIndex}`).val('');

                // Clear display
                $(`#customMeasurementsList_${itemIndex}`).html('');
                $(`#customMeasurements_${itemIndex}`).hide();

                // Restore required untuk ukuran standar
                $(`#ukuran_standar_${itemIndex}`).attr('required', 'required');

                // Hide delete button
                $(`#btnDeleteCustom_${itemIndex}`).hide();

                alert('Ukuran custom berhasil dihapus. Silakan pilih ukuran standar.');
            }
        };
    }

    // Initialize fabric counters for each item
    if (typeof window.fabricCounters === 'undefined') window.fabricCounters = {};
    if (typeof window.currentEditingFabricIndex === 'undefined') window.currentEditingFabricIndex = null;

    // Function to add fabric to an item
    window.addFabricToItem = function(itemIndex) {
        // Initialize fabric counter for this item if not exists
        if (!window.fabricCounters[itemIndex]) {
            window.fabricCounters[itemIndex] = 0;
        }

        window.fabricCounters[itemIndex]++;
        const fabricIndex = window.fabricCounters[itemIndex];

        const fabricItemHtml = `
            <div class="border rounded p-2 mb-2 bg-light" id="fabricItem_${itemIndex}_${fabricIndex}" data-fabric-selected="false">
                <div class="row align-items-center">
                    <div class="col-3">
                        <img src="<?= base_url('assets/images/placeholder.png') ?>" alt="Kain" class="img-fluid rounded fabric-img" style="max-height: 60px; object-fit: cover;">
                    </div>
                    <div class="col-6">
                        <small>
                            <strong class="fabric-name">Pilih Kain</strong><br>
                            <span class="text-muted">Warna: <span class="fabric-color">-</span></span><br>
                            <span class="text-muted">Kode: <span class="fabric-code">-</span></span><br>
                            <span class="text-warning fabric-price">Rp 0/m</span>
                        </small>
                        <!-- Hidden inputs for this fabric -->
                        <input type="hidden" name="kode_jenis_kain_${itemIndex}[]" class="fabric-kode-input" value="">
                        <input type="hidden" name="harga_kain_${itemIndex}[]" class="fabric-harga-input" value="0">
                        <input type="hidden" name="meter_pemakaian_${itemIndex}[]" class="fabric-meter-input" value="0">
                    </div>
                    <div class="col-3">
                        <button type="button" class="btn btn-success btn-sm btn-block mb-1 fabric-select-btn" onclick="editFabricItem(${itemIndex}, ${fabricIndex})">
                            <i class="fas fa-hand-pointer"></i> Pilih Kain
                        </button>
                        <button type="button" class="btn btn-danger btn-sm btn-block" onclick="deleteFabricItem(${itemIndex}, ${fabricIndex})">
                            <i class="fas fa-trash"></i> Delete
                        </button>
                    </div>
                </div>
                <?php if (auth()->user()->role != 'customer'): ?>
                <div class="row mt-2">
                    <div class="col-12">
                        <label class="mb-0"><small>Meter Pemakaian:</small></label>
                            <input type="number" class="form-control form-control-sm fabric-meter-display" step="0.5" min="0" placeholder="0" onchange="updateFabricMeter(${itemIndex}, ${fabricIndex}, this.value)">
                    </div>
                </div>
                <?php else: ?>
                <input type="hidden" class="form-control form-control-sm fabric-meter-display" step="0.5" min="0" value="0" readonly style="background-color: #e9ecef;">
                <?php endif; ?>
            </div>
        `;

        $(`#fabricListContainer_${itemIndex}`).append(fabricItemHtml);
    };

    // Function to edit fabric item - opens modal
    window.editFabricItem = function(itemIndex, fabricIndex) {
        window.currentEditingItemIndex = itemIndex;
        window.currentEditingFabricIndex = fabricIndex;
        $('#modalSelectFabric').modal('show');
    };

    // Function to delete fabric item
    window.deleteFabricItem = function(itemIndex, fabricIndex) {
        if (confirm('Apakah Anda yakin ingin menghapus kain ini?')) {
            $(`#fabricItem_${itemIndex}_${fabricIndex}`).remove();
            calculateItemTotal(itemIndex);
        }
    };

    // Function to update fabric meter
    window.updateFabricMeter = function(itemIndex, fabricIndex, meterValue) {
        $(`#fabricItem_${itemIndex}_${fabricIndex}`).find('.fabric-meter-input').val(meterValue);
        calculateItemTotal(itemIndex);
    };

    function initializeForm() {
        // Clear existing items
        $('#itemsContainer').empty();
        window.itemCounter = 0;

        // Initialize global functions untuk form CREATE
        setupGlobalFunctions();

        // Add first item automatically
        addNewItem();
        toggleModelSection(window.itemCounter);

        // Add item button click
        $('#btnAddItem').off('click').on('click', function() {
            addNewItem();
            toggleModelSection(window.itemCounter);
        });

        // Form validation
        $('#formCreateOrder').off('submit').on('submit', function(e) {
            // Validate alamat pengiriman if status pengiriman = 2 (kirim)
            const statusPengiriman = $('input[name="status_pengiriman"]:checked').val();
            const alamatPengiriman = $('#alamat_pengiriman_input').val().trim();

            if (statusPengiriman == '2' && !alamatPengiriman) {
                e.preventDefault();
                alert('Alamat pengiriman harus diisi jika memilih "Kirim ke Alamat"!');
                $('#alamat_pengiriman_input').focus();
                return false;
            }

            const items = $('.item-card');
            if (items.length === 0) {
                e.preventDefault();
                alert('Minimal harus ada 1 item pesanan!');
                return false;
            }

            // Validate each item
            let isValid = true;
            items.each(function(index) {
                const itemIndex = $(this).data('item-index');
                const modelSelected = $(`#kode_model_${itemIndex}`).val();
                const uploadModelSendiri = $(`#uploadModelSendiri_${itemIndex}`).is(':checked');
                const bawaSendiri = $(`#bawaBajuSendiri_${itemIndex}`).is(':checked');
                const fabricCount = $(`#fabricListContainer_${itemIndex} [id^="fabricItem_${itemIndex}_"]`).length;

                // Check ukuran: either standar OR custom must be filled
                const ukuranStandar = $(`#ukuran_standar_${itemIndex}`).val();
                const hasCustomSize = $(`#customMeasurements_${itemIndex}`).is(':visible');

                // Validate model: if not upload model sendiri, must select model from store
                if (!uploadModelSendiri && !modelSelected) {
                    isValid = false;
                    alert(`Item ${index + 1}: Silakan pilih model dari toko atau centang "Saya upload model sendiri"!`);
                    return false;
                }

                // Validate ukuran: must have either standar OR custom
                if (!ukuranStandar && !hasCustomSize) {
                    isValid = false;
                    alert(`Item ${index + 1}: Silakan pilih ukuran standar atau isi ukuran custom!`);
                    return false;
                }

                if (!bawaSendiri && fabricCount === 0) {
                    isValid = false;
                    alert(`Item ${index + 1}: Silakan tambah minimal 1 kain atau centang "Bawa kain sendiri"!`);
                    return false;
                }

                // Validate that all added fabrics have meter value (skip for customer)
                if (!bawaSendiri) {
                    let fabricValid = true;
                    $(`#fabricListContainer_${itemIndex} [id^="fabricItem_${itemIndex}_"]`).each(function() {
                        const kodeKain = $(this).find('.fabric-kode-input').val();
                        const meter = parseFloat($(this).find('.fabric-meter-input').val()) || 0;

                        if (!kodeKain || kodeKain === '') {
                            fabricValid = false;
                            alert(`Item ${index + 1}: Ada kain yang belum dipilih. Klik tombol "Pilih Kain" untuk memilih kain.`);
                            return false;
                        }

                        <?php if (auth()->user()->role != 'customer'): ?>
                            // Validasi meter hanya untuk non-customer (kasir/admin)
                            if (meter <= 0) {
                                fabricValid = false;
                                alert(`Item ${index + 1}: Semua kain harus memiliki nilai meter pemakaian > 0!`);
                                return false;
                            }
                        <?php endif; ?>
                    });

                    if (!fabricValid) {
                        isValid = false;
                        return false;
                    }
                }
            });

            if (!isValid) {
                e.preventDefault();
                return false;
            }

            // Before submit, collect fabric data and add as arrays per item
            // This prepares data in format: kode_jenis_kain_0[], kode_jenis_kain_1[], etc.
            items.each(function(itemIdx) {
                const itemIndex = $(this).data('item-index');
                const fabricContainer = $(`#fabricListContainer_${itemIndex}`);

                // Collect all fabric codes and meters for this item
                const fabricCodes = [];
                const fabricMeters = [];
                const fabricHargas = [];

                fabricContainer.find(`[id^="fabricItem_${itemIndex}_"]`).each(function() {
                    const kode = $(this).find('.fabric-kode-input').val();
                    const meter = $(this).find('.fabric-meter-input').val();
                    const harga = $(this).find('.fabric-harga-input').val();

                    if (kode) {
                        fabricCodes.push(kode);
                        fabricMeters.push(meter || 0);
                        fabricHargas.push(harga || 0);
                    }
                });

                // Add hidden inputs for this item's fabrics
                // If no fabrics (bawa sendiri), add single empty entry
                if (fabricCodes.length === 0) {
                    $(this).append(`<input type="hidden" name="kode_jenis_kain[]" value="">`);
                    $(this).append(`<input type="hidden" name="meter_pemakaian[]" value="0">`);
                    $(this).append(`<input type="hidden" name="harga_kain[]" value="0">`);
                } else {
                    // For now, we'll only send the first fabric to maintain backend compatibility
                    // TODO: Update backend to handle multiple fabrics per item
                    $(this).append(`<input type="hidden" name="kode_jenis_kain[]" value="${fabricCodes[0]}">`);
                    $(this).append(`<input type="hidden" name="meter_pemakaian[]" value="${fabricMeters[0]}">`);
                    $(this).append(`<input type="hidden" name="harga_kain[]" value="${fabricHargas[0]}">`);

                    // Store additional fabrics as JSON for future enhancement
                    if (fabricCodes.length > 1) {
                        const additionalFabrics = [];
                        for (let i = 1; i < fabricCodes.length; i++) {
                            additionalFabrics.push({
                                kode: fabricCodes[i],
                                meter: fabricMeters[i],
                                harga: fabricHargas[i]
                            });
                        }
                        $(this).append(`<input type="hidden" name="additional_fabrics[]" value='${JSON.stringify(additionalFabrics)}'>`);
                    }
                }
            });
        });
    }

    function resetForm() {
        window.isFormInitialized = false;
        window.itemCounter = 0;
        window.currentEditingItemIndex = null;
        window.fabricCounters = {}; // Clear fabric counters
        $('#itemsContainer').empty();
        if ($('#formCreateOrder')[0]) {
            $('#formCreateOrder')[0].reset();
        }
        // Clear global functions
        window.selectModelFromGrid = null;
        window.selectFabricFromGrid = null;
        window.saveCustomSize = null;
    }

    $(document).ready(function() {
        // If form is already visible (direct page load), initialize it
        if ($('#formCreateOrder').is(':visible')) {
            initializeForm();
            window.isFormInitialized = true;
        }
    });

    // Global function untuk dipanggil dari show_lg()
    window.initializeCurrentForm = function() {
        if ($('#formCreateOrder').length && !window.isFormInitialized) {
            console.log('Initializing CREATE form from show_lg trigger...');
            initializeForm();
            window.isFormInitialized = true;
        }
    };

    function addNewItem() {
        window.itemCounter++;
        const itemIndex = window.itemCounter;

        const itemHtml = `
        <?php if (auth()->user()->role == 'customer'): ?>
        <div class="card mb-3 shadow-sm item-card" data-item-index="${itemIndex}" style="border: 2px solid #d1d5db; border-radius: 12px;">
            <div class="card-header d-flex justify-content-between align-items-center" style="background: #ffffff; color: #111827; border-bottom: 2px solid #e5e7eb; border-radius: 10px 10px 0 0;">
                <h5 class="mb-0" style="color: #111827 !important;">
                    <i class="fas fa-box-open" style="color: #111827;"></i> Item #${itemIndex}
                </h5>
                <button type="button" class="btn btn-sm btn-danger" onclick="removeItem(${itemIndex})">
                    <i class="fas fa-trash"></i> Hapus Item
                </button>
            </div>
            <div class="card-body">
        <?php else: ?>
        <div class="card mb-3 border-primary item-card" data-item-index="${itemIndex}">
            <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                <h5 class="mb-0">
                    <i class="fas fa-box-open"></i> Item #${itemIndex}
                </h5>
                <button type="button" class="btn btn-sm btn-danger" onclick="removeItem(${itemIndex})">
                    <i class="fas fa-trash"></i> Hapus Item
                </button>
            </div>
            <div class="card-body">
        <?php endif; ?>
                <!-- Hidden fields for this item -->
                <input type="hidden" name="kode_model[]" id="kode_model_${itemIndex}">
                <input type="hidden" name="upload_model_sendiri[]" id="upload_model_sendiri_${itemIndex}" value="0">
                <input type="hidden" name="bawa_kain_sendiri[]" id="bawa_kain_sendiri_${itemIndex}" value="0">
                
                <!-- Hidden fields for prices -->
                <input type="hidden" name="harga_model[]" id="harga_model_${itemIndex}" value="0">
                <input type="hidden" name="ongkos_jahit_custom[]" id="ongkosJahitCustom_${itemIndex}" value="0">
                
                <!-- Hidden fields for custom measurements - default empty -->
                <input type="hidden" name="lingkar_dada[]" id="lingkar_dada_${itemIndex}" value="">
                <input type="hidden" name="lingkar_pinggang[]" id="lingkar_pinggang_${itemIndex}" value="">
                <input type="hidden" name="lingkar_panggul[]" id="lingkar_panggul_${itemIndex}" value="">
                <input type="hidden" name="lebar_bahu[]" id="lebar_bahu_${itemIndex}" value="">
                <input type="hidden" name="panjang_lengan[]" id="panjang_lengan_${itemIndex}" value="">
                <input type="hidden" name="panjang_gamis_custom[]" id="panjang_gamis_custom_${itemIndex}" value="">
                <input type="hidden" name="catatan_detail[]" id="catatan_detail_${itemIndex}" value="">

                <div class="row">
                    <!-- MODEL SECTION -->
                    <div class="col-md-6">
                        <div class="card h-100 mb-3 mb-md-0">
                            <?php if (auth()->user()->role == 'customer'): ?>
                            <div class="card-header" style="background: #e5e7eb; color: #111827;">
                            <?php else: ?>
                            <div class="card-header bg-success text-white">
                            <?php endif; ?>
                                <strong><i class="fas fa-shirt"></i> 1. Pilih Model Gamis</strong>
                            </div>
                            <div class="card-body">
                                <div class="form-group">
                                    <label class="custom-control custom-checkbox mb-2">
                                        <input type="checkbox" class="custom-control-input" id="uploadModelSendiri_${itemIndex}" onchange="toggleModelSection(${itemIndex})">
                                        <span class="custom-control-label">Saya upload model sendiri</span>
                                    </label>
                                </div>
                                <div id="modelSelectSection_${itemIndex}">
                                <?php if (auth()->user()->role == 'customer'): ?>
                                <button type="button" class="btn btn-block shadow-sm" onclick="openModelSelector(${itemIndex})" style="background: #e5e7eb; border: none; color: #111827 !important; font-weight: 500;">
                                <?php else: ?>
                                <button type="button" class="btn btn-success btn-block" onclick="openModelSelector(${itemIndex})">
                                <?php endif; ?>
                                    <i class="fas fa-search" style="color: #111827;"></i> Pilih Model
                                </button>
                                <div id="modelPreview_${itemIndex}" class="mt-3" style="display: none;">
                                    <div class="border border-success rounded p-2 bg-light">
                                        <div class="text-center">
                                            <img id="modelPreviewImg_${itemIndex}" src="" alt="Model" style="max-height: 120px; object-fit: cover;" class="img-fluid mb-2 rounded">
                                        </div>
                                        <p class="mb-1 text-center"><strong id="modelPreviewName_${itemIndex}"></strong></p>
                                        <small class="text-muted d-block text-center">Kode: <span id="modelPreviewCode_${itemIndex}"></span></small>
                                        <small class="text-success d-block text-center font-weight-bold">Ongkos Pengerjaan: Rp <span id="modelPreviewPrice_${itemIndex}">0</span></small>
                                    </div>
                                </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- KAIN SECTION -->
                    <div class="col-md-6">
                        <div class="card h-100">
                            <?php if (auth()->user()->role == 'customer'): ?>
                            <div class="card-header" style="background: #e5e7eb; color: #111827;">
                            <?php else: ?>
                            <div class="card-header bg-warning text-dark">
                            <?php endif; ?>
                                <strong><i class="fas fa-fabric"></i> 2. Pilih Jenis Kain</strong>
                            </div>
                            <div class="card-body">
                                <div class="form-group">
                                    <label class="custom-control custom-checkbox mb-2">
                                        <input type="checkbox" class="custom-control-input" id="bawaBajuSendiri_${itemIndex}" onchange="toggleFabricSection(${itemIndex})">
                                        <span class="custom-control-label">Saya bawa kain sendiri</span>
                                    </label>
                                </div>
                                <div id="fabricSelectSection_${itemIndex}">
                                    <?php if (auth()->user()->role == 'customer'): ?>
                                    <button type="button" class="btn btn-block btn-sm shadow-sm mb-2" onclick="addFabricToItem(${itemIndex})" style="background: #e5e7eb; border: none; color: #111827 !important; font-weight: 500;">
                                    <?php else: ?>
                                    <button type="button" class="btn btn-primary btn-block btn-sm mb-2" onclick="addFabricToItem(${itemIndex})">
                                    <?php endif; ?>
                                        <i class="fas fa-plus" style="color: #111827;"></i> Tambah Kain
                                    </button>
                                    
                                    <!-- Container untuk list kain yang dipilih -->
                                    <div id="fabricListContainer_${itemIndex}">
                                        <!-- Fabric items will be added here -->
                                    </div>
                                    
                                    <!-- Hidden inputs untuk kain akan ditambahkan secara dinamis -->
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <hr class="my-3">

                <!-- ONGKOS JAHIT CUSTOM (Tampil jika kedua checkbox dicentang) -->
                <div id="ongkosJahitSection_${itemIndex}" style="display: none;" class="alert alert-info">
                    <h6><i class="fas fa-money-bill-wave"></i> Ongkos Pengerjaan (Upload Model + Bawa Kain Sendiri)</h6>
                    <div class="form-group mb-0">
                        <label for="ongkosJahitCustomInput_${itemIndex}">Masukkan Harga Ongkos Jahit:</label>
                        <input type="number" class="form-control" id="ongkosJahitCustomInput_${itemIndex}" placeholder="Contoh: 150000" min="0" step="1000" onchange="updateOngkosJahitCustom(${itemIndex})">
                        <small class="text-muted">Ongkos jahit untuk item dengan model custom dan bawa kain sendiri</small>
                    </div>
                </div>

                <hr class="my-3">

                <!-- REFERENSI GAMBAR -->
                <div class="form-group" id="ImageReferenceSection_${itemIndex}">
                    <label class="form-label"><i class="fas fa-image"></i> Upload Gambar Referensi (Optional)</label>
                    <div class="input-group">
                        <div class="custom-file">
                            <input type="file" class="custom-file-input" id="gambarReferensi_${itemIndex}" name="gambar_referensi[]" accept="image/*" onchange="previewImage(${itemIndex})">
                            <label class="custom-file-label" for="gambarReferensi_${itemIndex}">Pilih file...</label>
                        </div>
                    </div>
                    <small class="form-text text-muted">Unggah gambar referensi untuk desain yang Anda inginkan</small>
                    <div id="previewReferensi_${itemIndex}" class="mt-2 text-center" style="display: none;">
                        <img id="gambarReferensiPreview_${itemIndex}" src="" alt="Preview" style="max-height: 150px; object-fit: cover;" class="img-fluid rounded border">
                    </div>
                </div>

                <hr class="my-3">

                <!-- UKURAN -->
                <div class="row">
                    <div class="col-md-8">
                        <div class="form-group">
                            <label class="form-label"><i class="fas fa-ruler-combined"></i> 3. Ukuran Standar</label>
                            <select class="form-control ukuran-standar-select" id="ukuran_standar_${itemIndex}" name="ukuran_gamis[]">
                                <option value="">-- Pilih Ukuran atau Gunakan Custom --</option>
                                <option value="S">S (Small)</option>
                                <option value="M">M (Medium)</option>
                                <option value="L">L (Large)</option>
                                <option value="XL">XL (Extra Large)</option>
                                <option value="XXL">XXL (Double XL)</option>
                            </select>
                            <small class="text-muted">Pilih ukuran standar atau klik "Ukuran Custom" (salah satu harus diisi)</small>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label d-block">&nbsp;</label>
                        <button type="button" class="btn btn-info btn-block mb-2" onclick="openCustomSize(${itemIndex})">
                            <i class="fas fa-plus"></i> Ukuran Custom
                        </button>
                        <button type="button" class="btn btn-danger btn-block btn-sm" onclick="deleteCustomSize(${itemIndex})" style="display: none;" id="btnDeleteCustom_${itemIndex}">
                            <i class="fas fa-trash"></i> Hapus Ukuran Custom
                        </button>
                    </div>
                </div>

                <div id="customMeasurements_${itemIndex}" class="mt-2" style="display: none;">
                    <div class="alert alert-info mb-0">
                        <strong>Ukuran Custom:</strong>
                        <ul id="customMeasurementsList_${itemIndex}" class="mb-0 mt-2"></ul>
                    </div>
                </div>

                <hr class="my-3">

                <!-- JUMLAH -->
                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group mb-0">
                            <label class="form-label"><i class="fas fa-sort-numeric-up"></i> 4. Jumlah (Pcs)</label>
                            <input type="number" class="form-control jumlah-input" id="jumlah_${itemIndex}" name="jumlah_pcs[]" min="1" value="1" required onchange="calculateItemTotal(${itemIndex})">
                        </div>
                    </div>
                </div>
                
                <hr class="my-3">
                
                <!-- TOTAL ITEM -->
                <div class="alert alert-warning mb-0">
                    <strong><i class="fas fa-calculator"></i> Total Item #${itemIndex}:</strong>
                    <h4 class="mb-0 mt-2">Rp <span id="totalItem_${itemIndex}">0</span></h4>
                    <small>
                        <div id="breakdownItem_${itemIndex}">
                            <strong>Model:</strong> Rp <span class="model-price">0</span> x <span class="jumlah-pcs">1</span> pcs = Rp <span class="model-subtotal">0</span><br>
                            <strong>Kain:</strong><br>
                            <div class="kain-breakdown ml-2">Tidak ada kain / Bawa sendiri</div>
                            <strong>Total Kain:</strong> Rp <span id="totalKain_${itemIndex}" class="kain-subtotal">0</span>
                        </div>
                    </small>
                </div>
            </div>
        </div>
        `;

        $('#itemsContainer').append(itemHtml);
        updateItemNumbers();
        calculateGrandTotal();
    }

    function removeItem(itemIndex) {
        if ($('.item-card').length <= 1) {
            alert('Minimal harus ada 1 item pesanan!');
            return;
        }

        if (confirm('Apakah Anda yakin ingin menghapus item ini?')) {
            $(`.item-card[data-item-index="${itemIndex}"]`).remove();
            updateItemNumbers();
            calculateGrandTotal();
        }
    }

    function updateItemNumbers() {
        const totalItems = $('.item-card').length;
        $('.item-card').each(function(index) {
            $(this).find('h5').html(`<i class="fas fa-box-open" style="color: #111827;"></i> Item #${index + 1}`).css('color', '#111827');

            // Hide/show delete button based on item count
            const deleteBtn = $(this).find('.btn-danger[onclick^="removeItem"]');
            if (totalItems <= 1) {
                deleteBtn.hide();
            } else {
                deleteBtn.show();
            }
        });
    }

    // Calculate item total
    function calculateItemTotal(itemIndex) {
        const hargaModel = parseFloat($(`#harga_model_${itemIndex}`).val()) || 0;
        const jumlah = parseInt($(`#jumlah_${itemIndex}`).val()) || 1;
        const bawaSendiri = $(`#bawaBajuSendiri_${itemIndex}`).is(':checked');
        const uploadModelSendiri = $(`#uploadModelSendiri_${itemIndex}`).is(':checked');
        const ongkosJahitCustom = parseFloat($(`#ongkosJahitCustom_${itemIndex}`).val()) || 0;

        let subtotalModel = hargaModel * jumlah;

        // If both upload model sendiri and bawa kain sendiri, use ongkos jahit custom instead
        // if (uploadModelSendiri && bawaSendiri) {
        if (uploadModelSendiri) {
            subtotalModel = ongkosJahitCustom * jumlah;
        }

        // Calculate total from multiple fabrics
        let subtotalKain = 0;
        let fabricBreakdown = '';

        if (!bawaSendiri) {
            $(`#fabricListContainer_${itemIndex} [id^="fabricItem_${itemIndex}_"]`).each(function() {
                const hargaKain = parseFloat($(this).find('.fabric-harga-input').val()) || 0;
                const meter = parseFloat($(this).find('.fabric-meter-input').val()) || 0;
                const fabricName = $(this).find('.fabric-name').text();

                const fabricSubtotal = hargaKain * meter * jumlah;
                subtotalKain += fabricSubtotal;

                if (hargaKain > 0 && meter > 0) {
                    fabricBreakdown += `${fabricName}: Rp ${formatRupiah(hargaKain)}/m x ${meter}m x ${jumlah} pcs = Rp ${formatRupiah(fabricSubtotal)}<br>`;
                }
            });
        }

        const totalItem = subtotalModel + subtotalKain;

        // Update breakdown display
        const breakdown = $(`#breakdownItem_${itemIndex}`);

        if (uploadModelSendiri && bawaSendiri) {
            breakdown.find('.model-price').text('Ongkos Jahit: ' + formatRupiah(ongkosJahitCustom));
        } else {
            breakdown.find('.model-price').text(formatRupiah(hargaModel));
        }

        breakdown.find('.jumlah-pcs').text(jumlah);
        breakdown.find('.model-subtotal').text(formatRupiah(subtotalModel));

        if (fabricBreakdown) {
            breakdown.find('.kain-breakdown').html(fabricBreakdown);
        } else {
            breakdown.find('.kain-breakdown').html('Tidak ada kain / Bawa sendiri');
        }
        breakdown.find('.kain-subtotal').text(formatRupiah(subtotalKain));

        // Update total item
        $(`#totalItem_${itemIndex}`).text(formatRupiah(totalItem));

        // Update grand total
        calculateGrandTotal();
    }

    // Calculate grand total
    function calculateGrandTotal() {
        let grandTotal = 0;
        $('.item-card').each(function() {
            const itemIndex = $(this).data('item-index');
            const totalText = $(`#totalItem_${itemIndex}`).text();
            const total = parseFloat(totalText.replace(/\./g, '')) || 0;
            grandTotal += total;
        });
        $('#grandTotal').text(formatRupiah(grandTotal));
    }

    // Format number to Rupiah
    function formatRupiah(number) {
        return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
    }

    function toggleModelSection(itemIndex) {
        const isChecked = $(`#uploadModelSendiri_${itemIndex}`).is(':checked');
        if (isChecked) {
            $(`#modelSelectSection_${itemIndex}`).hide();
            $(`#ImageReferenceSection_${itemIndex}`).show();
            $(`#kode_model_${itemIndex}`).val('');
            $(`#harga_model_${itemIndex}`).val(0);
            $(`#upload_model_sendiri_${itemIndex}`).val(1);
        } else {
            $(`#ImageReferenceSection_${itemIndex}`).hide();
            $(`#modelSelectSection_${itemIndex}`).show();
            $(`#upload_model_sendiri_${itemIndex}`).val(0);
        }
        checkShowOngkosJahit(itemIndex);
        calculateItemTotal(itemIndex);
    }

    function toggleFabricSection(itemIndex) {
        const isChecked = $(`#bawaBajuSendiri_${itemIndex}`).is(':checked');
        if (isChecked) {
            $(`#fabricSelectSection_${itemIndex}`).hide();
            // Clear all fabric items when "bawa sendiri" is checked
            $(`#fabricListContainer_${itemIndex}`).empty();
            $(`#bawa_kain_sendiri_${itemIndex}`).val(1);
        } else {
            $(`#fabricSelectSection_${itemIndex}`).show();
            $(`#bawa_kain_sendiri_${itemIndex}`).val(0);
        }
        checkShowOngkosJahit(itemIndex);
        calculateItemTotal(itemIndex);
    }

    function checkShowOngkosJahit(itemIndex) {
        const uploadModelSendiri = $(`#uploadModelSendiri_${itemIndex}`).is(':checked');
        const bawaSendiri = $(`#bawaBajuSendiri_${itemIndex}`).is(':checked');
        const isNotCustomer = "<?php echo auth()->user()->role != 'customer' ? '1' : '0'; ?>" === '1';

        // if (uploadModelSendiri && bawaSendiri && isNotCustomer) {
        if (uploadModelSendiri && isNotCustomer) {
            $(`#ongkosJahitSection_${itemIndex}`).show();
        } else {
            $(`#ongkosJahitSection_${itemIndex}`).hide();
            $(`#ongkosJahitCustomInput_${itemIndex}`).val('');
            $(`#ongkosJahitCustom_${itemIndex}`).val(0);
        }
    }

    function updateOngkosJahitCustom(itemIndex) {
        const value = parseFloat($(`#ongkosJahitCustomInput_${itemIndex}`).val()) || 0;
        $(`#ongkosJahitCustom_${itemIndex}`).val(value);
        calculateItemTotal(itemIndex);
    }

    function previewImage(itemIndex) {
        const input = document.getElementById(`gambarReferensi_${itemIndex}`);
        const file = input.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                $(`#gambarReferensiPreview_${itemIndex}`).attr('src', e.target.result);
                $(`#previewReferensi_${itemIndex}`).show();
            };
            reader.readAsDataURL(file);

            // Update label
            const fileName = file.name;
            $(`#gambarReferensi_${itemIndex}`).next('.custom-file-label').html(fileName);
        }
    }

    function openModelSelector(itemIndex) {
        window.currentEditingItemIndex = itemIndex;
        $('#modalSelectModel').modal('show');
    }

    function openFabricSelector(itemIndex) {
        window.currentEditingItemIndex = itemIndex;
        $('#modalSelectFabric').modal('show');
    }

    function openCustomSize(itemIndex) {
        window.currentEditingItemIndex = itemIndex;

        // Load existing data from hidden inputs (if editing existing item)
        const lingkarDada = $(`#lingkar_dada_${itemIndex}`).val();
        const lingkarPinggang = $(`#lingkar_pinggang_${itemIndex}`).val();
        const lingkarPanggul = $(`#lingkar_panggul_${itemIndex}`).val();
        const lebarBahu = $(`#lebar_bahu_${itemIndex}`).val();
        const panjangLengan = $(`#panjang_lengan_${itemIndex}`).val();
        const panjangGamis = $(`#panjang_gamis_custom_${itemIndex}`).val();
        const catatanDetail = $(`#catatan_detail_${itemIndex}`).val();

        // Populate modal form fields
        $('#lingkar_dada').val(lingkarDada || '');
        $('#lingkar_pinggang').val(lingkarPinggang || '');
        $('#lingkar_panggul').val(lingkarPanggul || '');
        $('#lebar_bahu').val(lebarBahu || '');
        $('#panjang_lengan').val(panjangLengan || '');
        $('#panjang_gamis').val(panjangGamis || '');
        $('#catatan_detail').val(catatanDetail || '');

        $('#modalCustomSize').modal('show');
    }

    // ============= CUSTOMER AUTOCOMPLETE SEARCH =============
    <?php if (auth()->user()->role != 'customer'): ?>
        let customerSearchTimeout;
        $('#customer_search').on('keyup', function() {
            clearTimeout(customerSearchTimeout);
            const query = $(this).val();

            if (query.length < 2) {
                $('#customer_search_results').hide().empty();
                return;
            }

            customerSearchTimeout = setTimeout(function() {
                $.ajax({
                    url: '<?= base_url('customer/search') ?>',
                    method: 'GET',
                    data: {
                        q: query
                    },
                    dataType: 'json',
                    success: function(data) {
                        const results = $('#customer_search_results');
                        results.empty();

                        if (data.length > 0) {
                            data.forEach(function(customer) {
                                const item = $(`
                                <a href="#" class="list-group-item list-group-item-action" data-id="${customer.id_customer}">
                                    <div class="d-flex w-100 justify-content-between">
                                        <h6 class="mb-1">${customer.nama}</h6>
                                        <small>${customer.telepon}</small>
                                    </div>
                                </a>
                            `);

                                item.on('click', function(e) {
                                    e.preventDefault();
                                    $('#customer_search').val(customer.nama);
                                    $('#id_customer').val(customer.id_customer);
                                    results.hide();
                                });

                                results.append(item);
                            });
                            results.show();
                        } else {
                            results.html('<div class="list-group-item">Tidak ada customer ditemukan</div>').show();
                        }
                    }
                });
            }, 300);
        });

        // Hide results when clicking outside
        $(document).on('click', function(e) {
            if (!$(e.target).closest('#customer_search, #customer_search_results').length) {
                $('#customer_search_results').hide();
            }
        });

        // Show Add Customer Modal
        function showAddCustomerModal(event) {
            if (event) {
                event.preventDefault();
                event.stopPropagation();
            }
            $('#modalAddCustomer').modal({
                backdrop: 'static',
                keyboard: false
            });
        }

        // Close Add Customer Modal (without closing parent)
        function closeAddCustomerModal(event) {
            if (event) {
                event.preventDefault();
                event.stopPropagation();
            }
            $('#modalAddCustomer').modal('hide');
            $('#formAddCustomer')[0].reset();
            $('#error_message').html('');
        }

        // Save new customer with async/await
        $('#formAddCustomer').on('submit', async function(e) {
            e.preventDefault();


            // Disable submit button dan tampilkan loading
            const submitBtn = $('#btnSaveCustomer');
            submitBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Menyimpan...');
            $('#error_message').html('');

            try {
                const response = await $.ajax({
                    url: '<?= base_url('customer/create_ajax') ?>',
                    method: 'POST',
                    data: $(this).serialize(),
                    dataType: 'json'
                });

                if (response.success) {
                    // Set customer data
                    $('#customer_search').val(response.data.nama);
                    $('#id_customer').val(response.data.id_customer);

                    // Close modal using dedicated function
                    closeAddCustomerModal(null);

                    // Show success message with credentials
                    const credentials = `Customer berhasil ditambahkan!\\n\\nInformasi Login:\\nUsername: ${response.data.username}\\nPassword: ${response.data.password}\\n\\nHarap catat informasi ini untuk diberikan kepada customer.`;
                    alert(credentials);
                } else {
                    // Show error message
                    let errorMsg = response.message;
                    if (response.errors) {
                        errorMsg += '<ul>';
                        for (let field in response.errors) {
                            errorMsg += '<li>' + response.errors[field] + '</li>';
                        }
                        errorMsg += '</ul>';
                    }
                    $('#error_message').html('<div class="alert alert-danger">' + errorMsg + '</div>');
                }
            } catch (error) {
                console.error('Error:', error);
                $('#error_message').html('<div class="alert alert-danger">Terjadi kesalahan saat menyimpan customer. Silakan coba lagi.</div>');
            } finally {
                // Reset button state
                submitBtn.prop('disabled', false).html('<i class="fas fa-save"></i> Simpan Customer');
            }
        });

        // Toggle Password Visibility
        $('#togglePassword').on('click', function() {
            const passwordField = $('#password_customer');
            const icon = $('#togglePasswordIcon');

            if (passwordField.attr('type') === 'password') {
                passwordField.attr('type', 'text');
                icon.removeClass('fa-eye').addClass('fa-eye-slash');
            } else {
                passwordField.attr('type', 'password');
                icon.removeClass('fa-eye-slash').addClass('fa-eye');
            }
        });

        // Toggle Password Confirm Visibility
        $('#togglePasswordConfirm').on('click', function() {
            const passwordConfirmField = $('#password_confirm_customer');
            const icon = $('#togglePasswordConfirmIcon');

            if (passwordConfirmField.attr('type') === 'password') {
                passwordConfirmField.attr('type', 'text');
                icon.removeClass('fa-eye').addClass('fa-eye-slash');
            } else {
                passwordConfirmField.attr('type', 'password');
                icon.removeClass('fa-eye-slash').addClass('fa-eye');
            }
        });
    <?php endif; ?>

    // Function to toggle alamat pengiriman display
    function toggleAlamatPengiriman() {
        const statusPengiriman = $('input[name="status_pengiriman"]:checked').val();
        if (statusPengiriman == '2') {
            $('#alamat_pengiriman_group').show();
            $('#alamat_pengiriman_input').attr('required', 'required');
        } else {
            $('#alamat_pengiriman_group').hide();
            $('#alamat_pengiriman_input').removeAttr('required');
            $('#alamat_pengiriman_input').val(''); // Clear value when hidden
        }
    }
</script>

<!-- Modal Add Customer -->
<?php if (auth()->user()->role != 'customer'): ?>
    <div class="modal fade" id="modalAddCustomer" tabindex="-1" data-backdrop="static" data-keyboard="false">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-success text-white">
                    <h5 class="modal-title"><i class="fas fa-user-plus"></i> Tambah Customer Baru</h5>
                    <button type="button" class="close text-white" onclick="closeAddCustomerModal(event)">
                        <span>&times;</span>
                    </button>
                </div>
                <form id="formAddCustomer">
                    <?= csrf_field() ?>
                    <div class="modal-body">
                        <div id="error_message"></div>

                        <div class="form-group">
                            <label>Nama Lengkap <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="nama" required>
                        </div>

                        <div class="form-group d-none">
                            <label for="new_username">Username <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="new_username" name="username">
                        </div>

                        <div class="form-group">
                            <label>Nomor Telepon <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="no_telp" required minlength="10" maxlength="20">
                            <small class="form-text text-muted">Minimal 10 digit</small>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" onclick="closeAddCustomerModal(event)">Batal</button>
                        <button type="submit" class="btn btn-success" id="btnSaveCustomer">
                            <i class="fas fa-save"></i> Simpan Customer
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
<?php endif; ?>