@extends('layouts.app')

@section('title', 'New Quotation Booking | Saai Cards')

@section('content')
<div class="max-w-3xl mx-auto">
    <div class="flex justify-between items-center mb-xl">
        <div>
            <h2 class="font-headline-md text-headline-md text-on-surface">Create Quotation Booking</h2>
            <p class="font-body-md text-body-md text-secondary">Select options — final amount = (all selected prices added) × quantity.</p>
        </div>
        <a href="{{ route('bookings.index') }}" class="px-lg py-2 border border-outline-variant rounded-xl font-label-md text-label-md text-secondary hover:bg-surface-container transition-colors inline-block text-center">Back to List</a>
    </div>

    <form action="{{ route('bookings.store') }}" method="POST" id="bookingForm" class="bg-surface-container-lowest rounded-xl custom-shadow border border-surface-container p-xl">
        @csrf
        
        <div class="space-y-md">
            <div class="grid grid-cols-1 md:grid-cols-3 gap-md items-center">
                <label class="font-label-md text-label-md text-on-surface-variant md:text-right">Date</label>
                <div class="md:col-span-2">
                    <input type="date" class="w-full bg-white border border-outline-variant rounded-lg px-md py-sm text-body-md focus:border-primary focus:ring-2 focus:ring-primary/20 transition-all outline-none" id="booking_date" name="booking_date" value="{{ date('Y-m-d') }}" required>
                </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-3 gap-md items-center">
                <label class="font-label-md text-label-md text-on-surface-variant md:text-right">Customer <span class="text-error">*</span></label>
                <div class="md:col-span-2">
                    <select class="w-full select2-tw bg-surface-container-low border border-outline-variant/50 rounded-lg px-md py-sm text-body-md" name="customer_id" id="customer_id" required>
                        <option value="">Select Customer</option>
                        @foreach($customers as $cust)
                            <option value="{{ $cust->id }}"
                                data-address="{{ $cust->address }}"
                                data-mobile="{{ $cust->mobile }}">
                                {{ $cust->name }}
                            </option>
                        @endforeach
                    </select>
                    <p class="mt-1 text-[11px] text-secondary">Add customers from the Customers menu first.</p>
                </div>
            </div>

            <div id="customerInfo" class="hidden grid grid-cols-1 md:grid-cols-3 gap-md items-start">
                <label class="font-label-md text-label-md text-on-surface-variant md:text-right pt-1">Customer Info</label>
                <div class="md:col-span-2 text-body-md text-on-surface-variant bg-surface-container-low rounded-lg px-md py-sm border border-outline-variant/30">
                    <div><strong>Address:</strong> <span id="info_address">-</span></div>
                    <div><strong>Mobile:</strong> <span id="info_mobile">-</span></div>
                </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-3 gap-md items-center">
                <label class="font-label-md text-label-md text-on-surface-variant md:text-right">Category Name</label>
                <div class="md:col-span-2">
                    <select class="w-full select2-tw price-field bg-surface-container-low border border-outline-variant/50 rounded-lg px-md py-sm text-body-md" name="category_id" id="category_id" required>
                        <option value="" data-price="0" data-name="">Select Category</option>
                        @foreach($categories as $cat)
                            <option value="{{ $cat->id }}" data-price="{{ $cat->price ?? 0 }}" data-name="{{ $cat->name }}">{{ $cat->name }} (₹{{ number_format($cat->price ?? 0, 2) }})</option>
                        @endforeach
                    </select>
                </div>
            </div>

            <div id="dependentFields" class="space-y-md">
                <div class="grid grid-cols-1 md:grid-cols-3 gap-md items-center">
                    <label class="font-label-md text-label-md text-on-surface-variant md:text-right">Print Paper Size</label>
                    <div class="md:col-span-2">
                        <select class="w-full select2-tw price-field bg-surface-container-low border border-outline-variant/50 rounded-lg px-md py-sm text-body-md" name="paper_size_id">
                            <option value="" data-price="0" data-name="">Select Size</option>
                            @foreach($paperSizes as $ps)
                                <option value="{{ $ps->id }}" data-price="{{ $ps->price ?? 0 }}" data-name="{{ $ps->name }}">{{ $ps->name }} (₹{{ number_format($ps->price ?? 0, 2) }})</option>
                            @endforeach
                        </select>
                    </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-3 gap-md items-center">
                    <label class="font-label-md text-label-md text-on-surface-variant md:text-right">GSM</label>
                    <div class="md:col-span-2">
                        <select class="w-full select2-tw price-field bg-surface-container-low border border-outline-variant/50 rounded-lg px-md py-sm text-body-md" name="paper_gsm_id">
                            <option value="" data-price="0" data-name="">Select</option>
                            @foreach($paperGsms as $gsm)
                                <option value="{{ $gsm->id }}" data-price="{{ $gsm->price ?? 0 }}" data-name="{{ $gsm->name }}">{{ $gsm->name }} (₹{{ number_format($gsm->price ?? 0, 2) }})</option>
                            @endforeach
                        </select>
                    </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-3 gap-md items-center">
                    <label class="font-label-md text-label-md text-on-surface-variant md:text-right">Print Type</label>
                    <div class="md:col-span-2">
                        <select class="w-full select2-tw price-field bg-surface-container-low border border-outline-variant/50 rounded-lg px-md py-sm text-body-md" name="print_type_id">
                            <option value="" data-price="0">Select</option>
                            @foreach($printTypes as $item)
                                <option value="{{ $item->id }}" data-price="{{ $item->price ?? 0 }}">{{ $item->name }} (₹{{ number_format($item->price ?? 0, 2) }})</option>
                            @endforeach
                        </select>
                    </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-3 gap-md items-center">
                    <label class="font-label-md text-label-md text-on-surface-variant md:text-right">Lamination</label>
                    <div class="md:col-span-2">
                        <select class="w-full select2-tw price-field bg-surface-container-low border border-outline-variant/50 rounded-lg px-md py-sm text-body-md" name="lamination_id">
                            <option value="" data-price="0">NONE</option>
                            @foreach($laminations as $item)
                                <option value="{{ $item->id }}" data-price="{{ $item->price ?? 0 }}">{{ $item->name }} (₹{{ number_format($item->price ?? 0, 2) }})</option>
                            @endforeach
                        </select>
                    </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-3 gap-md items-center">
                    <label class="font-label-md text-label-md text-on-surface-variant md:text-right">Lamination Side</label>
                    <div class="md:col-span-2">
                        <select class="w-full select2-tw price-field bg-surface-container-low border border-outline-variant/50 rounded-lg px-md py-sm text-body-md" name="lamination_side_id">
                            <option value="" data-price="0">NONE</option>
                            @foreach($laminationSides as $item)
                                <option value="{{ $item->id }}" data-price="{{ $item->price ?? 0 }}">{{ $item->name }} (₹{{ number_format($item->price ?? 0, 2) }})</option>
                            @endforeach
                        </select>
                    </div>
                </div>

                <!-- Bill Book Options -->
                <div id="billBookFields" class="space-y-md hidden">
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-md items-center">
                        <label class="font-label-md text-label-md text-on-surface-variant md:text-right">Carbon Copy</label>
                        <div class="md:col-span-2">
                            <select class="w-full select2-tw price-field bg-surface-container-low border border-outline-variant/50 rounded-lg px-md py-sm text-body-md" name="carbon_copy" id="carbon_copy">
                                <option value="" data-price="0">Select</option>
                                @foreach($carbonCopies as $cc)
                                    <option value="{{ $cc->name }}" data-price="{{ $cc->price ?? 0 }}">{{ $cc->name }} (₹{{ number_format($cc->price ?? 0, 2) }})</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-md items-center">
                        <label class="font-label-md text-label-md text-on-surface-variant md:text-right">Binding</label>
                        <div class="md:col-span-2">
                            <select class="w-full select2-tw price-field bg-surface-container-low border border-outline-variant/50 rounded-lg px-md py-sm text-body-md" name="bill_binding" id="bill_binding">
                                <option value="" data-price="0">Select</option>
                                @foreach($bindings as $bind)
                                    <option value="{{ $bind->name }}" data-price="{{ $bind->price ?? 0 }}">{{ $bind->name }} (₹{{ number_format($bind->price ?? 0, 2) }})</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-3 gap-md items-center">
                    <label class="font-label-md text-label-md text-on-surface-variant md:text-right">Quantity</label>
                    <div class="md:col-span-2">
                        <input type="number" class="w-full bg-white border border-on-surface rounded-sm px-md py-sm text-body-md font-bold focus:border-primary focus:ring-1 focus:ring-primary outline-none" name="quantity" id="quantity" value="200" min="1" required>
                    </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-3 gap-md items-start">
                    <label class="font-label-md text-label-md text-on-surface-variant md:text-right pt-sm">Enter Job Name</label>
                    <div class="md:col-span-2">
                        <textarea class="w-full bg-surface-container-low border border-outline-variant/50 rounded-lg px-md py-sm text-body-md focus:border-primary focus:ring-2 focus:ring-primary/20 transition-all outline-none resize-none h-24" name="job_name" placeholder="Ex:INVITATION CARDS ABC SIZE" required></textarea>
                    </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-3 gap-md items-start pt-md">
                    <label class="font-label-md text-label-md text-on-surface-variant md:text-right pt-1">Price Breakup</label>
                    <div class="md:col-span-2">
                        <div id="price_breakdown" class="bg-surface-container-low border border-outline-variant/50 rounded-lg px-md py-sm text-body-md text-on-surface-variant space-y-1 text-sm">
                            <div>Select options to see pricing</div>
                        </div>
                    </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-3 gap-md items-center">
                    <label class="font-label-md text-label-md text-on-surface-variant md:text-right">Unit Total</label>
                    <div class="md:col-span-2">
                        <input type="text" id="unit_price_display" class="w-full bg-surface-container-low border border-outline-variant/50 rounded-lg px-md py-sm text-body-md font-bold" value="₹0.00" readonly>
                        <p class="mt-1 text-[11px] text-secondary">Sum of all selected master prices</p>
                    </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-3 gap-md items-center">
                    <label class="font-label-md text-label-md text-on-surface-variant md:text-right">Final Amount *</label>
                    <div class="md:col-span-2">
                        <input type="number" step="0.01" class="w-full bg-white border border-outline-variant rounded-lg px-md py-sm text-body-md focus:border-primary focus:ring-2 focus:ring-primary/20 transition-all outline-none font-bold" name="grand_total" id="grand_total" required>
                        <p class="mt-1 text-[11px] text-secondary">Auto: Unit Total × Quantity (editable)</p>
                    </div>
                </div>
            </div>
            
            <input type="hidden" name="booking_no" value="{{ $booking_no ?? 'BK-'.time() }}">
            <input type="hidden" name="status" value="Pending">

            <div class="grid grid-cols-1 md:grid-cols-3 gap-md items-center pt-lg mt-lg border-t border-surface-container">
                <div class="md:col-start-2 flex gap-md">
                    <button type="submit" class="bg-primary border border-primary text-on-primary px-xl py-sm rounded font-bold hover:brightness-110 transition-all shadow-sm">
                        Book Now
                    </button>
                    <button type="button" class="bg-[#2980b9] border border-[#2980b9] text-white px-xl py-sm rounded font-bold hover:bg-[#3498db] transition-all shadow-sm" onclick="document.getElementById('bookingForm').reset();">
                        Refresh
                    </button>
                </div>
            </div>
        </div>
    </form>
