{% extends 'base.html' %}
{% load static %}

{% block content %}
<div class="container">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-body p-4">
                    <h5 class="mb-4">Edit Booking</h5>
                    <form method="post" class="row g-3">
                        {% csrf_token %}
                        <div class="col-md-4">
                            <label class="form-label">Booking ID</label>
                            <input type="text" class="form-control" value="{{ booking.booking_id|default:'None' }}" readonly>
                        </div>

                        <div class="col-md-4">
                            <label for="booking_status" class="form-label">Status</label>
                            <select id="booking_status" name="booking_status" class="form-select">
                                <option value="pending_confirmation" {% if booking.booking_status  ==  'pending_confirmation' %}selected{% endif %}>Pending</option>
                                <option value="confirmed" {% if booking.booking_status  ==  'confirmed' %}selected{% endif %}>Confirmed</option>
                                <option value="in_progress" {% if booking.booking_status  ==  'in_progress' %}selected{% endif %}>In Progress</option>
                                <option value="completed" {% if booking.booking_status  ==  'completed' %}selected{% endif %}>Completed</option>
                                <option value="cancelled" {% if booking.booking_status  ==  'cancelled' %}selected{% endif %}>Cancelled</option>
                                <option value="back_to_base" {% if booking.booking_status  ==  'back_to_base' %}selected{% endif %}>Back to Base</option>
                            </select>
                        </div>

                        <div class="col-md-4">
                            <label for="rider" class="form-label">Assign Rider</label>
                            <select id="rider" name="rider" class="form-select">
                                <option value="">-- Select Rider --</option>
                                {% for r in riders %}
                                    <option value="{{ r.id }}" {% if booking.rider_id == r.id %}selected{% endif %}>{{ r.display_name|default:r.full_name }}</option>
                                {% endfor %}
                            </select>
                        </div>

                        <div class="col-md-4">
                            <label for="pickup_type" class="form-label">Pickup Type</label>
                            <select id="pickup_type" name="pickup_type" class="form-select">
                                <option value="normal" {% if booking.pickup_type  ==  'normal' %}selected{% endif %}>Normal</option>
                                <option value="express" {% if booking.pickup_type  ==  'express' %}selected{% endif %}>Express</option>
                            </select>
                        </div>

                        <div class="col-md-4">
                            <label for="schedule_pickup_date" class="form-label">Pickup Date</label>
                            <input id="schedule_pickup_date" name="schedule_pickup_date" type="date" class="form-control" value="{{ booking.schedule_pickup_date }}">
                        </div>
                        <div class="col-md-4">
                            <label for="schedule_pickup_time" class="form-label">Pickup Time</label>
                            <select id="schedule_pickup_time" name="schedule_pickup_time" class="form-select">
                                <option value="">Select Time Slot</option>
                                {% for slot in time_slots %}
                                    <option value="{{ slot }}" {% if booking.schedule_pickup_time == slot %}selected{% endif %}>{{ slot }}</option>
                                {% endfor %}
                            </select>
                        </div>

                        <div class="col-md-4">
                            <label for="contact_name" class="form-label">Contact Name</label>
                            <input id="contact_name" name="contact_name" type="text" class="form-control" value="{{ booking.contact_name }}">
                        </div>
                        <div class="col-md-4">
                            <label for="contact_mobile" class="form-label">Contact Mobile</label>
                            <input id="contact_mobile" name="contact_mobile" type="text" class="form-control" value="{{ booking.contact_mobile }}">
                        </div>

                        <div class="col-12">
                            <label for="pickup_instructions" class="form-label">Pickup Instructions</label>
                            <textarea id="pickup_instructions" name="pickup_instructions" class="form-control" rows="3">{{ booking.pickup_instructions }}</textarea>
                        </div>

                        <!-- Pickup Address Section -->
                        <div class="col-12">
                            <h6 class="mt-3">Pickup Address</h6>
                            <div class="mb-3">
                                <label class="form-label">Select from User Addresses</label>
                                <select id="user_address_select" class="form-select">
                                    <option value="">-- Select Address --</option>
                                    {% for addr in user_addresses %}
                                        <option value="{{ addr.id }}">{{ addr.get_address_type_display }}: {{ addr.street_address|truncatechars:50 }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                            <div class="card bg-light">
                                <div class="card-body row g-2">
                                    <div class="col-md-12">
                                        <label class="form-label small">Street Address</label>
                                        <input type="text" id="addr_street" class="form-control form-control-sm">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label small">City</label>
                                        <input type="text" id="addr_city" class="form-control form-control-sm">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label small">Zip Code</label>
                                        <input type="text" id="addr_zip" class="form-control form-control-sm">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label small">State</label>
                                        <input type="text" id="addr_state" class="form-control form-control-sm">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label small">Landmark</label>
                                        <input type="text" id="addr_landmark" class="form-control form-control-sm">
                                    </div>
                                </div>
                            </div>
                            <!-- Hidden input to store the final JSON -->
                            <input type="hidden" id="pickup_address" name="pickup_address" value="">
                        </div>

                        <!-- Order Details Section -->
                        <div class="col-12">
                            <h6 class="mt-4">Order Details (Standard)</h6>
                            <div class="card mb-3">
                                <div class="card-body bg-light">
                                    <div class="row g-2 align-items-end">
                                        <div class="col-md-3">
                                            <label class="form-label small">Service</label>
                                            <select id="item_service_standard" class="form-select form-select-sm">
                                                <option value="">Select Service</option>
                                                {% for s in services %}
                                                    <option value="{{ s.id }}" data-name="{{ s.service_name }}">{{ s.service_name }}</option>
                                                {% endfor %}
                                            </select>
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label small">Category</label>
                                            <select id="item_category_standard" class="form-select form-select-sm">
                                                <option value="">Select Category</option>
                                                {% for c in categories %}
                                                    <option value="{{ c.id }}" data-name="{{ c.name }}">{{ c.name }}</option>
                                                {% endfor %}
                                            </select>
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label small">Garment</label>
                                            <select id="item_garment_standard" class="form-select form-select-sm">
                                                <option value="">Select Garment</option>
                                            </select>
                                        </div>
                                        <div class="col-md-1">
                                            <label class="form-label small">Qty</label>
                                            <input type="number" id="item_qty_standard" class="form-control form-control-sm" value="1" min="1">
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label small">Price</label>
                                            <input type="number" id="item_price_standard" class="form-control form-control-sm" step="0.01">
                                        </div>
                                        <div class="col-12 mt-2">
                                            <button type="button" id="btn_add_item_standard" class="btn btn-sm btn-success w-100">Add Item</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="table-responsive">
                                <table class="table table-bordered table-sm" id="order_items_table_standard">
                                    <thead class="table-light">
                                        <tr>
                                            <th>Service</th>
                                            <th>Category</th>
                                            <th>Item</th>
                                            <th>Qty</th>
                                            <th>Price</th>
                                            <th>Total</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody></tbody>
                                </table>
                            </div>
                            <input type="hidden" id="order_details" name="order_details" value="">
                        </div>

                        <!-- Premium Details Section -->
                        <div class="col-12">
                            <h6 class="mt-4">Premium Details</h6>
                            <div class="card mb-3">
                                <div class="card-body bg-light">
                                    <div class="row g-2 align-items-end">
                                        <div class="col-md-2">
                                            <label class="form-label small">Service</label>
                                            <select id="item_service_premium" class="form-select form-select-sm">
                                                <option value="">Select Service</option>
                                                {% for s in services %}
                                                    <option value="{{ s.id }}" data-name="{{ s.service_name }}">{{ s.service_name }}</option>
                                                {% endfor %}
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label small">Category</label>
                                            <select id="item_category_premium" class="form-select form-select-sm">
                                                <option value="">Select Category</option>
                                                {% for c in categories %}
                                                    <option value="{{ c.id }}" data-name="{{ c.name }}">{{ c.name }}</option>
                                                {% endfor %}
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label small">Garment</label>
                                            <select id="item_garment_premium" class="form-select form-select-sm">
                                                <option value="">Select Garment</option>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label small">Brand</label>
                                            <select id="item_brand_premium" class="form-select form-select-sm">
                                                <option value="">Select Brand</option>
                                                {% for b in brands %}
                                                    <option value="{{ b.id }}" data-name="{{ b.brand_name }}">{{ b.brand_name }}</option>
                                                {% endfor %}
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label small">Material</label>
                                            <select id="item_material_premium" class="form-select form-select-sm">
                                                <option value="">Select Material</option>
                                                {% for m in materials %}
                                                    <option value="{{ m.id }}" data-name="{{ m.material_name }}">{{ m.material_name }}</option>
                                                {% endfor %}
                                            </select>
                                        </div>
                                        <div class="col-md-1">
                                            <label class="form-label small">Qty</label>
                                            <input type="number" id="item_qty_premium" class="form-control form-control-sm" value="1" min="1">
                                        </div>
                                        <div class="col-md-1">
                                            <label class="form-label small">Price</label>
                                            <input type="number" id="item_price_premium" class="form-control form-control-sm" step="0.01">
                                        </div>
                                        <div class="col-md-12">
                                            <label class="form-label small">Note</label>
                                            <input type="text" id="item_note_premium" class="form-control form-control-sm" placeholder="Add note...">
                                        </div>
                                        <div class="col-12 mt-2">
                                            <button type="button" id="btn_add_item_premium" class="btn btn-sm btn-success w-100">Add Item</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="table-responsive">
                                <table class="table table-bordered table-sm" id="order_items_table_premium">
                                    <thead class="table-light">
                                        <tr>
                                            <th>Service</th>
                                            <th>Category</th>
                                            <th>Item</th>
                                            <th>Brand</th>
                                            <th>Material</th>
                                            <th>Note</th>
                                            <th>Qty</th>
                                            <th>Price</th>
                                            <th>Total</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody></tbody>
                                </table>
                            </div>
                            <input type="hidden" id="premium_details" name="premium_details" value="">
                        </div>

                        <!-- Luxury Details Section -->
                        <div class="col-12">
                            <h6 class="mt-4">Luxury Details</h6>
                            <div class="card mb-3">
                                <div class="card-body bg-light">
                                    <div class="row g-2 align-items-end">
                                        <div class="col-md-2">
                                            <label class="form-label small">Service</label>
                                            <select id="item_service_luxury" class="form-select form-select-sm">
                                                <option value="">Select Service</option>
                                                {% for s in services %}
                                                    <option value="{{ s.id }}" data-name="{{ s.service_name }}">{{ s.service_name }}</option>
                                                {% endfor %}
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label small">Category</label>
                                            <select id="item_category_luxury" class="form-select form-select-sm">
                                                <option value="">Select Category</option>
                                                {% for c in categories %}
                                                    <option value="{{ c.id }}" data-name="{{ c.name }}">{{ c.name }}</option>
                                                {% endfor %}
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label small">Garment</label>
                                            <select id="item_garment_luxury" class="form-select form-select-sm">
                                                <option value="">Select Garment</option>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label small">Brand</label>
                                            <select id="item_brand_luxury" class="form-select form-select-sm">
                                                <option value="">Select Brand</option>
                                                {% for b in brands %}
                                                    <option value="{{ b.id }}" data-name="{{ b.brand_name }}">{{ b.brand_name }}</option>
                                                {% endfor %}
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label small">Material</label>
                                            <select id="item_material_luxury" class="form-select form-select-sm">
                                                <option value="">Select Material</option>
                                                {% for m in materials %}
                                                    <option value="{{ m.id }}" data-name="{{ m.material_name }}">{{ m.material_name }}</option>
                                                {% endfor %}
                                            </select>
                                        </div>
                                        <div class="col-md-1">
                                            <label class="form-label small">Qty</label>
                                            <input type="number" id="item_qty_luxury" class="form-control form-control-sm" value="1" min="1">
                                        </div>
                                        <div class="col-md-1">
                                            <label class="form-label small">Price</label>
                                            <input type="number" id="item_price_luxury" class="form-control form-control-sm" step="0.01">
                                        </div>
                                        <div class="col-md-12">
                                            <label class="form-label small">Note</label>
                                            <input type="text" id="item_note_luxury" class="form-control form-control-sm" placeholder="Add note...">
                                        </div>
                                        <div class="col-12 mt-2">
                                            <button type="button" id="btn_add_item_luxury" class="btn btn-sm btn-success w-100">Add Item</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="table-responsive">
                                <table class="table table-bordered table-sm" id="order_items_table_luxury">
                                    <thead class="table-light">
                                        <tr>
                                            <th>Service</th>
                                            <th>Category</th>
                                            <th>Item</th>
                                            <th>Brand</th>
                                            <th>Material</th>
                                            <th>Note</th>
                                            <th>Qty</th>
                                            <th>Price</th>
                                            <th>Total</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody></tbody>
                                </table>
                            </div>
                            <input type="hidden" id="luxury_details" name="luxury_details" value="">
                        </div>

                        <div class="col-md-4">
                            <label for="total_quantity" class="form-label">Total Quantity</label>
                            <input id="total_quantity" name="total_quantity" type="number" min="0" class="form-control" value="{{ booking.total_quantity }}">
                        </div>
                        <div class="col-md-4">
                            <label for="total_final_price" class="form-label">Total Final Price</label>
                            <input id="total_final_price" name="total_final_price" type="text" class="form-control" value="{{ booking.total_final_price }}">
                        </div>

                        <div class="col-12">
                            <div class="d-md-flex d-grid align-items-center gap-3">
                                <button type="submit" class="btn btn-primary px-4">Save</button>
                                <button type="submit" name="generate_tags" value="1" class="btn btn-info px-4">Save & Generate Tags</button>
                                <a class="btn btn-light px-4" href="{% url 'booking-management' %}">Cancel</a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

    <!-- Inspection Modal -->
    <div class="modal fade" id="inspectionModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Item Inspection</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div id="inspectionItemsContainer">
                        <!-- Dynamic Content -->
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" id="saveInspectionBtn">Save Inspection</button>
                </div>
            </div>
        </div>
    </div>

{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
    // Data from backend
    const garmentsData = {{ garments_json|safe }};
    const addressesData = {{ addresses_json|safe }};
    const initialPickupAddress = {{ pickup_address_json|safe }};
    const initialOrderDetails = {{ order_details_json|safe }};
    const initialPremiumDetails = {{ premium_details_json|safe }};
    const initialLuxuryDetails = {{ luxury_details_json|safe }};
    const bookingItemsData = {{ booking_items_json|safe }};

    $(document).ready(function() {
        // Initialize Select2
        $('#item_service').select2({ theme: 'bootstrap-5', width: '100%' });
        $('#item_category').select2({ theme: 'bootstrap-5', width: '100%' });
        $('#item_garment').select2({ theme: 'bootstrap-5', width: '100%' });
        $('#user_address_select').select2({ theme: 'bootstrap-5', width: '100%' });
        $('#rider').select2({ theme: 'bootstrap-5', width: '100%' });

        // DOM Elements (jQuery wrappers)
        const $addrStreet = $('#addr_street');
        const $addrCity = $('#addr_city');
        const $addrZip = $('#addr_zip');
        const $addrState = $('#addr_state');
        const $addrLandmark = $('#addr_landmark');
        const $pickupAddressInput = $('#pickup_address');
        const $totalQuantityInput = $('#total_quantity');
        const $totalFinalPriceInput = $('#total_final_price');
        const $inspectionItemsContainer = $('#inspectionItemsContainer');
        const $inspectionModal = new bootstrap.Modal(document.getElementById('inspectionModal'));

        // --- Address Logic ---
        function populateAddressFields(addrObj) {
            if (!addrObj) return;
            $addrStreet.val(addrObj.street_address || addrObj.raw_address || '');
            $addrCity.val(addrObj.city || '');
            $addrZip.val(addrObj.zip_code || '');
            $addrState.val(addrObj.state || '');
            $addrLandmark.val(addrObj.landmark || '');
            updatePickupAddressJson();
        }

        function updatePickupAddressJson() {
            const addr = {
                street_address: $addrStreet.val(),
                city: $addrCity.val(),
                zip_code: $addrZip.val(),
                state: $addrState.val(),
                landmark: $addrLandmark.val(),
                raw_address: `${$addrStreet.val()}, ${$addrCity.val()}` // Fallback
            };
            $pickupAddressInput.val(JSON.stringify(addr));
        }

        // Initialize Address
        if (initialPickupAddress) {
            populateAddressFields(initialPickupAddress);
        }

        $('#user_address_select').on('change', function() {
            const selectedId = parseInt($(this).val());
            const addr = addressesData.find(a => a.id === selectedId);
            if (addr) {
                populateAddressFields(addr);
            }
        });

        $('#addr_street, #addr_city, #addr_zip, #addr_state, #addr_landmark').on('input', updatePickupAddressJson);

        // --- Booking Sections Logic ---
        const sections = {};

        function updateGlobalTotals() {
            let totalQty = 0;
            let totalPrice = 0;
            
            Object.values(sections).forEach(section => {
                section.items.forEach(item => {
                    totalQty += item.qty;
                    totalPrice += (item.totalPrice || 0);
                });
            });

            $totalQuantityInput.val(totalQty);
            $totalFinalPriceInput.val(totalPrice.toFixed(2));
        }

        class BookingSection {
            constructor(type, initialData, inputId) {
                this.type = type;
                this.items = [];
                this.editingIndex = null;
                this.inputId = inputId;
                
                this.$service = $(`#item_service_${type}`);
                this.$category = $(`#item_category_${type}`);
                this.$garment = $(`#item_garment_${type}`);
                this.$qty = $(`#item_qty_${type}`);
                this.$price = $(`#item_price_${type}`);
                this.$btnAdd = $(`#btn_add_item_${type}`);
                this.$tableBody = $(`#order_items_table_${type} tbody`);
                this.$input = $(`#${inputId}`);

                if (this.type !== 'standard') {
                    this.$brand = $(`#item_brand_${type}`);
                    this.$material = $(`#item_material_${type}`);
                    this.$note = $(`#item_note_${type}`);
                }

                this.init();
                if (initialData) this.loadData(initialData);
            }

            init() {
                this.$service.select2({ theme: 'bootstrap-5', width: '100%' });
                this.$category.select2({ theme: 'bootstrap-5', width: '100%' });
                this.$garment.select2({ theme: 'bootstrap-5', width: '100%' });

                if (this.type !== 'standard') {
                    this.$brand.select2({ theme: 'bootstrap-5', width: '100%' });
                    this.$material.select2({ theme: 'bootstrap-5', width: '100%' });
                }

                this.$category.on('change', () => this.populateGarments());
                this.$garment.on('change', () => this.updatePrice());
                this.$btnAdd.on('click', () => this.addItem());
            }

            populateGarments() {
                const catId = parseInt(this.$category.val());
                this.$garment.empty().append('<option value="">Select Garment</option>');
                
                if (catId) {
                    const filtered = garmentsData.filter(g => g.category_id === catId);
                    filtered.forEach(g => {
                        const option = new Option(g.name, g.id, false, false);
                        $(option).attr('data-name', g.name);
                        this.$garment.append(option);
                    });
                }
                this.$garment.trigger('change');
            }

            updatePrice() {
                const serviceId = parseInt(this.$service.val());
                const garmentId = parseInt(this.$garment.val());
                
                if (serviceId && garmentId) {
                    const garment = garmentsData.find(g => g.id === garmentId);
                    if (garment && garment.service_prices) {
                        let price = '';
                        if (Array.isArray(garment.service_prices)) {
                             const sp = garment.service_prices.find(p => p.service_id == serviceId);
                             if (sp) price = sp.price;
                        } else if (typeof garment.service_prices === 'object') {
                             const serviceName = this.$service.find(':selected').data('name');
                             if (garment.service_prices[serviceName]) price = garment.service_prices[serviceName];
                        }
                        this.$price.val(price);
                    }
                }
            }

            addItem() {
                const serviceId = this.$service.val();
                const categoryId = this.$category.val();
                const garmentId = this.$garment.val();
                const qty = parseInt(this.$qty.val());
                let price = parseFloat(this.$price.val());

                // For premium/luxury, price is optional (default to 0)
                if (this.type !== 'standard' && isNaN(price)) {
                    price = 0;
                }

                if (!serviceId || !categoryId || !garmentId || !qty || isNaN(price)) {
                    alert("Please fill all item fields");
                    return;
                }

                const serviceName = this.$service.find(':selected').data('name') || this.$service.find(':selected').text();
                const categoryName = this.$category.find(':selected').data('name') || this.$category.find(':selected').text();
                const garmentName = this.$garment.find(':selected').data('name') || this.$garment.find(':selected').text();

                const newItem = {
                    serviceName, categoryName, itemId: garmentId, itemName: garmentName,
                    qty, unitPrice: price, totalPrice: qty * price
                };

                if (this.type !== 'standard') {
                    newItem.brandId = this.$brand.val();
                    newItem.brandName = this.$brand.find(':selected').data('name') || '';
                    newItem.materialId = this.$material.val();
                    newItem.materialName = this.$material.find(':selected').data('name') || '';
                    newItem.note = this.$note.val();
                }

                if (this.editingIndex !== null) {
                    this.items[this.editingIndex] = newItem;
                    this.editingIndex = null;
                    this.$btnAdd.text("Add Item").removeClass('btn-warning').addClass('btn-success');
                } else {
                    this.items.push(newItem);
                }

                this.render();
                
                // Reset
                this.$garment.val('').trigger('change');
                this.$qty.val(1);
                this.$price.val('');
                if (this.type !== 'standard') {
                    this.$brand.val('').trigger('change');
                    this.$material.val('').trigger('change');
                    this.$note.val('');
                }
            }

            render() {
                this.$tableBody.empty();
                this.items.forEach((item, index) => {
                    let inspectBtn = '';
                    // Filter tags by item_type
                    const bItems = (bookingItemsData[item.itemId] || []).filter(t => t.item_type === this.type);
                    
                    if (bItems.length > 0) {
                        inspectBtn = `<button type="button" class="btn btn-xs btn-info me-1" onclick="openInspectionModal('${this.type}', ${index})">Inspect (${bItems.length})</button>`;
                    } else {
                        inspectBtn = `<span class="badge bg-secondary me-1">No Tags</span>`;
                    }

                    let extraCols = '';
                    if (this.type !== 'standard') {
                        extraCols = `
                            <td>${item.brandName || '-'}</td>
                            <td>${item.materialName || '-'}</td>
                            <td>${item.note || '-'}</td>
                        `;
                    }

                    const tr = `
                        <tr>
                            <td>${item.serviceName}</td>
                            <td>${item.categoryName}</td>
                            <td>${item.itemName}</td>
                            ${extraCols}
                            <td>${item.qty}</td>
                            <td>${(item.unitPrice || 0).toFixed(2)}</td>
                            <td>${(item.totalPrice || 0).toFixed(2)}</td>
                            <td>
                                ${inspectBtn}
                                <button type="button" class="btn btn-xs btn-warning me-1" onclick="editItem('${this.type}', ${index})">Edit</button>
                                <button type="button" class="btn btn-xs btn-danger" onclick="removeItem('${this.type}', ${index})">X</button>
                            </td>
                        </tr>
                    `;
                    this.$tableBody.append(tr);
                });
                this.updateJson();
                updateGlobalTotals();
            }

            updateJson() {
                const result = {};
                this.items.forEach(item => {
                    if (!result[item.serviceName]) result[item.serviceName] = {};
                    if (!result[item.serviceName][item.categoryName]) result[item.serviceName][item.categoryName] = [];
                    
                    const itemData = {
                        item_id: item.itemId,
                        item_name: item.itemName,
                        item_service: item.serviceName,
                        item_quantity: item.qty,
                        unit_price: item.unitPrice,
                        total_item_price: item.totalPrice
                    };

                    if (this.type !== 'standard') {
                        itemData.brand_id = item.brandId;
                        itemData.brand_name = item.brandName;
                        itemData.material_id = item.materialId;
                        itemData.material_name = item.materialName;
                        itemData.note = item.note;
                    }

                    result[item.serviceName][item.categoryName].push(itemData);
                });
                this.$input.val(JSON.stringify(result));
            }

            loadData(data) {
                if (!data) return;
                for (const [serviceName, categories] of Object.entries(data)) {
                    for (const [categoryName, items] of Object.entries(categories)) {
                        items.forEach(item => {
                            let uPrice = parseFloat(item.unit_price);
                            let tPrice = parseFloat(item.total_item_price);
                            
                            if (isNaN(uPrice)) uPrice = 0;
                            if (isNaN(tPrice)) tPrice = 0;

                            const newItem = {
                                serviceName, categoryName,
                                itemId: item.item_id,
                                itemName: item.item_name,
                                qty: item.item_quantity,
                                unitPrice: uPrice,
                                totalPrice: tPrice
                            };
                            if (this.type !== 'standard') {
                                newItem.brandId = item.brand_id;
                                newItem.brandName = item.brand_name;
                                newItem.materialId = item.material_id;
                                newItem.materialName = item.material_name;
                                newItem.note = item.note;
                            }
                            this.items.push(newItem);
                        });
                    }
                }
                this.render();
            }
            
            editItem(index) {
                const item = this.items[index];
                this.editingIndex = index;
                
                // Set Service
                const $serviceOpt = this.$service.find(`option[data-name="${item.serviceName}"]`);
                if ($serviceOpt.length) this.$service.val($serviceOpt.val()).trigger('change');

                // Set Category
                const $catOpt = this.$category.find(`option[data-name="${item.categoryName}"]`);
                if ($catOpt.length) this.$category.val($catOpt.val()).trigger('change');

                // Set Garment
                this.$garment.val(item.itemId).trigger('change');

                // Set Qty and Price
                this.$qty.val(item.qty);
                this.$price.val(item.unitPrice || '');

                if (this.type !== 'standard') {
                    this.$brand.val(item.brandId).trigger('change');
                    this.$material.val(item.materialId).trigger('change');
                    this.$note.val(item.note);
                }

                this.$btnAdd.text("Update Item").removeClass('btn-success').addClass('btn-warning');
            }
            
            removeItem(index) {
                if (this.editingIndex === index) {
                    alert("Cannot remove item while editing it.");
                    return;
                }
                this.items.splice(index, 1);
                if (this.editingIndex !== null && index < this.editingIndex) this.editingIndex--;
                this.render();
            }
            
            openInspectionModal(index) {
                const item = this.items[index];
                $inspectionItemsContainer.empty();
                
                const tags = (bookingItemsData[item.itemId] || []).filter(t => t.item_type === this.type);
                
                if (tags.length === 0) {
                    alert("No tags generated for this item yet.");
                    return;
                }
                
                tags.forEach(tagObj => {
                    const isDamagedChecked = tagObj.is_damaged ? 'checked' : '';
                    const html = `
                        <div class="card mb-3" data-id="${tagObj.id}">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <strong>Tag: ${tagObj.tag}</strong>
                                <button type="button" class="btn btn-sm btn-danger delete-tag-btn" data-id="${tagObj.id}">Delete Tag</button>
                            </div>
                            <div class="card-body">
                                <div class="row g-3">
                                    <div class="col-md-4">
                                        <label class="form-label">Color</label>
                                        <input type="text" class="form-control inspection-color" value="${tagObj.color || ''}" placeholder="e.g. Blue">
                                    </div>
                                    <div class="col-md-2">
                                        <label class="form-label">Damaged?</label>
                                        <div class="form-check mt-2">
                                            <input class="form-check-input inspection-damaged" type="checkbox" ${isDamagedChecked}>
                                            <label class="form-check-label">Yes</label>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Damage Description</label>
                                        <input type="text" class="form-control inspection-desc" value="${tagObj.damage_description || ''}" placeholder="Describe damage...">
                                    </div>
                                </div>
                            </div>
                        </div>
                    `;
                    $inspectionItemsContainer.append(html);
                });
                $inspectionModal.show();
            }
        }

        // Initialize Sections
        sections.standard = new BookingSection('standard', initialOrderDetails, 'order_details');
        sections.premium = new BookingSection('premium', initialPremiumDetails, 'premium_details');
        sections.luxury = new BookingSection('luxury', initialLuxuryDetails, 'luxury_details');

        // Global functions for inline onclick handlers
        window.editItem = function(type, index) {
            sections[type].editItem(index);
        };
        
        window.removeItem = function(type, index) {
            sections[type].removeItem(index);
        };
        
        window.openInspectionModal = function(type, index) {
            sections[type].openInspectionModal(index);
        };

        // Delete Tag Handler
        $(document).on('click', '.delete-tag-btn', function() {
            if (!confirm("Are you sure you want to delete this tag?")) return;
            
            const tagId = $(this).data('id');
            const $card = $(this).closest('.card');
            const urlTemplate = "{% url 'booking-item-delete' 0 %}";
            const url = urlTemplate.replace('0', tagId);

            fetch(url, {
                method: 'POST',
                headers: {
                    'X-CSRFToken': '{{ csrf_token }}'
                }
            }).then(response => {
                if (response.ok) {
                    $card.remove();
                } else {
                    alert("Error deleting tag.");
                }
            });
        });

        $('#saveInspectionBtn').on('click', function() {
            const promises = [];
            const urlTemplate = "{% url 'booking-item-update' 0 %}";

            $inspectionItemsContainer.find('.card').each(function() {
                const $card = $(this);
                const id = $card.data('id');
                const color = $card.find('.inspection-color').val();
                const isDamaged = $card.find('.inspection-damaged').is(':checked');
                const desc = $card.find('.inspection-desc').val();
                
                const url = urlTemplate.replace('0', id);

                const p = fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': '{{ csrf_token }}'
                    },
                    body: JSON.stringify({
                        color: color,
                        is_damaged: isDamaged,
                        damage_description: desc
                    })
                }).then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                });
                promises.push(p);
            });

            Promise.all(promises).then(responses => {
                alert("Inspection details saved!");
                $inspectionModal.hide();
                location.reload(); 
            }).catch(err => {
                alert("Error saving inspection details: " + err);
            });
        });

        updatePickupAddressJson(); // Ensure hidden input is populated on load
    });
</script>
{% endblock %}


{% block extra_css %}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" />
{% endblock %}


