<div class="card-box">

    <div class="card-box-header">
        <h5><i class="fa-solid fa-shirt text-primary"></i>
            <?= isset($row) ? 'Edit Tailoring Order' : 'New Tailoring Order' ?>
        </h5>
        <a href="<?= site_url('tailoring_order') ?>" class="btn btn-sm" style="background:#f1f5f9;color:#374151;">
            <i class="fa-solid fa-arrow-left me-1"></i> Back
        </a>
    </div>

    <?php if(validation_errors()): ?>
    <div class="alert alert-danger">
        <?= validation_errors('<ul class="mb-0 ps-3">','</ul>','<li>','</li>') ?>
    </div>
    <?php endif; ?>
    <?php if(isset($item_error)): ?>
    <div class="alert alert-danger">
        <i class="fa-solid fa-circle-exclamation me-2"></i><?= $item_error ?>
    </div>
    <?php endif; ?>

    <form method="post" action="<?= isset($row) ? site_url('tailoring_order/edit/'.$row->id) : site_url('tailoring_order/create') ?>">

        <div class="p-3 mb-3 rounded" style="background:#d5f2ed;border:1px solid #e2e8f0;">
            <div class="fw-bold text-muted mb-3" style="font-size:12px;letter-spacing:.8px;text-transform:uppercase;">
                <i class="fa-solid fa-circle-info me-1"></i> Order Details
            </div>
            <div class="row g-3">
                <div class="col-md-4">
                    <label class="form-label">Customer <span class="required-star">*</span></label>
                    <div class="d-flex align-items-center gap-2">
                        <div style="flex:1;min-width:0;">
                            <select name="customer_id" id="customer_id" class="form-select select2 <?= form_error('customer_id') ? 'is-invalid' : '' ?>">
                                <option value="">— Select Customer —</option>
                                <?php foreach($customers as $c): ?>
                                <option value="<?= $c->id ?>"
                                    <?= set_select('customer_id', $c->id, isset($row) && $row->customer_id == $c->id) ?>>
                                    <?= htmlspecialchars($c->customer_name) ?><?= !empty($c->mobile) ? ' - ' . htmlspecialchars($c->mobile) : '' ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <button type="button" class="btn btn-primary flex-shrink-0 d-none" id="btnAddCustomer" title="Add New Customer">
                            <i class="fa-solid fa-plus"></i>
                        </button>
                    </div>
                    <?php if(form_error('customer_id')): ?><div class="invalid-feedback d-block"><?= form_error('customer_id') ?></div><?php endif; ?>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Order Date <span class="required-star">*</span></label>
                    <input type="date" name="order_date"
                           class="form-control <?= form_error('order_date') ? 'is-invalid' : '' ?>"
                           value="<?= set_value('order_date', isset($row) ? $row->order_date : date('Y-m-d')) ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label">Delivery Date <span class="required-star">*</span></label>
                    <input type="date" name="delivery_date"
                           class="form-control <?= form_error('delivery_date') ? 'is-invalid' : '' ?>"
                           value="<?= set_value('delivery_date', isset($row) ? $row->delivery_date : '') ?>">
                </div>
                <div class="col-md-2">
                    <label class="form-label">Advance Paid (₹)</label>
                    <input type="number" step="0.01" min="0" name="advance_paid" class="form-control"
                           value="<?= set_value('advance_paid', isset($row) ? $row->advance_paid : '0') ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label">Status</label>
                    <select name="status" class="form-select">
                        <?php
                        $statuses = ['Pending' => 'Pending', 'In Progress' => 'In Progress', 'Ready' => 'Ready', 'Delivered' => 'Delivered', 'Cancelled' => 'Cancelled'];
                        foreach($statuses as $val => $lbl):
                            $currentStatus = isset($row) ? $row->order_status : 'Pending';
                            $sel = ($currentStatus == $val) ? 'selected' : '';
                        ?>
                        <option value="<?= $val ?>" <?= $sel ?>><?= $lbl ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-9">
                    <label class="form-label">Notes</label>
                    <input type="text" name="notes" class="form-control"
                           value="<?= set_value('notes', isset($row) ? $row->notes : '') ?>"
                           placeholder="Measurements, special instructions...">
                </div>
            </div>
        </div>

        <!-- Garment Items -->
        <div class="p-3 mb-3 rounded text-dark" style="background-color:#e0ffff;">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <div class="fw-bold text-dark" style="font-size:12px;letter-spacing:.8px;text-transform:uppercase;">
                    <i class="fa-solid fa-shirt me-1"></i> Garment Items
                </div>
            </div>

            <div id="itemsBody">
                <?php
                // Group existing items (if any) by garment type, then pair them up index-wise
                // so each "card" shows one Pant + one Shirt + one Kurta/Blazer together.
                $gc_buckets = ['Pant' => [], 'Shirt' => [], 'Kurta/Blazer' => []];
                if (isset($edit_items) && !empty($edit_items)) {
                    foreach ($edit_items as $item) {
                        if (isset($gc_buckets[$item->garment_type])) {
                            $gc_buckets[$item->garment_type][] = $item;
                        }
                    }
                }
                $gc_card_count = max(count($gc_buckets['Pant']), count($gc_buckets['Shirt']), count($gc_buckets['Kurta/Blazer']), 1);
                for ($idx = 0; $idx < $gc_card_count; $idx++):
                    $pant  = $gc_buckets['Pant'][$idx]          ?? null;
                    $shirt = $gc_buckets['Shirt'][$idx]         ?? null;
                    $kurta = $gc_buckets['Kurta/Blazer'][$idx]  ?? null;
                    include APPPATH . 'views/tailoring_order/_garment_card.php';
                endfor;
                ?>
            </div>

            <div class="d-flex justify-content-between align-items-center bg-white rounded p-2">
                <div class="fw-bold text-dark">Grand Total: <span id="grand_total_display">₹0.00</span></div>
                <input type="hidden" id="grand_total" value="0.00">
                <!--<button type="button" id="addRow" class="btn btn-sm btn-success no-loader" style="white-space:nowrap;">-->
                <!--    <i class="fa-solid fa-plus me-1"></i>Add Garment-->
                <!--</button>-->
            </div>
        </div>

        <div class="d-flex gap-2">
            <button type="submit" name="save_order" value="1" class="btn btn-primary px-4 text-white">
                <i class="fa-solid fa-floppy-disk me-1"></i>
                <?= isset($row) ? 'Update Order' : 'Save Order' ?>
            </button>
            <a href="<?= site_url('tailoring_order') ?>" class="btn" style="background:#f1f5f9;color:#374151;">Cancel</a>
        </div>

    </form>
