@extends('layouts.app')

@section('title', 'Bookings List | Saai Cards')

@section('content')
<div class="max-w-container-max mx-auto space-y-lg">
    <!-- Page Header Actions -->
    <div class="flex flex-col md:flex-row md:items-center justify-between gap-md mb-xl">
        <div>
            <h2 class="font-headline-md text-headline-md text-on-surface">Quotation List</h2>
            <p class="font-body-md text-body-md text-secondary">Manage quotations — Confirm to send into Job List.</p>
        </div>
        <div class="flex items-center gap-sm">
            <button class="px-md py-sm bg-surface-container-lowest border border-outline-variant text-secondary rounded-lg font-label-md text-label-md flex items-center gap-xs hover:bg-surface-container transition-all" id="exportExcelBtn">
                <span class="material-symbols-outlined text-[18px]">download</span>
                Export Excel
            </button>
            <button class="px-md py-sm bg-surface-container-lowest border border-outline-variant text-secondary rounded-lg font-label-md text-label-md flex items-center gap-xs hover:bg-surface-container transition-all" id="exportPdfBtn">
                <span class="material-symbols-outlined text-[18px]">picture_as_pdf</span>
                PDF Report
            </button>
            <a href="{{ route('bookings.create') }}" class="px-md py-sm bg-primary text-on-primary rounded-lg font-label-md text-label-md flex items-center gap-xs shadow-md hover:bg-opacity-90 transition-all">
                <span class="material-symbols-outlined text-[18px]">add_circle</span>
                Add New Quotation
            </a>
        </div>
    </div>

    <!-- Filters Area -->
    <div class="bg-surface-container-lowest ambient-shadow rounded-xl p-md flex flex-wrap items-center gap-md border border-surface-container mb-lg">
        <div class="flex items-center gap-xs bg-surface-container-low px-sm py-xs rounded-lg border border-outline-variant/30">
            <span class="material-symbols-outlined text-secondary text-[18px]">filter_list</span>
            <span class="font-label-md text-label-md text-secondary">Filters:</span>
        </div>
        <select class="bg-transparent border-none font-label-md text-label-md text-on-surface focus:ring-0 cursor-pointer" id="statusFilter">
            <option value="">All Status</option>
            <option value="Pending">Pending</option>
            <option value="Confirmed">Confirmed</option>
        </select>
        <div class="flex-1"></div>
        <div class="flex items-center gap-xs">
            <span class="font-label-sm text-label-sm text-secondary">Items:</span>
            <span class="font-label-md text-label-md text-on-surface font-bold" id="totalRecords">Loading...</span>
        </div>
    </div>

    <!-- Modern Data Table -->
    <div class="bg-surface-container-lowest ambient-shadow rounded-xl overflow-hidden border border-surface-container">
        <div class="overflow-x-auto custom-scrollbar p-md">
            <table id="bookingsTable" class="w-full text-left border-collapse stripe hover dataTable">
                <thead>
                    <tr class="bg-surface-container-low/50">
                        <th class="px-lg py-md font-label-md text-label-md text-secondary uppercase tracking-wider border-b border-surface-container">Booking No</th>
                        <th class="px-lg py-md font-label-md text-label-md text-secondary uppercase tracking-wider border-b border-surface-container">Date</th>
                        <th class="px-lg py-md font-label-md text-label-md text-secondary uppercase tracking-wider border-b border-surface-container">Customer</th>
                        <th class="px-lg py-md font-label-md text-label-md text-secondary uppercase tracking-wider border-b border-surface-container">Job Name</th>
                        <th class="px-lg py-md font-label-md text-label-md text-secondary uppercase tracking-wider border-b border-surface-container text-right">Amount</th>
                        <th class="px-lg py-md font-label-md text-label-md text-secondary uppercase tracking-wider border-b border-surface-container text-right">Advance</th>
                        <th class="px-lg py-md font-label-md text-label-md text-secondary uppercase tracking-wider border-b border-surface-container text-right">Balance</th>
                        <th class="px-lg py-md font-label-md text-label-md text-secondary uppercase tracking-wider border-b border-surface-container">Status</th>
                        <th class="px-lg py-md font-label-md text-label-md text-secondary uppercase tracking-wider border-b border-surface-container text-center">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-surface-container">
                </tbody>
            </table>
        </div>
    </div>
</div>

@endsection

