<?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-edit"></i> Revisi 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">Revisi 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 edit */

            /* Scope semua styling ke dalam form edit */
            #formEditOrder .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);
            }

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

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

            /* Button hapus item styling - posisi di kanan */
            #formEditOrder .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;
            }

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

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

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

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

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

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

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

            #formEditOrder div[id^="modelSelectSection_"] .btn .fas,
            #formEditOrder div[id^="modelSelectSection_"] .btn .fa {
                color: #ffffff !important;
            }
        </style>
    <?php endif; ?>
    <form method="POST" action="<?= base_url('permintaan_custom/edit/' . $data->kode_permintaan_custom) ?>" enctype="multipart/form-data" id="formEditOrder">
        <?= 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="id_customer">Pilih Customer</label>
                        <input type="hidden" name="id_customer" value="<?= $data->id_customer ?>">
                        <select class="custom-select" id="id_customer" required disabled>
                            <option value="">--- Pilih Customer ---</option>
                            <?php foreach ($customer as $cstm): ?>
                                <option value="<?= $cstm->id_customer ?>" <?= $cstm->id_customer == $data->id_customer ? "selected" : '' ?>><?= $cstm->nama ?></option>
                            <?php endforeach; ?>
                        </select>
                    </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; color: #111827;">
                    <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', strtotime($data->tanggal_order)) ?>" readonly required>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="form-label">
                                <?php if (auth()->user()->role == 'customer'): ?>
                                    Perkiraan Tanggal Pengambilan <small class="text-muted">(Akan dikonfirmasi kasir)</small>
                                <?php else: ?>
                                    Tanggal Pengambilan <small class="text-muted">(Konfirmasi final)</small>
                                <?php endif; ?>
                            </label>
                            <input type="date" class="form-control" name="tanggal_pengambilan" value="<?= isset($data->tanggal_pengambilan) && $data->tanggal_pengambilan ? date('Y-m-d', strtotime($data->tanggal_pengambilan)) : '' ?>" min="<?= date('Y-m-d', strtotime('+1 day')) ?>">
                            <small class="text-muted">
                                <?php if (auth()->user()->role == 'customer'): ?>
                                    Kasir akan mengkonfirmasi tanggal pengambilan final
                                <?php else: ?>
                                    Tetapkan tanggal pengambilan untuk customer
                                <?php endif; ?>
                            </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"><?= $data->catatan_pelanggan ?? '' ?></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_edit" name="status_pengiriman" value="1" <?= (!isset($data->status_pengiriman) || $data->status_pengiriman == 1) ? 'checked' : '' ?> onchange="toggleAlamatPengirimanEdit()">
                                <label class="custom-control-label" for="pengiriman_ambil_edit">
                                    <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_edit" name="status_pengiriman" value="2" <?= (isset($data->status_pengiriman) && $data->status_pengiriman == 2) ? 'checked' : '' ?> onchange="toggleAlamatPengirimanEdit()">
                                <label class="custom-control-label" for="pengiriman_kirim_edit">
                                    <i class="fas fa-truck"></i> Kirim ke Alamat
                                </label>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="form-group mb-0" id="alamat_pengiriman_group_edit" style="display: <?= (isset($data->status_pengiriman) && $data->status_pengiriman == 2) ? 'block' : 'none' ?>;">
                    <label class="form-label">Alamat Pengiriman <span class="text-danger">*</span></label>
                    <textarea class="form-control" name="alamat_pengiriman" id="alamat_pengiriman_input_edit" placeholder="Masukkan alamat lengkap untuk pengiriman" rows="3" <?= (isset($data->status_pengiriman) && $data->status_pengiriman == 2) ? 'required' : '' ?>><?= $data->alamat_pengiriman ?? '' ?></textarea>
                    <small class="text-muted">Harap cantumkan alamat lengkap, RT/RW, Kelurahan, Kecamatan, Kota, dan Kode Pos</small>
                </div>
            </div>
        </div>

        <!-- MULTIPLE ITEMS CONTAINER -->
        <div id="itemsContainer">
            <!-- Items will be loaded 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; color: #111827; 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>
                            <?php if (isset($data->status_pelunasan)): ?>
                                <span class="badge badge-<?= $data->status_pelunasan == 2 ? 'success' : 'danger' ?>">
                                    <?= $data->status_pelunasan == 2 ? 'Lunas' : 'Belum Dibayar' ?>
                                </span>
                            <?php else: ?>
                                <span class="badge badge-danger">Belum Dibayar</span>
                            <?php endif; ?>
                        </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 Perubahan
                        </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> Update 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.currentEditingFabricIndex === 'undefined') window.currentEditingFabricIndex = null;
    if (typeof window.isFormInitialized === 'undefined') window.isFormInitialized = false;
    if (typeof window.fabricCounters === 'undefined') window.fabricCounters = {};

    // Existing data from backend - gunakan window object untuk menghindari redeclaration
    if (typeof window.existingItems === 'undefined') {
        window.existingItems = <?= json_encode($detail_model) ?>;
    }
    var existingItems = window.existingItems;

    // Global reset function untuk dipanggil dari show_lg()
    window.resetFormState = function() {
        window.itemCounter = 0;
        window.currentEditingItemIndex = null;
        window.currentEditingFabricIndex = null;
        window.isFormInitialized = false;
        window.fabricCounters = {};
    };

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

    $(document).ready(function() {
        // Prevent double initialization
        if (window.isFormInitialized) {
            return;
        }
        window.isFormInitialized = true;

        // Load existing items
        if (existingItems && existingItems.length > 0) {
            existingItems.forEach((item, index) => {
                // Parse additional_fabrics if it's a string
                if (typeof item.additional_fabrics === 'string' && item.additional_fabrics) {
                    try {
                        item.additional_fabrics = JSON.parse(item.additional_fabrics);
                    } catch (e) {
                        console.error('Error parsing additional_fabrics:', e);
                    }
                }

                loadExistingItem(item);
                toggleModelSection(window.itemCounter);
            });
        }

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

        // Form validation
        $('#formEditOrder').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_edit').val().trim();

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

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

            // Collect fabrics for each item
            items.each(function() {
                const itemIndex = $(this).data('item-index');
                const fabricsArray = [];
                let totalMeterForItem = 0;

                const totalFabricCards = $(`#fabricListContainer_${itemIndex} .fabric-item`).length;
                console.log(`Item ${itemIndex}: Collecting ${totalFabricCards} fabric(s)`);

                $(`#fabricListContainer_${itemIndex} .fabric-item`).each(function(index) {
                    const fabricIndex = $(this).data('fabric-index');
                    const kode = $(`#fabric_kode_${itemIndex}_${fabricIndex}`).val();
                    const meter = $(`#fabric_meter_${itemIndex}_${fabricIndex}`).val();
                    const harga = $(`#fabric_harga_${itemIndex}_${fabricIndex}`).val();
                    const nama = $(`#fabric_nama_${itemIndex}_${fabricIndex}`).val();
                    const warna = $(`#fabric_warna_${itemIndex}_${fabricIndex}`).val();
                    const foto = $(`#fabric_foto_${itemIndex}_${fabricIndex}`).val();

                    // Check kode saja, meter boleh 0 (untuk customer yang belum input meter)
                    if (kode) {
                        const meterValue = parseFloat(meter) || 0;
                        totalMeterForItem += meterValue;

                        // First fabric = primary, rest = additional
                        if (index === 0) {
                            $(`#kode_jenis_kain_${itemIndex}`).val(kode);
                            $(`#harga_kain_${itemIndex}`).val(harga);
                        } else {
                            fabricsArray.push({
                                kode: kode,
                                meter: meterValue,
                                harga_per_meter: parseFloat(harga),
                                nama_jenis_kain: nama,
                                warna: warna,
                                foto_jenis_kain: foto
                            });
                        }
                    }
                });

                // Update total meter untuk item ini (dari semua fabric)
                $(`#meter_${itemIndex}`).val(totalMeterForItem);

                // Update hidden field with JSON (only additional fabrics, not primary)
                if (fabricsArray.length > 0) {
                    const jsonValue = JSON.stringify(fabricsArray);
                    $(`#additional_fabrics_${itemIndex}`).val(jsonValue);
                    console.log(`✅ Item ${itemIndex}: Primary + ${fabricsArray.length} additional fabric(s)`);
                } else {
                    $(`#additional_fabrics_${itemIndex}`).val('');
                }
            });

            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 ukuranStandar = $(`#ukuran_standar_${itemIndex}`).val();

                // Check if has custom measurements
                const hasCustom = $(`#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();

                // 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 fabric: check if any fabric is selected in fabricListContainer
                const fabricsWithData = $(`#fabricListContainer_${itemIndex} .fabric-item[data-fabric-selected="true"]`).length;
                if (!bawaSendiri && fabricsWithData === 0) {
                    isValid = false;
                    alert(`Item ${index + 1}: Silakan pilih minimal 1 jenis kain atau centang "Bawa kain sendiri"!`);
                    return false;
                }

                // Validasi ukuran: harus ada ukuran standar ATAU custom
                if (!ukuranStandar && !hasCustom) {
                    isValid = false;
                    alert(`Item ${index + 1}: Silakan pilih ukuran standar atau isi ukuran custom!`);
                    return false;
                }
            });

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

            // === SHOW SUMMARY BEFORE SUBMIT ===
            let summaryMessage = '📋 RINGKASAN DATA YANG AKAN DISIMPAN:\n\n';
            items.each(function(idx) {
                const itemIndex = $(this).data('item-index');
                const totalFabrics = $(`#fabricListContainer_${itemIndex} .fabric-item`).length;
                const additionalFabricsJson = $(`#additional_fabrics_${itemIndex}`).val();
                const additionalCount = additionalFabricsJson ? JSON.parse(additionalFabricsJson).length : 0;

                summaryMessage += `Item ${idx + 1}:\n`;
                summaryMessage += `  - Total Kain: ${totalFabrics} (1 primary + ${additionalCount} additional)\n`;
                summaryMessage += `  - Additional Fabrics JSON: ${additionalFabricsJson ? 'Ada' : 'Kosong'}\n\n`;
            });

            console.log(summaryMessage);

            // Show alert if any item has only 1 fabric
            items.each(function() {
                const itemIndex = $(this).data('item-index');
                const totalFabrics = $(`#fabricListContainer_${itemIndex} .fabric-item`).length;
                if (totalFabrics === 1) {
                    console.warn(`⚠️ WARNING: Item ${itemIndex} hanya punya 1 kain!`);
                }
            });

            // === FINAL VERIFICATION BEFORE SUBMIT ===
            console.log('\n🚀 === FINAL FORM DATA VERIFICATION ===');
            const formData = new FormData($('#editForm')[0]);

            console.log('📦 All POST parameters:');
            for (let pair of formData.entries()) {
                if (pair[0] === 'additional_fabrics[]') {
                    console.log(`  ${pair[0]} = ${pair[1]}`);
                    if (pair[1]) {
                        try {
                            const parsed = JSON.parse(pair[1]);
                            console.log(`    ↳ Parsed:`, parsed);
                        } catch (e) {
                            console.log(`    ↳ Parse error:`, e.message);
                        }
                    }
                }
            }

            console.log('=== END VERIFICATION ===\n');
        });
    });

    // Function to add new empty item
    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; ?>
                <input type="hidden" name="kode_model[]" id="kode_model_${itemIndex}">
                <input type="hidden" name="kode_jenis_kain[]" id="kode_jenis_kain_${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">
                <input type="hidden" name="ongkos_jahit_custom[]" id="ongkos_jahit_custom_${itemIndex}" value="0">

                <input type="hidden" name="harga_model[]" id="harga_model_${itemIndex}" value="0">
                <input type="hidden" name="harga_kain[]" id="harga_kain_${itemIndex}" value="0">

                <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="">
                <input type="hidden" name="additional_fabrics[]" id="additional_fabrics_${itemIndex}" value="">

                <div class="row">
                    <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">Harga: Rp <span id="modelPreviewPrice_${itemIndex}">0</span></small>
                                    </div>
                                </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <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>
                                    
                                    <div id="fabricListContainer_${itemIndex}">
                                        <!-- Fabric items will be added here -->
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <hr class="my-3">

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

                <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[]" required>
                                <option value="">-- Pilih Ukuran --</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>
                        </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">

                <div class="row">
                    <input type="hidden" class="meter-input" id="meter_${itemIndex}" name="meter_pemakaian[]" value="0">
                    <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">

                <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}">
                            Model: Rp <span class="model-price">0</span> x <span class="jumlah-pcs">1</span> pcs = Rp <span class="model-subtotal">0</span><br>
                            Kain: Rp <span class="kain-price">0</span>/m x <span class="meter-val">0</span>m x <span class="jumlah-pcs">1</span> pcs = Rp <span class="kain-subtotal">0</span>
                        </div>
                    </small>
                </div>
            </div>
        </div>
        `;

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

    // Function to load existing item with data
    function loadExistingItem(item) {
        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; ?>
                <input type="hidden" name="kode_model[]" id="kode_model_${itemIndex}" value="${item.kode_model || ''}">
                <input type="hidden" name="kode_jenis_kain[]" id="kode_jenis_kain_${itemIndex}" value="${item.kode_jenis_kain || ''}">
                <input type="hidden" name="upload_model_sendiri[]" id="upload_model_sendiri_${itemIndex}" value="${item.upload_model_sendiri || 0}">
                <input type="hidden" name="bawa_kain_sendiri[]" id="bawa_kain_sendiri_${itemIndex}" value="${item.bawa_kain_sendiri || 0}">
                <input type="hidden" name="ongkos_jahit_custom[]" id="ongkos_jahit_custom_${itemIndex}" value="${item.ongkos_jahit_custom || 0}">
                
                <input type="hidden" name="harga_model[]" id="harga_model_${itemIndex}" value="${item.ongkos_pengerjaan || 0}">
                <input type="hidden" name="harga_kain[]" id="harga_kain_${itemIndex}" value="${item.harga_per_meter || 0}">
                
                <input type="hidden" name="lingkar_dada[]" id="lingkar_dada_${itemIndex}" value="${item.lingkar_dada || ''}">
                <input type="hidden" name="lingkar_pinggang[]" id="lingkar_pinggang_${itemIndex}" value="${item.lingkar_pinggang || ''}">
                <input type="hidden" name="lingkar_panggul[]" id="lingkar_panggul_${itemIndex}" value="${item.lingkar_panggul || ''}">
                <input type="hidden" name="lebar_bahu[]" id="lebar_bahu_${itemIndex}" value="${item.lebar_bahu || ''}">
                <input type="hidden" name="panjang_lengan[]" id="panjang_lengan_${itemIndex}" value="${item.panjang_lengan || ''}">
                <input type="hidden" name="panjang_gamis_custom[]" id="panjang_gamis_custom_${itemIndex}" value="${item.panjang_gamis || ''}">
                <input type="hidden" name="catatan_detail[]" id="catatan_detail_${itemIndex}" value="${item.catatan_detail || ''}">
                <input type="hidden" name="additional_fabrics[]" id="additional_fabrics_${itemIndex}" value="">

                <div class="row">
                    <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})" ${(item.upload_model_sendiri == 1 || item.upload_model_sendiri == '1') ? 'checked' : ''}>
                                        <span class="custom-control-label">Saya upload model sendiri</span>
                                    </label>
                                </div>
                                <div id="modelSelectSection_${itemIndex}" style="${(item.upload_model_sendiri == 1 || item.upload_model_sendiri == '1') ? 'display: none;' : ''}">
                                <?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="${item.foto_model ? '' : 'display: none;'}">
                                    <div class="border border-success rounded p-2 bg-light">
                                        <div class="text-center">
                                            <img id="modelPreviewImg_${itemIndex}" src="${item.foto_model ? '<?= base_url() ?>/' + item.foto_model : ''}" 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}">${item.nama_model || ''}</strong></p>
                                        <small class="text-muted d-block text-center">Kode: <span id="modelPreviewCode_${itemIndex}">${item.kode_model || ''}</span></small>
                                        <small class="text-success d-block text-center font-weight-bold">Harga: Rp <span id="modelPreviewPrice_${itemIndex}">${formatRupiah(item.ongkos_pengerjaan || 0)}</span></small>
                                    </div>
                                </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <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})" ${(item.bawa_kain_sendiri == 1 || item.bawa_kain_sendiri == '1') ? 'checked' : ''}>
                                        <span class="custom-control-label">Saya bawa kain sendiri</span>
                                    </label>
                                </div>
                                <div id="fabricSelectSection_${itemIndex}" style="${(item.bawa_kain_sendiri == 1 || item.bawa_kain_sendiri == '1') ? 'display: none;' : ''}">
                                    <?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>
                                    
                                    <div id="fabricListContainer_${itemIndex}">
                                        <!-- Fabric items will be added here -->
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <hr class="my-3">

                <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="${item.gambar_referensi ? '' : 'display: none;'}">
                        <img id="gambarReferensiPreview_${itemIndex}" src="${item.gambar_referensi ? '<?= base_url() ?>/' + item.gambar_referensi : ''}" alt="Preview" style="max-height: 150px; object-fit: cover;" class="img-fluid rounded border">
                    </div>
                </div>

                <hr class="my-3">

                <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" ${item.ukuran_gamis == 'S' ? 'selected' : ''}>S (Small)</option>
                                <option value="M" ${item.ukuran_gamis == 'M' ? 'selected' : ''}>M (Medium)</option>
                                <option value="L" ${item.ukuran_gamis == 'L' ? 'selected' : ''}>L (Large)</option>
                                <option value="XL" ${item.ukuran_gamis == 'XL' ? 'selected' : ''}>XL (Extra Large)</option>
                                <option value="XXL" ${item.ukuran_gamis == 'XXL' ? 'selected' : ''}>XXL (Double XL)</option>
                            </select>
                        </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">

                <div class="row">
                    <input type="hidden" class="meter-input" id="meter_${itemIndex}" name="meter_pemakaian[]" value="${item.meter_pemakaian || 0}">
                    <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="${item.jumlah_pcs || 1}" required onchange="calculateItemTotal(${itemIndex})">
                        </div>
                    </div>
                </div>

                <hr class="my-3">

                <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}">
                            Model: Rp <span class="model-price">0</span> x <span class="jumlah-pcs">1</span> pcs = Rp <span class="model-subtotal">0</span><br>
                            Kain: Rp <span class="kain-price">0</span>/m x <span class="meter-val">0</span>m x <span class="jumlah-pcs">1</span> pcs = Rp <span class="kain-subtotal">0</span>
                        </div>
                    </small>
                </div>
            </div>
        </div>
        `;

        $('#itemsContainer').append(itemHtml);
        updateItemNumbers();
        loadCustomMeasurements(itemIndex, item);
        loadExistingFabrics(itemIndex, item);
        calculateItemTotal(itemIndex);
    }

    // Multi-fabric functions
    window.addFabricToItem = function(itemIndex) {
        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 fabric-item" id="fabricItem_${itemIndex}_${fabricIndex}" data-fabric-index="${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>
                        <input type="hidden" id="fabric_kode_${itemIndex}_${fabricIndex}" class="fabric-kode-input" value="">
                        <input type="hidden" id="fabric_harga_${itemIndex}_${fabricIndex}" class="fabric-harga-input" value="0">
                        <input type="hidden" id="fabric_meter_${itemIndex}_${fabricIndex}" class="fabric-meter-input" value="0">
                        <input type="hidden" id="fabric_nama_${itemIndex}_${fabricIndex}" class="fabric-nama-input" value="">
                        <input type="hidden" id="fabric_warna_${itemIndex}_${fabricIndex}" class="fabric-warna-input" value="">
                        <input type="hidden" id="fabric_foto_${itemIndex}_${fabricIndex}" class="fabric-foto-input" value="">
                    </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');
    };

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

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

    function loadExistingFabrics(itemIndex, item) {
        // Load primary fabric first (if exists and not "bawa sendiri")
        if (item.kode_jenis_kain && item.bawa_kain_sendiri != 1 && item.bawa_kain_sendiri != '1') {

            if (!window.fabricCounters[itemIndex]) {
                window.fabricCounters[itemIndex] = 0;
            }

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

            const primaryFabricHtml = `
                <div class="border rounded p-2 mb-2 bg-light fabric-item" id="fabricItem_${itemIndex}_${fabricIndex}" data-fabric-index="${fabricIndex}" data-fabric-selected="true">
                    <div class="row align-items-center">
                        <div class="col-3">
                            <img src="${item.foto_jenis_kain ? '<?= base_url() ?>/' + item.foto_jenis_kain : '<?= 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">${item.nama_jenis_kain || 'Kain Utama'}</strong>
                                <span class="badge badge-primary badge-sm">Utama</span><br>
                                <span class="text-muted">Warna: <span class="fabric-color">${item.warna || '-'}</span></span><br>
                                <span class="text-muted">Kode: <span class="fabric-code">${item.kode_jenis_kain || '-'}</span></span><br>
                                <span class="text-warning fabric-price">Rp ${formatRupiah(item.harga_per_meter || 0)}/m</span>
                            </small>
                            <input type="hidden" id="fabric_kode_${itemIndex}_${fabricIndex}" class="fabric-kode-input" value="${item.kode_jenis_kain || ''}">
                            <input type="hidden" id="fabric_harga_${itemIndex}_${fabricIndex}" class="fabric-harga-input" value="${item.harga_per_meter || 0}">
                            <input type="hidden" id="fabric_meter_${itemIndex}_${fabricIndex}" class="fabric-meter-input" value="${item.meter_pemakaian || 0}">
                            <input type="hidden" id="fabric_nama_${itemIndex}_${fabricIndex}" class="fabric-nama-input" value="${item.nama_jenis_kain || ''}">
                            <input type="hidden" id="fabric_warna_${itemIndex}_${fabricIndex}" class="fabric-warna-input" value="${item.warna || ''}">
                            <input type="hidden" id="fabric_foto_${itemIndex}_${fabricIndex}" class="fabric-foto-input" value="${item.foto_jenis_kain || ''}">
                        </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-edit"></i> Edit
                            </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" value="${item.meter_pemakaian || 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="${item.meter_pemakaian || 0}" readonly style="background-color: #e9ecef;">
                    <?php endif; ?>
                </div>
            `;

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

        // Load additional fabrics
        if (item.additional_fabrics) {
            try {
                const additionalFabrics = typeof item.additional_fabrics === 'string' ?
                    JSON.parse(item.additional_fabrics) :
                    item.additional_fabrics;

                if (Array.isArray(additionalFabrics) && additionalFabrics.length > 0) {
                    console.log(`✅ Loading ${additionalFabrics.length} additional fabric(s) for item ${itemIndex}`);

                    additionalFabrics.forEach((fabric, index) => {
                        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 fabric-item" id="fabricItem_${itemIndex}_${fabricIndex}" data-fabric-index="${fabricIndex}" data-fabric-selected="true">
                                <div class="row align-items-center">
                                    <div class="col-3">
                                        <img src="${fabric.foto_jenis_kain ? '<?= base_url() ?>/' + fabric.foto_jenis_kain : '<?= 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">${fabric.nama_jenis_kain || 'Kain'}</strong>
                                            <span class="badge badge-secondary badge-sm">Tambahan</span><br>
                                            <span class="text-muted">Warna: <span class="fabric-color">${fabric.warna || '-'}</span></span><br>
                                            <span class="text-muted">Kode: <span class="fabric-code">${fabric.kode_jenis_kain || fabric.kode || '-'}</span></span><br>
                                            <span class="text-warning fabric-price">Rp ${formatRupiah(fabric.harga_per_meter || 0)}/m</span>
                                        </small>
                                        <input type="hidden" id="fabric_kode_${itemIndex}_${fabricIndex}" class="fabric-kode-input" value="${fabric.kode_jenis_kain || fabric.kode || ''}">
                                        <input type="hidden" id="fabric_harga_${itemIndex}_${fabricIndex}" class="fabric-harga-input" value="${fabric.harga_per_meter || 0}">
                                        <input type="hidden" id="fabric_meter_${itemIndex}_${fabricIndex}" class="fabric-meter-input" value="${fabric.meter_pemakaian || fabric.meter || 0}">
                                        <input type="hidden" id="fabric_nama_${itemIndex}_${fabricIndex}" class="fabric-nama-input" value="${fabric.nama_jenis_kain || ''}">
                                        <input type="hidden" id="fabric_warna_${itemIndex}_${fabricIndex}" class="fabric-warna-input" value="${fabric.warna || ''}">
                                        <input type="hidden" id="fabric_foto_${itemIndex}_${fabricIndex}" class="fabric-foto-input" value="${fabric.foto_jenis_kain || ''}">
                                    </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-edit"></i> Edit
                                        </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" value="${fabric.meter_pemakaian || fabric.meter || 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="${fabric.meter_pemakaian || fabric.meter || 0}" readonly style="background-color: #e9ecef;">
                                <?php endif; ?>
                            </div>
                        `;

                        $(`#fabricListContainer_${itemIndex}`).append(fabricItemHtml);
                    });
                    console.log(`✅ Loaded ${additionalFabrics.length} additional fabric(s)`);
                }
            } catch (e) {
                console.error('❌ Error parsing additional_fabrics:', e);
            }
        }
    }

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

    window.selectFabricFromGrid = function(kodeKain, jenisKain, warna, fotoKain, hargaKain) {
        if (window.currentEditingItemIndex !== null && window.currentEditingFabricIndex !== null) {
            const itemIndex = window.currentEditingItemIndex;
            const fabricIndex = window.currentEditingFabricIndex;

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

            fabricItem.find('.fabric-kode-input').val(kodeKain);
            fabricItem.find('.fabric-harga-input').val(hargaKain || 0);
            fabricItem.find('.fabric-nama-input').val(jenisKain);
            fabricItem.find('.fabric-warna-input').val(warna);
            fabricItem.find('.fabric-foto-input').val(fotoKain);

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

            // Remove yellow highlight after selection
            fabricItem.css({
                'background': '#f8f9fa',
                'border': '1px solid #dee2e6'
            });
            fabricItem.find('.alert-warning').remove();

            calculateItemTotal(itemIndex);
            $('#modalSelectFabric').modal('hide');
            window.currentEditingFabricIndex = null;
            calculateItemTotal(itemIndex);
        } else if (window.currentEditingItemIndex !== null) {
            // Single fabric selection (legacy - not used in multi-fabric mode)
            const itemIndex = window.currentEditingItemIndex;
            $(`#kode_jenis_kain_${itemIndex}`).val(kodeKain);
            $(`#harga_kain_${itemIndex}`).val(hargaKain || 0);
            $('#modalSelectFabric').modal('hide');
            calculateItemTotal(itemIndex);
        }
    };

    window.saveCustomSize = function(measurements) {
        if (window.currentEditingItemIndex !== null) {
            const itemIndex = window.currentEditingItemIndex;
            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'
            };

            $(`#lingkar_dada_${itemIndex}`).val(measurements.lingkar_dada || '');
            $(`#lingkar_pinggang_${itemIndex}`).val(measurements.lingkar_pinggang || '');
            $(`#lingkar_panggul_${itemIndex}`).val(measurements.lingkar_panggul || '');
            $(`#lebar_bahu_${itemIndex}`).val(measurements.lebar_bahu || '');
            $(`#panjang_lengan_${itemIndex}`).val(measurements.panjang_lengan || '');
            $(`#panjang_gamis_custom_${itemIndex}`).val(measurements.panjang_gamis || '');
            $(`#catatan_detail_${itemIndex}`).val(measurements.catatan_detail || '');

            let html = '';
            let hasData = false;

            for (let key in labels) {
                if (measurements[key] && measurements[key] !== '0' && measurements[key] !== 0) {
                    hasData = true;
                    const unit = key === 'catatan_detail' ? '' : ' cm';
                    html += `<li>${labels[key]}: ${measurements[key]}${unit}</li>`;
                }
            }

            if (hasData) {
                $(`#customMeasurementsList_${itemIndex}`).html(html);
                $(`#customMeasurements_${itemIndex}`).show();
                $(`#btnDeleteCustom_${itemIndex}`).show();

                // Clear ukuran standar when using custom
                $(`#ukuran_standar_${itemIndex}`).val('').removeAttr('required');
            } else {
                // Re-add required if no custom measurements
                $(`#ukuran_standar_${itemIndex}`).attr('required', 'required');
            }

            window.currentEditingItemIndex = null;
        }
    };

    window.deleteCustomSize = function(itemIndex) {
        if (confirm('Apakah Anda yakin ingin menghapus ukuran custom untuk item ini?')) {
            $(`#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('');

            $(`#customMeasurementsList_${itemIndex}`).html('');
            $(`#customMeasurements_${itemIndex}`).hide();
            $(`#btnDeleteCustom_${itemIndex}`).hide();

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

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

    function loadCustomMeasurements(itemIndex, item) {
        const fieldMapping = {
            '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'
        };

        let html = '';
        let hasData = false;

        for (let key in fieldMapping) {
            if (item[key] && item[key] !== '0' && item[key] !== 0) {
                hasData = true;
                const unit = key === 'catatan_detail' ? '' : ' cm';
                html += `<li>${fieldMapping[key]}: ${item[key]}${unit}</li>`;
            }
        }

        if (hasData) {
            $(`#customMeasurementsList_${itemIndex}`).html(html);
            $(`#customMeasurements_${itemIndex}`).show();
            $(`#btnDeleteCustom_${itemIndex}`).show();
        }
    }

    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 && ongkosJahitCustom > 0) {
            subtotalModel = ongkosJahitCustom * jumlah;
        }

        // Calculate total fabric cost from all fabric items
        let subtotalKain = 0;
        let totalMeter = 0;
        if (!bawaSendiri) {
            $(`#fabricListContainer_${itemIndex} .fabric-item`).each(function() {
                const fabricIndex = $(this).data('fabric-index');
                const fabricHarga = parseFloat($(`#fabric_harga_${itemIndex}_${fabricIndex}`).val()) || 0;
                const fabricMeter = parseFloat($(`#fabric_meter_${itemIndex}_${fabricIndex}`).val()) || 0;
                totalMeter += fabricMeter;
                subtotalKain += (fabricHarga * fabricMeter * jumlah);
            });
        }

        // Update hidden meter_pemakaian field (untuk compatibility dengan backend)
        $(`#meter_${itemIndex}`).val(totalMeter);

        const totalItem = subtotalModel + subtotalKain;

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

        if (uploadModelSendiri && bawaSendiri && ongkosJahitCustom > 0) {
            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));
        breakdown.find('.kain-price').text('Total Kain');
        breakdown.find('.meter-val').text(totalMeter.toFixed(1));
        breakdown.find('.kain-subtotal').text(formatRupiah(subtotalKain));

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

        // Update grand total
        calculateGrandTotal();
    }

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

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

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

    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 {
            $(`#modelSelectSection_${itemIndex}`).show();
            $(`#ImageReferenceSection_${itemIndex}`).hide();
            $(`#upload_model_sendiri_${itemIndex}`).val(0);
        }
        calculateItemTotal(itemIndex);
    }

    function toggleFabricSection(itemIndex) {
        const isChecked = $(`#bawaBajuSendiri_${itemIndex}`).is(':checked');
        if (isChecked) {
            $(`#fabricSelectSection_${itemIndex}`).hide();
            $(`#kode_jenis_kain_${itemIndex}`).val('');
            $(`#harga_kain_${itemIndex}`).val(0);
            $(`#bawa_kain_sendiri_${itemIndex}`).val(1);
        } else {
            $(`#fabricSelectSection_${itemIndex}`).show();
            $(`#bawa_kain_sendiri_${itemIndex}`).val(0);
        }
        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);

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

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

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

        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();

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

    // Function to toggle alamat pengiriman display in edit form
    function toggleAlamatPengirimanEdit() {
        const statusPengiriman = $('input[name="status_pengiriman"]:checked').val();
        if (statusPengiriman == '2') {
            $('#alamat_pengiriman_group_edit').show();
            $('#alamat_pengiriman_input_edit').attr('required', 'required');
        } else {
            $('#alamat_pengiriman_group_edit').hide();
            $('#alamat_pengiriman_input_edit').removeAttr('required');
        }
    }
</script>