</div>

<!-- ── Add New Customer Modal ───────────────────────────────────────────── -->
<div class="modal fade" id="addCustomerModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" style="max-width:550px;">
        <div class="modal-content" style="border-radius:12px;overflow:hidden;">
            <div class="modal-header border-0 pb-1 pt-3">
                <h5 class="modal-title text-danger fw-bold w-100 text-center" style="font-size:1.15rem;">
                    Add New Customer
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body px-4 pt-2 pb-4" style="background:#eef2f7;">
                <div class="row g-3 mt-1">
                    <div class="col-md-6">
                        <label class="form-label text-primary fw-semibold">Customer Name <span class="text-danger">*</span></label>
                        <input type="text" id="nc_name" class="form-control" placeholder="Enter Customer Name">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label text-primary fw-semibold">Mobile <span class="text-danger">*</span></label>
                        <input type="text" id="nc_mobile" class="form-control" placeholder="Enter 10-digit Mobile No" maxlength="10" pattern="[0-9]{10}">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label text-primary fw-semibold">GST No <span class="text-muted" style="font-weight:400;">(optional)</span></label>
                        <input type="text" id="nc_gst" class="form-control" placeholder="Enter GST No">
                    </div>
                    <div class="col-12">
                        <label class="form-label text-primary fw-semibold">Address <span class="text-danger">*</span></label>
                        <textarea id="nc_address" class="form-control" rows="3" placeholder="Enter Address"></textarea>
                    </div>
                </div>
                <div class="d-flex justify-content-end gap-2 mt-3">
                    <button type="button" class="btn btn-primary px-4" id="btnSaveCustomer">
                        <i class="fa-solid fa-floppy-disk me-1"></i> Submit
                    </button>
                    <button type="button" class="btn btn-danger px-3" data-bs-dismiss="modal">
                        <i class="fa-solid fa-times me-1"></i> Cancel
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function(){

    // Select2 init — customer dropdown
    $('#customer_id').select2({ theme: 'bootstrap-5', width: '100%' });
    $('#customer_id').on('select2:open', function(){
        setTimeout(function(){
            var $dropdown = $('.select2-container--open .select2-dropdown');
            if($dropdown.length && $dropdown.find('.add-new-option').length === 0){
                var $opt = $('<div class="add-new-option" style="padding:8px 14px;cursor:pointer;color:#7c3aed;font-weight:600;border-bottom:1px solid #eee;background:#f5f3ff;"><i class="fa-solid fa-plus me-2"></i>Add New Customer</div>');
                $opt.on('mousedown', function(e){
                    e.preventDefault();
                    e.stopPropagation();
                    $('#customer_id').select2('close');
                    $('#btnAddCustomer').trigger('click');
                });
                $dropdown.find('.select2-results').after($opt);
            }
        }, 0);
    });

    // ── Add New Customer Modal Logic ─────────────────────────────────────────
    $('#btnAddCustomer').on('click', function(){
        $('#nc_name').val('');
        $('#nc_mobile').val('');
        $('#nc_gst').val('');
        $('#nc_address').val('');
        $('#addCustomerModal').modal('show');
    });

    $('#btnSaveCustomer').on('click', function(){
        var name    = $('#nc_name').val().trim();
        var mobile  = $('#nc_mobile').val().trim();
        var gst_no  = $('#nc_gst').val().trim();
        var address = $('#nc_address').val().trim();

        if(!name){ showProAlert('error', 'Error', 'Customer Name is required!'); return; }
        if(!mobile || !/^[0-9]{10}$/.test(mobile)){ showProAlert('error', 'Error', 'Valid 10-digit Mobile Number is required!'); return; }
        if(!address){ showProAlert('error', 'Error', 'Address is required!'); return; }

        $('#btnSaveCustomer').prop('disabled', true).html('<i class="fa-solid fa-spinner fa-spin me-1"></i> Saving...');

        $.ajax({
            url: '<?= site_url("tailoring_order/ajax_add_customer") ?>',
            type: 'POST',
            data: { customer_name: name, mobile: mobile, gst_no: gst_no, address: address },
            dataType: 'json',
            success: function(res){
                if(res.status === 'success'){
                    var displayText = res.customer_name + (res.mobile ? ' - ' + res.mobile : '');
                    var newOption = new Option(displayText, res.id, true, true);
                    $('#customer_id').append(newOption).trigger('change');
                    $('#addCustomerModal').modal('hide');
                    showProAlert('success', 'Added!', res.customer_name + ' successfully added!');
                } else {
                    showProAlert('error', 'Error', res.message || 'Something went wrong!');
                }
            },
            error: function(){ showProAlert('error', 'Error', 'Server error. Please try again.'); },
            complete: function(){ $('#btnSaveCustomer').prop('disabled', false).html('<i class="fa-solid fa-floppy-disk me-1"></i> Submit'); }
        });
    });
});
</script>

