<div class="modal-header">
    <h4 class="modal-title">Tambah Pesanan Custom 2</h4>
    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
        <span aria-hidden="true">×</span>
    </button>
</div>
<div class="modal-body" style="max-height: 85vh; overflow-y: auto;">
    <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="id_customer">Pilih Customer</label>
                        <select class="custom-select" id="id_customer" name="id_customer" required>
                            <option value="">--- Pilih Customer ---</option>
                            <?php foreach ($customer as $cstm): ?>
                                <option value="<?= $cstm->id_customer ?>"><?= $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">
            <div class="card-header bg-secondary text-white">
                <h6 class="mb-0 text-light"><i class="fas fa-calendar"></i> Jadwal & Catatan</h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="form-label">Tanggal Pengambilan</label>
                            <input type="date" class="form-control" name="tanggal_pengambilan" value="<?= date('Y-m-d') ?>" required>
                        </div>
                    </div>
                    <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>
                <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>

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

        <!-- Add Item Button -->
        <div class="text-center mb-3">
            <button type="button" class="btn btn-success btn-lg" id="btnAddItem">
                <i class="fas fa-plus-circle"></i> Tambah Item Pesanan
            </button>
        </div>

        <div class="modal-footer">
            <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>
        </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>
    let itemCounter = 0;
    let currentEditingItemIndex = null;

    $(document).ready(function() {
        // Add first item automatically
        addNewItem();

        // Add item button click
        $('#btnAddItem').click(function() {
            addNewItem();
        });

        // Form validation
        $('#formCreateOrder').submit(function(e) {
            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 bawaSendiri = $(`#bawaBajuSendiri_${itemIndex}`).is(':checked');
                const kainSelected = $(`#kode_jenis_kain_${itemIndex}`).val();

                if (!modelSelected) {
                    isValid = false;
                    alert(`Item ${index + 1}: Silakan pilih model terlebih dahulu!`);
                    return false;
                }

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

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

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

        const itemHtml = `
        <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 text-light">
                    <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">
                <!-- Hidden fields for this item -->
                <input type="hidden" name="kode_model[]" id="kode_model_${itemIndex}">
                <input type="hidden" name="kode_jenis_kain[]" id="kode_jenis_kain_${itemIndex}">

                <div class="row">
                    <!-- MODEL SECTION -->
                    <div class="col-md-6">
                        <div class="card h-100 mb-3 mb-md-0">
                            <div class="card-header bg-success text-white">
                                <strong><i class="fas fa-shirt"></i> 1. Pilih Model Gamis</strong>
                            </div>
                            <div class="card-body">
                                <button type="button" class="btn btn-success btn-block" onclick="openModelSelector(${itemIndex})">
                                    <i class="fas fa-search"></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>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- KAIN SECTION -->
                    <div class="col-md-6">
                        <div class="card h-100">
                            <div class="card-header bg-warning text-dark">
                                <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}">
                                    <button type="button" class="btn btn-warning btn-block" onclick="openFabricSelector(${itemIndex})">
                                        <i class="fas fa-search"></i> Pilih Jenis Kain
                                    </button>
                                    <div id="fabricPreview_${itemIndex}" class="mt-3" style="display: none;">
                                        <div class="border border-warning rounded p-2 bg-light">
                                            <div class="text-center">
                                                <img id="fabricPreviewImg_${itemIndex}" src="" alt="Kain" style="max-height: 120px; object-fit: cover;" class="img-fluid mb-2 rounded">
                                            </div>
                                            <p class="mb-1 text-center"><strong id="fabricPreviewName_${itemIndex}"></strong></p>
                                            <small class="text-muted d-block text-center">Warna: <span id="fabricPreviewColor_${itemIndex}"></span></small>
                                            <small class="text-muted d-block text-center">Kode: <span id="fabricPreviewCode_${itemIndex}"></span></small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <hr class="my-3">

                <!-- REFERENSI GAMBAR -->
                <div class="form-group">
                    <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>
                            <input type="text" class="form-control" name="ukuran_gamis[]" placeholder="Contoh: M, L, XL atau Custom" required>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label d-block">&nbsp;</label>
                        <button type="button" class="btn btn-outline-info btn-block" onclick="openCustomSize(${itemIndex})">
                            <i class="fas fa-plus"></i> 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">

                <!-- METER & JUMLAH -->
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group mb-0">
                            <label class="form-label"><i class="fas fa-ruler"></i> 4. Meter Pemakaian Kain</label>
                            <input type="number" class="form-control" name="meter_pemakaian[]" step="0.5" placeholder="Contoh: 2.5" required>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group mb-0">
                            <label class="form-label"><i class="fas fa-sort-numeric-up"></i> 5. Jumlah (Pcs)</label>
                            <input type="number" class="form-control" name="jumlah_pcs[]" min="1" value="1" required>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        `;

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

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

    function updateItemNumbers() {
        $('.item-card').each(function(index) {
            $(this).find('h5').html(`<i class="fas fa-box-open"></i> Item #${index + 1}`);
        });
    }

    function toggleFabricSection(itemIndex) {
        const isChecked = $(`#bawaBajuSendiri_${itemIndex}`).is(':checked');
        if (isChecked) {
            $(`#fabricSelectSection_${itemIndex}`).hide();
            $(`#kode_jenis_kain_${itemIndex}`).val('');
            $(`#fabricPreview_${itemIndex}`).hide();
        } else {
            $(`#fabricSelectSection_${itemIndex}`).show();
        }
    }

    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) {
        currentEditingItemIndex = itemIndex;
        $('#modalSelectModel').modal('show');
    }

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

    function openCustomSize(itemIndex) {
        currentEditingItemIndex = itemIndex;
        $('#modalCustomSize').modal('show');
    }

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

    window.selectFabricFromGrid = function(kodeKain, jenisKain, warna, fotoKain) {
        if (currentEditingItemIndex !== null) {
            $(`#kode_jenis_kain_${currentEditingItemIndex}`).val(kodeKain);
            $(`#fabricPreviewImg_${currentEditingItemIndex}`).attr('src', '<?= base_url() ?>/' + fotoKain);
            $(`#fabricPreviewName_${currentEditingItemIndex}`).text(jenisKain);
            $(`#fabricPreviewColor_${currentEditingItemIndex}`).text(warna);
            $(`#fabricPreviewCode_${currentEditingItemIndex}`).text(kodeKain);
            $(`#fabricPreview_${currentEditingItemIndex}`).show();
            $('#modalSelectFabric').modal('hide');
        }
    };

    window.saveCustomSize = function(measurements) {
        if (currentEditingItemIndex !== null) {
            let html = '';
            for (let key in measurements) {
                if (measurements[key]) {
                    html += `<li>${key}: ${measurements[key]} cm</li>`;
                }
            }
            $(`#customMeasurementsList_${currentEditingItemIndex}`).html(html);
            $(`#customMeasurements_${currentEditingItemIndex}`).show();
        }
    };
</script>