@stack('scripts')
<script>
    document.addEventListener("DOMContentLoaded", function() {
        let table = $('#bookingsTable').DataTable({
            processing: true,
            serverSide: true,
            ajax: {
                url: "{{ route('bookings.index') }}",
                data: function(d) {
                    d.status = $('#statusFilter').val();
                }
            },
            columns: [
                {data: 'booking_no', name: 'booking_no', render: function(data) { 
                    return '<span class="font-label-md text-label-md text-primary font-bold">'+data+'</span>'; 
                }},
                {data: 'booking_date', name: 'booking_date', render: function(data) {
                    return '<span class="font-body-md text-body-md text-on-surface-variant">'+data+'</span>';
                }},
                {data: 'customer_name', name: 'customer_name', render: function(data) {
                    data = data || 'N/A';
                    let initials = data.substring(0, 2).toUpperCase();
                    return `<div class="flex items-center gap-sm">
                                <div class="w-8 h-8 rounded-full bg-secondary-container flex items-center justify-center font-bold text-on-secondary-container text-[10px]">${initials}</div>
                                <span class="font-label-md text-label-md text-on-surface">${data}</span>
                            </div>`;
                }},
                {data: 'job_name', name: 'job_name', render: function(data) {
                    return '<span class="font-body-md text-body-md text-on-surface">'+data+'</span>';
                }},
                {data: 'grand_total', name: 'grand_total', className: 'text-right', render: function(data) { 
                    return '<span class="font-label-md text-label-md text-on-surface font-bold">₹'+parseFloat(data).toFixed(2)+'</span>'; 
                }},
                {data: 'advance', name: 'advance', className: 'text-right', orderable: false, searchable: false, render: function(data) { 
                    return '<span class="text-green-600 font-label-md text-label-md">₹'+parseFloat(data).toFixed(2)+'</span>'; 
                }},
                {data: 'balance', name: 'balance', className: 'text-right', orderable: false, searchable: false, render: function(data) { 
                    return '<span class="text-error font-label-md text-label-md">₹'+parseFloat(data).toFixed(2)+'</span>'; 
                }},
                {data: 'status', name: 'status', render: function(data, type, row) {
                    let current = (data === 'Confirmed') ? 'Confirmed' : 'Pending';
                    let badgeClass = current === 'Confirmed'
                        ? 'bg-emerald-50 text-emerald-700 border-emerald-100'
                        : 'bg-amber-50 text-amber-700 border-amber-100';
                    
                    return `<select class="status-changer outline-none font-label-sm text-label-sm rounded-full px-sm py-1 border ${badgeClass} cursor-pointer" data-id="${row.id}">
                                <option value="Pending" ${current === 'Pending' ? 'selected' : ''}>Pending</option>
                                <option value="Confirmed" ${current === 'Confirmed' ? 'selected' : ''}>Confirmed</option>
                            </select>`;
                }},
                {data: 'action', name: 'action', orderable: false, searchable: false, className: 'text-center', render: function(data, type, row) {
                    let viewUrl = "{{ url('bookings') }}/" + row.id;
                    let editUrl = "{{ url('bookings') }}/" + row.id + "/edit";
                    
                    return `<div class="flex items-center justify-center gap-xs">
                                <a href="${viewUrl}" class="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-primary-container hover:text-primary transition-all text-secondary" title="View Booking">
                                    <span class="material-symbols-outlined text-[18px]">visibility</span>
                                </a>
                                <a href="${editUrl}" class="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-blue-100 hover:text-blue-700 transition-all text-secondary" title="Edit Booking">
                                    <span class="material-symbols-outlined text-[18px]">edit</span>
                                </a>
                                <button type="button" class="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-error-container hover:text-error transition-all text-secondary delete-btn" data-id="${row.id}" title="Delete Booking">
                                    <span class="material-symbols-outlined text-[18px]">delete</span>
                                </button>
                            </div>`;
                }},
            ],
            dom: '<"flex justify-between items-center mb-4"lf>rt<"flex justify-between items-center mt-4"ip>',
            buttons: ['excel', 'pdf'],
            order: [[0, 'desc']],
            pageLength: 25,
            responsive: true,
            createdRow: function(row, data, dataIndex) {
                $(row).addClass('hover:bg-surface-container-low transition-colors duration-150');
                $(row).find('td').addClass('px-lg py-md border-b border-surface-container whitespace-nowrap');
            },
            drawCallback: function(settings) {
                $('#totalRecords').text(settings.fnRecordsDisplay() + ' Total');
            }
        });

        // Trigger filters
        $('#statusFilter').on('change', function() {
            table.draw();
        });
        
        // Export buttons
        $('#exportExcelBtn').on('click', function() {
            table.button('.buttons-excel').trigger();
        });
        $('#exportPdfBtn').on('click', function() {
            table.button('.buttons-pdf').trigger();
        });

        // Delete Record
        $('body').on('click', '.delete-btn', function () {
            let id = $(this).data('id');
            Swal.fire({
                title: 'Are you sure?',
                text: "This will permanently delete this booking!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#ba1a1a',
                cancelButtonColor: '#737686',
                confirmButtonText: 'Yes, delete it!'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: "{{ url('bookings') }}/" + id,
                        type: 'DELETE',
                        success: function (data) {
                            table.draw();
                            Swal.fire({icon: 'success', title: 'Deleted!', text: data.message, timer: 1500, showConfirmButton: false});
                        },
                        error: function (xhr) {
                            Swal.fire({icon: 'error', title: 'Error', text: 'Cannot delete this booking.'});
                        }
                    });
                }
            });
        });

        // Inline Status Changer
        $('body').on('change', '.status-changer', function() {
            let id = $(this).data('id');
            let newStatus = $(this).val();
            let selectElement = $(this);
            
            selectElement.removeClass('bg-amber-50 text-amber-700 border-amber-100 bg-emerald-50 text-emerald-700 border-emerald-100');
            if (newStatus === 'Pending') selectElement.addClass('bg-amber-50 text-amber-700 border-amber-100');
            else selectElement.addClass('bg-emerald-50 text-emerald-700 border-emerald-100');

            $.ajax({
                url: "{{ url('bookings') }}/" + id + "/status",
                type: 'PATCH',
                data: {
                    _token: '{{ csrf_token() }}',
                    status: newStatus
                },
                success: function(response) {
                    let msg = 'Status updated to ' + newStatus;
                    if (newStatus === 'Confirmed') msg += ' — sent to Job List';
                    Swal.fire({
                        toast: true, position: 'top-end', icon: 'success', title: msg, showConfirmButton: false, timer: 2000
                    });
                },
                error: function() {
                    Swal.fire({icon: 'error', title: 'Error', text: 'Could not update status.'});
                    table.draw(false);
                }
            });
        });
    });
</script>