</div>
@endsection

@stack('scripts')
<script>
    document.addEventListener("DOMContentLoaded", function() {
        const dependencyMap = {
            'Invitations': {
                sizes: ['A4', 'A3', '22.5" X 11.5"', 'DEMI', 'A4 - ROYAL', 'A3 - ROYAL', 'DEMI ROYAL', '24.5" X 11.5"', '20" X 30"', '14.5"X19.5" / 29"X9"', '19"X7" / 14"X9.5"', '35"x11" (or) 22"x17.5"'],
                gsms: ['60 Gsm Maplitho', '70 Gsm Maplitho', '80 Gsm Maplitho', '90 Gsm Maplitho', '120 Gsm Maplitho', '100 Gsm Art Paper', '105 Gsm Art Paper', '130 Gsm Art Paper', '170 Gsm Art Paper', '220 Gsm Art Board', '250 Gsm Art Board', '300 Gsm Art Board', '350 Gsm Art Board']
            },
            'Invitation Covers': {
                sizes: ['Cover A4'],
                gsms: ['70 Gsm Maplitho', '80 Gsm Maplitho', '100 Gsm Art Paper', '105 Gsm Art Paper', '130 Gsm Art Paper', '170 Gsm Art Paper', '220 Gsm Art Board', '250 Gsm Art Board', '300 Gsm Art Board']
            },
            'Office Covers': {
                sizes: ['Cover A4', 'Cover 10.5" x 4.5"', 'Cover 9" x 4"', 'Cover 6" x 4"'],
                gsms: ['60 Gsm Maplitho', '70 Gsm Maplitho', '80 Gsm Maplitho', '90 Gsm Maplitho', '120 Gsm Maplitho', '100 Gsm Art Paper', '105 Gsm Art Paper', '130 Gsm Art Paper', '170 Gsm Art Paper']
            },
            'Brouchre': {
                sizes: ['A3', '22.5" X 11.5"', 'DEMI', 'A3 - ROYAL', 'DEMI ROYAL', '20" X 30"', '14.5"X19.5" / 29"X9"', '19"X7" / 14"X9.5"', 'A4', 'A4 - ROYAL', '28" X 40"', '35"x11" (or) 22"x17.5"'],
                gsms: ['60 Gsm Maplitho', '70 Gsm Maplitho', '80 Gsm Maplitho', '90 Gsm Maplitho', '120 Gsm Maplitho', '100 Gsm Art Paper', '105 Gsm Art Paper', '130 Gsm Art Paper', '170 Gsm Art Paper', '80 Gsm Bond Paper', '100 Gsm Bond Paper']
            },
            'Catalogues': {
                sizes: ['A3', '22.5" X 11.5"', 'DEMI', 'A3 - ROYAL', 'DEMI ROYAL', '24.5" X 11.5"', '14.5"X19.5" / 29"X9"', '19"X7" / 14"X9.5"', '22" X 28"', '21.5" X 13.5"', 'A4', 'A4 - ROYAL', '28" X 40"'],
                gsms: ['170 Gsm Art Paper', '220 Gsm Art Board', '250 Gsm Art Board', '300 Gsm Art Board']
            },
            'Letter Head': {
                sizes: ['A4 Bond (210 X 280)', 'A4 Bond Royal (210 X 297)'],
                gsms: ['80 Gsm Bond Paper', '100 Gsm Bond Paper']
            },
            'Sticker': {
                sizes: ['Sticker - Demi Royal', 'Sticker - A4', 'Sticker - A3', 'Sticker - Demi', 'Sticker - 15" x 20"', 'Sticker - 20" x 30"'],
                gsms: ['Sticker Chrome Art (20" X 30" / 23" X 36")', 'Sticker Mirror Coat (23" X 36")']
            },
            'Calendars': {
                sizes: ['DEMI', '20" X 30"', 'DEMI ROYAL', '28" X 40"'],
                gsms: ['60 Gsm Maplitho', '70 Gsm Maplitho', '80 Gsm Maplitho', '90 Gsm Maplitho', '120 Gsm Maplitho', '100 Gsm Art Paper', '105 Gsm Art Paper', '130 Gsm Art Paper', '170 Gsm Art Paper', '220 Gsm Art Board', '250 Gsm Art Board', '300 Gsm Art Board', '350 Gsm Art Board']
            },
            'Bill Book': {
                sizes: ['A4', 'A3', 'DEMI', 'A4 - ROYAL', 'A3 - ROYAL', 'DEMI ROYAL'],
                gsms: ['60 Gsm Maplitho', '70 Gsm Maplitho', '80 Gsm Maplitho', '90 Gsm Maplitho', '120 Gsm Maplitho', '100 Gsm Art Paper', '105 Gsm Art Paper', '130 Gsm Art Paper']
            }
        };

        const categorySelect = document.querySelector('[name="category_id"]');
        const sizeSelect = document.querySelector('[name="paper_size_id"]');
        const gsmSelect = document.querySelector('[name="paper_gsm_id"]');
        const qtyInput = document.getElementById('quantity');
        const grandTotal = document.getElementById('grand_total');
        const unitPriceDisplay = document.getElementById('unit_price_display');
        const billBookFields = document.getElementById('billBookFields');
        const breakdownEl = document.getElementById('price_breakdown');

        const priceFieldNames = {
            category_id: 'Category',
            paper_size_id: 'Paper Size',
            paper_gsm_id: 'GSM',
            print_type_id: 'Print Type',
            lamination_id: 'Lamination',
            lamination_side_id: 'Lamination Side',
            carbon_copy: 'Carbon Copy',
            bill_binding: 'Binding'
        };

        function getSelectedCategoryName() {
            const opt = categorySelect?.options[categorySelect.selectedIndex];
            return opt?.dataset?.name || '';
        }

        function getOptionPrice(selectEl) {
            if (!selectEl || !selectEl.value) return 0;
            const opt = selectEl.options[selectEl.selectedIndex];
            return parseFloat(opt?.dataset?.price || 0) || 0;
        }

        function getOptionLabel(selectEl) {
            if (!selectEl || !selectEl.value) return '';
            const opt = selectEl.options[selectEl.selectedIndex];
            return opt?.dataset?.name || (opt?.text || '').replace(/\s*\(₹.*\)$/, '');
        }

        function calculateAmount() {
            let unitTotal = 0;
            let lines = [];

            Object.keys(priceFieldNames).forEach(function(name) {
                const el = document.querySelector('[name="' + name + '"]');
                if (!el) return;
                if ((name === 'carbon_copy' || name === 'bill_binding') && billBookFields.classList.contains('hidden')) {
                    return;
                }
                if (!el.value) return;
                const price = getOptionPrice(el);
                unitTotal += price;
                lines.push('<div class="flex justify-between gap-2"><span>' + priceFieldNames[name] + ': ' + getOptionLabel(el) + '</span><span class="font-semibold text-on-surface">₹' + price.toFixed(2) + '</span></div>');
            });

            const qty = parseFloat(qtyInput?.value || 0) || 0;
            unitPriceDisplay.value = '₹' + unitTotal.toFixed(2);
            grandTotal.value = (unitTotal * qty).toFixed(2);

            if (lines.length) {
                lines.push('<div class="flex justify-between gap-2 border-t border-outline-variant/40 pt-1 mt-1"><span class="font-semibold">Unit Total × Qty (' + qty + ')</span><span class="font-bold text-primary">₹' + (unitTotal * qty).toFixed(2) + '</span></div>');
                breakdownEl.innerHTML = lines.join('');
            } else {
                breakdownEl.innerHTML = '<div>Select options to see pricing</div>';
            }
        }

        function toggleBillBookFields() {
            const name = getSelectedCategoryName();
            if (name === 'Bill Book') {
                billBookFields.classList.remove('hidden');
            } else {
                billBookFields.classList.add('hidden');
                $('#carbon_copy').val('').trigger('change');
                $('#bill_binding').val('').trigger('change');
            }
        }

        function optionMatchName(opt) {
            return opt.dataset.name || opt.text.replace(/\s*\(₹.*\)$/, '');
        }

        function updateDropdowns() {
            if (!categorySelect) return;
            const selectedText = getSelectedCategoryName();
            const rules = dependencyMap[selectedText];

            if (sizeSelect) {
                Array.from(sizeSelect.options).forEach(opt => {
                    if (opt.value === "") {
                        opt.hidden = false; opt.disabled = false;
                    } else if (rules) {
                        const isMatch = rules.sizes.includes(optionMatchName(opt));
                        opt.hidden = !isMatch; opt.disabled = !isMatch;
                    } else {
                        opt.hidden = true; opt.disabled = true;
                    }
                });
                sizeSelect.selectedIndex = 0;
                if ($(sizeSelect).data('select2')) $(sizeSelect).trigger('change');
            }

            if (gsmSelect) {
                Array.from(gsmSelect.options).forEach(opt => {
                    if (opt.value === "") {
                        opt.hidden = false; opt.disabled = false;
                    } else if (rules) {
                        const isMatch = rules.gsms.includes(optionMatchName(opt));
                        opt.hidden = !isMatch; opt.disabled = !isMatch;
                    } else {
                        opt.hidden = true; opt.disabled = true;
                    }
                });
                gsmSelect.selectedIndex = 0;
                if ($(gsmSelect).data('select2')) $(gsmSelect).trigger('change');
            }

            toggleBillBookFields();
            calculateAmount();
        }

        $(categorySelect).on('change', updateDropdowns);
        $(qtyInput).on('input change', calculateAmount);
        $('.price-field').on('change', calculateAmount);
        updateDropdowns();

        $('#customer_id').on('change', function() {
            const opt = this.options[this.selectedIndex];
            if (this.value) {
                $('#info_address').text(opt.dataset.address || '-');
                $('#info_mobile').text(opt.dataset.mobile || '-');
                $('#customerInfo').removeClass('hidden').addClass('grid');
            } else {
                $('#customerInfo').addClass('hidden').removeClass('grid');
            }
        });
    });
</script>
