<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:#f8fafc;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 bg-secondary text-white">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <div class="fw-bold text-white" style="font-size:12px;letter-spacing:.8px;text-transform:uppercase;">
                    <i class="fa-solid fa-shirt me-1"></i> Garment Items
                </div>

            </div>
            <div class="table-responsive bg-white rounded p-2">
                <table class="table table-bordered mb-0" style="font-size:13px;">
                    <thead>
                        <tr>
                            <th width="35">#</th>
                            <th width="180">Garment Type</th>
                            <th>Description / Measurements</th>
                            <th width="80">Qty</th>
                            <th width="120">Rate (₹)</th>
                            <th width="120">Amount (₹)</th>
                            <th width="40"></th>
<th width="120"></th>
                        </tr>
                    </thead>
                    <tbody id="itemsBody">

                        <?php
                        if (isset($edit_items) && !empty($edit_items)):
                            foreach($edit_items as $idx => $item): ?>
                        <tr class="item-row">
                            <td class="row-num"><?= $idx + 1 ?></td>
                            <td>
                                <input type="text" name="garment_type[]"
                                       class="form-control form-control-sm"
                                       value="<?= htmlspecialchars($item->garment_type) ?>"
                                       placeholder="e.g. Shirt, Salwar, Kurta"
                                       list="garment_suggestions">
                            </td>
                            <td>
                                <input type="text" name="description[]"
                                       class="form-control form-control-sm"
                                       value="<?= htmlspecialchars($item->description) ?>"
                                       placeholder="Chest 40, Waist 34...">
                            </td>
                            <td><input type="number" name="qty[]" class="form-control form-control-sm qty-inp" min="1" value="<?= $item->qty ?>"></td>
                            <td><input type="number" step="0.01" min="0" name="rate[]" class="form-control form-control-sm rate-inp" value="<?= $item->rate ?>"></td>
                            <td><input type="text" class="form-control form-control-sm amt-out bg-light" readonly value="<?= (int)($item->amount) ?>"></td>
                            <td><button type="button" class="btn btn-sm btn-danger remove-row no-loader"><i class="fa-solid fa-times"></i></button></td>
                        </tr>
                        <?php endforeach;
                        else: ?>
                        <tr class="item-row">
                            <td class="row-num">1</td>
                            <td>
                                <input type="text" name="garment_type[]"
                                       class="form-control form-control-sm"
                                       placeholder="e.g. Shirt, Salwar, Kurta"
                                       list="garment_suggestions">
                            </td>
                            <td>
                                <input type="text" name="description[]"
                                       class="form-control form-control-sm"
                                       placeholder="Chest 40, Waist 34...">
                            </td>
                            <td><input type="number" name="qty[]" class="form-control form-control-sm qty-inp" min="1" value="1"></td>
                            <td><input type="number" step="0.01" min="0" name="rate[]" class="form-control form-control-sm rate-inp" placeholder="0.00"></td>
                            <td><input type="text" class="form-control form-control-sm amt-out bg-light" readonly value="0.00"></td>
                            <td><button type="button" class="btn btn-sm btn-danger remove-row no-loader"><i class="fa-solid fa-times"></i></button></td>
                        </tr>
                        <?php endif; ?>

                    </tbody>
                    <!--<tfoot>-->
                    <!--    <tr>-->
                    <!--        <td colspan="6" class="text-end fw-bold">Grand Total:</td>-->
                    <!--        <td><input type="text" id="grand_total" class="form-control form-control-sm bg-light fw-bold text-success" readonly value="0.00"></td>-->
                    <!--        <td><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 Row</button></td>-->
                    <!--    </tr>-->
                    <!--</tfoot>-->
                    
                    <tfoot>
    <tr>
        <td colspan="5" class="text-end fw-bold">Grand Total:</td>

        <td>
            <input type="text"
                   id="grand_total"
                   class="form-control form-control-sm bg-light fw-bold text-success"
                   readonly value="0.00">
        </td>

        <td></td>

        <td>
            <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 Row
            </button>
        </td>
    </tr>
</tfoot>
                </table>
            </div>

            <!-- Datalist for garment suggestions -->
            <datalist id="garment_suggestions">
                <option value="Shirt">
                <option value="Pant">
                <option value="Salwar Kameez">
                <option value="Kurta">
                <option value="Saree Blouse">
                <option value="Lehenga">
                <option value="Coat">
                <option value="Jacket">
                <option value="Sherwani">
                <option value="Safari Suit">
                <option value="School Uniform">
            </datalist>
        </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>
$(document).ready(function(){

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

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

    $(document).on('input', '.qty-inp, .rate-inp', function(){
        var row  = $(this).closest('tr');
        var qty  = parseFloat(row.find('.qty-inp').val()) || 0;
        var rate = parseFloat(row.find('.rate-inp').val()) || 0;
        row.find('.amt-out').val((qty * rate));
        calcGrand();
    });

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

    // ✅ Add Row
    $('#addRow').on('click', function(){

        var newRow = `
        <tr class="item-row">
            <td class="row-num"></td>
            <td>
                <input type="text" name="garment_type[]"
                       class="form-control form-control-sm"
                    
                       list="garment_suggestions">
            </td>
            <td>
                <input type="text" name="description[]"
                       class="form-control form-control-sm"
                       >
            </td>
            <td><input type="number" name="qty[]" class="form-control form-control-sm qty-inp" min="1" value="1"></td>
            <td><input type="number" step="0.01" min="0" name="rate[]" class="form-control form-control-sm rate-inp" placeholder="0.00"></td>
            <td><input type="text" class="form-control form-control-sm amt-out bg-light" readonly value="0.00"></td>
            <td><button type="button" class="btn btn-sm btn-danger remove-row no-loader"><i class="fa-solid fa-times"></i></button></td>
        </tr>`;

        $('#itemsBody').append(newRow);
        reNumberRows();
    });

    // Edit mode — existing rows calculate
    $('.item-row').each(function(){
        var row  = $(this);
        var qty  = parseFloat(row.find('.qty-inp').val()) || 0;
        var rate = parseFloat(row.find('.rate-inp').val()) || 0;
        row.find('.amt-out').val((qty * rate));
    });
    calcGrand();
});
</script>