<script>
window.gcReceiptNo = <?= json_encode(isset($row) ? $row->order_no : ($order_no ?? '')) ?>;
$(document).ready(function(){

    function calcGrand(){
        var total = 0;
        $('.amt-out').each(function(){ total += parseFloat($(this).val()) || 0; });
        $('#grand_total').val(total);
        $('#grand_total_display').text('₹' + total.toFixed(2));
    }

    function reNumberRows(){
        $('.garment-card').each(function(i){
            $(this).find('.row-num').text('#' + (i + 1));
        });
    }

    function serializeMeasurements(block){
        var data = {};
        var summaryParts = [];
        block.find('.m-fld').each(function(){
            var key = $(this).data('key');
            var val = $(this).val();
            if (val !== '' && val !== null) {
                data[key] = val;
                summaryParts.push(key.replace('_', ' ') + ': ' + val);
            }
        });

        block.find('.measurements-json').val(JSON.stringify(data));
        block.find('.description-hidden').val(summaryParts.join(', '));
    }

    // Each garment type (Pant / Shirt / Kurta-Blazer) calculates its own Amount independently
    $(document).on('input change', '.qty-inp, .rate-inp', function(){
        var block = $(this).closest('.type-block');
        var qty   = parseFloat(block.find('.qty-inp').val()) || 0;
        var rate  = parseFloat(block.find('.rate-inp').val()) || 0;
        block.find('.amt-out').val((qty * rate).toFixed(2));
        calcGrand();
    });

    $(document).on('click', '.remove-row', function(){
        if($('.garment-card').length > 1){
            $(this).closest('.garment-card').remove();
            reNumberRows();
            calcGrand();
        }
    });

    // ✅ Add Garment — one click adds Pant + Shirt + Kurta/Blazer together, same chit design
    $('#addRow').on('click', function(){
        var idx = $('.garment-card').length;
        var newCard = `
        <div class="garment-card border rounded mb-3 bg-white text-dark">
            <div class="d-flex justify-content-between align-items-center p-2 border-bottom bg-light rounded-top">
                <div class="fw-bold text-muted row-num">#${idx + 1}</div>
                <button type="button" class="btn btn-sm btn-danger remove-row no-loader"><i class="fa-solid fa-times"></i></button>
            </div>

            <div class="type-block p-2">
                <div class="chit">
                    <div class="chit-head">
                        <div class="chit-title">Pant</div>
                        <div class="chit-receipt">
                            <div class="chit-receipt-lbl">Receipt No.</div>
                            <div class="chit-receipt-val">${window.gcReceiptNo || ''}</div>
                        </div>
                    </div>
                    <div class="chit-qra">
                        <div class="chit-qra-item"><label>Qty</label><input type="number" min="1" name="qty[]" class="qty-inp" value="1"></div>
                        <div class="chit-qra-item"><label>Rate (₹)</label><input type="number" step="0.01" min="0" name="rate[]" class="rate-inp" value=""></div>
                        <div class="chit-qra-item"><label>Amount (₹)</label><input type="text" class="amt-out" readonly value="0.00"></div>
                    </div>
                    <div class="chit-row">
                        <div class="chit-cell"><label>Height</label><input type="text" class="m-fld" data-key="height"></div>
                        <div class="chit-cell"><label>Waist</label><input type="text" class="m-fld" data-key="waist"></div>
                        <div class="chit-cell"><label>Length (T)</label><input type="text" class="m-fld" data-key="length"></div>
                    </div>
                    <div class="chit-row">
                        <div class="chit-cell"><label>Seat / Hip (F)</label><input type="text" class="m-fld" data-key="seat"></div>
                        <div class="chit-cell"><label>Thigh</label><input type="text" class="m-fld" data-key="thigh"></div>
                        <div class="chit-cell"><label>Knee</label><input type="text" class="m-fld" data-key="knee"></div>
                    </div>
                    <div class="chit-line-row">
                        <span class="chit-lbl">French Fly</span>
                        <span class="chit-dash"></span>
                        <span class="chit-lbl">Bottom</span>
                        <input type="text" class="m-fld" data-key="bottom">
                    </div>
                    <div class="chit-row">
                        <div class="chit-cell chit-narrow"><label>Cross</label><input type="text" class="m-fld" data-key="cross"></div>
                        <div class="chit-cell chit-wide"><label>Fly / Pocket Style</label><input type="text" class="m-fld" data-key="style" placeholder="V.P.C / P.S / 2 P.C"></div>
                    </div>
                    <div class="chit-notes"><label>Other Notes</label><input type="text" class="m-fld" data-key="notes"></div>
                </div>
                <input type="hidden" name="garment_type[]" value="Pant">
                <input type="hidden" name="measurements[]" class="measurements-json" value="">
                <input type="hidden" name="description[]" class="description-hidden" value="">
            </div>

            <div class="type-block p-2">
                <div class="chit">
                    <div class="chit-head">
                        <div class="chit-title">Shirt</div>
                        <div class="chit-receipt">
                            <div class="chit-receipt-lbl">Receipt No.</div>
                            <div class="chit-receipt-val">${window.gcReceiptNo || ''}</div>
                        </div>
                    </div>
                    <div class="chit-qra">
                        <div class="chit-qra-item"><label>Qty</label><input type="number" min="1" name="qty[]" class="qty-inp" value="1"></div>
                        <div class="chit-qra-item"><label>Rate (₹)</label><input type="number" step="0.01" min="0" name="rate[]" class="rate-inp" value=""></div>
                        <div class="chit-qra-item"><label>Amount (₹)</label><input type="text" class="amt-out" readonly value="0.00"></div>
                    </div>
                    <div class="chit-row">
                        <div class="chit-cell"><label>Height</label><input type="text" class="m-fld" data-key="height"></div>
                        <div class="chit-cell"><label>Chest</label><input type="text" class="m-fld" data-key="chest"></div>
                        <div class="chit-cell"><label>Waist</label><input type="text" class="m-fld" data-key="waist"></div>
                        <div class="chit-cell"><label>Stomach</label><input type="text" class="m-fld" data-key="stomach"></div>
                        <div class="chit-cell"><label>Shoulder</label><input type="text" class="m-fld" data-key="shoulder"></div>
                    </div>
                    <div class="chit-row">
                        <div class="chit-cell"><label>Sleeve Length</label><input type="text" class="m-fld" data-key="sleeve_length"></div>
                        <div class="chit-cell chit-sleeve-wrap">
                            <label>Sleeve Type</label>
                            <select class="form-select form-select-sm m-fld select2 sleeve-type-sel" data-key="sleeve_type">
                                <option value="">--</option>
                                <option value="Full Sleeves">Full Sleeves</option>
                                <option value="Half Sleeves">Half Sleeves</option>
                            </select>
                        </div>
                        <div class="chit-cell chit-wide"><label>Collar Style</label><input type="text" class="m-fld" data-key="collar" placeholder="M / X / T / C / R.C"></div>
                    </div>
                    <div class="chit-fbrow">
                        <div class="chit-fb">F: <input type="text" class="m-fld" data-key="front"></div>
                        <div class="chit-fb">B: <input type="text" class="m-fld" data-key="back"></div>
                    </div>
                    <div class="chit-notes"><label>Other Notes</label><input type="text" class="m-fld" data-key="notes"></div>
                </div>
                <input type="hidden" name="garment_type[]" value="Shirt">
                <input type="hidden" name="measurements[]" class="measurements-json" value="">
                <input type="hidden" name="description[]" class="description-hidden" value="">
            </div>

            <div class="type-block p-2">
                <div class="chit">
                    <div class="chit-head">
                        <div class="chit-title">Kurta / Blazer</div>
                        <div class="chit-receipt">
                            <div class="chit-receipt-lbl">Receipt No.</div>
                            <div class="chit-receipt-val">${window.gcReceiptNo || ''}</div>
                        </div>
                    </div>
                    <div class="chit-qra">
                        <div class="chit-qra-item"><label>Qty</label><input type="number" min="1" name="qty[]" class="qty-inp" value="1"></div>
                        <div class="chit-qra-item"><label>Rate (₹)</label><input type="number" step="0.01" min="0" name="rate[]" class="rate-inp" value=""></div>
                        <div class="chit-qra-item"><label>Amount (₹)</label><input type="text" class="amt-out" readonly value="0.00"></div>
                    </div>
                    <div class="chit-row">
                        <div class="chit-cell"><label>Height</label><input type="text" class="m-fld" data-key="height"></div>
                        <div class="chit-cell"><label>Chest</label><input type="text" class="m-fld" data-key="chest"></div>
                        <div class="chit-cell"><label>Waist</label><input type="text" class="m-fld" data-key="waist"></div>
                        <div class="chit-cell"><label>Stomach</label><input type="text" class="m-fld" data-key="stomach"></div>
                        <div class="chit-cell"><label>Shoulder</label><input type="text" class="m-fld" data-key="shoulder"></div>
                        <div class="chit-cell"><label>Length</label><input type="text" class="m-fld" data-key="length"></div>
                    </div>
                    <div class="chit-row">
                        <div class="chit-cell"><label>Sleeve Length</label><input type="text" class="m-fld" data-key="sleeve_length"></div>
                        <div class="chit-cell chit-sleeve-wrap">
                            <label>Sleeve Type</label>
                            <select class="form-select form-select-sm m-fld select2 sleeve-type-sel" data-key="sleeve_type">
                                <option value="">--</option>
                                <option value="Full Sleeves">Full Sleeves</option>
                                <option value="Half Sleeves">Half Sleeves</option>
                            </select>
                        </div>
                        <div class="chit-cell chit-wide"><label>Collar Style</label><input type="text" class="m-fld" data-key="collar" placeholder="M / X / T / C / R.C"></div>
                    </div>
                    <div class="chit-fbrow">
                        <div class="chit-fb">F: <input type="text" class="m-fld" data-key="front"></div>
                        <div class="chit-fb">B: <input type="text" class="m-fld" data-key="back"></div>
                    </div>
                    <div class="chit-notes"><label>Other Notes</label><input type="text" class="m-fld" data-key="notes"></div>
                </div>
                <input type="hidden" name="garment_type[]" value="Kurta/Blazer">
                <input type="hidden" name="measurements[]" class="measurements-json" value="">
                <input type="hidden" name="description[]" class="description-hidden" value="">
            </div>
        </div>`;

        var $newCard = $(newCard);
        $('#itemsBody').append($newCard);
        $newCard.find('.select2.sleeve-type-sel').select2({ theme: 'bootstrap-5', width: '100%' });
        reNumberRows();
    });

    // Serialize measurements right before submit — one hidden set per type-block
    $('form').on('submit', function(){
        $('.type-block').each(function(){
            serializeMeasurements($(this));
        });
    });

    // Sleeve Type dropdowns are always visible now (no dropdown-triggered show/hide), init once upfront
    $('.sleeve-type-sel').select2({ theme: 'bootstrap-5', width: '100%' });

    // Edit mode / initial load — calculate each type-block's own amount
    $('.type-block').each(function(){
        var block = $(this);
        var qty   = parseFloat(block.find('.qty-inp').val()) || 0;
        var rate  = parseFloat(block.find('.rate-inp').val()) || 0;
        block.find('.amt-out').val((qty * rate).toFixed(2));
    });
    calcGrand();
});
</script>