<?php $__env->startSection('title', __('restaurant.bookings')); ?>

<?php $__env->startSection('content'); ?>
    <!-- Content Header (Page header) -->
    <section class="content-header">
        <h1><?php echo app('translator')->getFromJson('restaurant.bookings'); ?> & Guest Management</h1>
    </section>

    <!-- Main content -->
    <section class="content">
        <div class="row">
            <?php if(count($business_locations) >= 1): ?>
                <div class="col-sm-12">
                    <select id="business_location_id" class="select2" style="width:50%">
                        <option value=""><?php echo app('translator')->getFromJson('purchase.business_location'); ?></option>
                        <?php $__currentLoopData = $business_locations; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $value): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($key, false); ?>"><?php echo e($value, false); ?></option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                </div>
            <?php endif; ?>
        </div>
        <br>

        <!-- Today's Bookings with Guest Information -->
        <div class="row">
            <div class="col-sm-12">
                <div class="box box-primary">
                    <div class="box-header with-border">
                        <h3 class="box-title">
                            <i class="fa fa-calendar-check-o"></i> <?php echo app('translator')->getFromJson('restaurant.todays_bookings'); ?> with Guest Details
                        </h3>
                        <div class="box-tools pull-right">
                            <button type="button" class="btn btn-box-tool" data-widget="collapse">
                                <i class="fa fa-minus"></i>
                            </button>
                        </div>
                    </div>
                    <div class="box-body">
                        <div class="table-responsive">
                            <table class="table table-bordered table-condensed table-striped" id="todays_bookings_table">
                                <thead>
                                <tr>
                                    <th>Guest Name</th>
                                    <th>Contact Info</th>
                                    <th>Guest Details</th>
                                    <th>Room Details</th>
                                    <th>Booking Times</th>
                                    <th>Table</th>
                                    <th>Location</th>
                                    <th>Staff</th>
                                    <th>Price</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                                </thead>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Guest Check-ins Summary -->
        <div class="row">
            <div class="col-sm-12">
                <div class="box box-info">
                    <div class="box-header with-border">
                        <h3 class="box-title">
                            <i class="fa fa-users"></i> Recent Guest Check-ins
                        </h3>
                        <div class="box-tools pull-right">
                            <button type="button" class="btn btn-box-tool" data-widget="collapse">
                                <i class="fa fa-minus"></i>
                            </button>
                        </div>
                    </div>
                    <div class="box-body">
                        <div class="table-responsive">
                            <table class="table table-bordered table-condensed table-striped" id="guest_checkins_table">
                                <thead>
                                <tr>
                                    <th>Full Name</th>
                                    <th>Email</th>
                                    <th>Phone</th>
                                    <th>Gender</th>
                                    <th>Nationality</th>
                                    <th>Stay Purpose</th>
                                    <th>Payment Method</th>
                                    <th>Staff Ack.</th>
                                    <th>Guest Ack.</th>
                                    <th>Booking Status</th>
                                    <th>Created At</th>
                                    <th>Action</th>
                                </tr>
                                </thead>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

             <!-- Online Booking -->
  

<div class="row">
    <div class="col-sm-12">
        <div class="box box-info">
            <div class="box-header with-border">
                <h3 class="box-title">
                    <i class="fa fa-users"></i> Online Booking guests
                </h3>
                <div class="box-tools pull-right">
                    <button type="button" class="btn btn-box-tool" data-widget="collapse">
                        <i class="fa fa-minus"></i>
                    </button>
                </div>
            </div>
            <div class="box-body">
                <div class="table-responsive">
                    <table class="table table-bordered table-condensed table-striped" id="guest_checkins_table">
                        <thead>
                        <tr>
                            <th>Full Name</th>
                            <th>Email</th>
                            <th>Phone</th>
                            <th>Gender</th>
                            <th>Room Type</th>
                            <th>Check-in</th>
                            <th>Check-out</th>
                            <th>Days</th>
                            <th>Adults</th>
                            <th>Rooms</th>
                            <th>Occupancy</th>
                            <th>Price/Room</th>
                            <th>Total Price</th>
                            <th>Created At</th>
                            <th>Action</th>
                        </tr>
                        </thead>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

        <!-- Calendar View -->
        <div class="row">
            <div class="col-sm-10">
                <div class="box">
                    <div class="box-header with-border">
                        <h3 class="box-title">
                            <i class="fa fa-calendar"></i> Booking Calendar
                        </h3>
                    </div>
                    <div class="box-body">
                        <div class="row">
                            <div class="col-sm-12 text-right">
                                <button type="button" class="btn btn-primary" id="add_new_booking_btn">
                                    <i class="fa fa-plus"></i> <?php echo app('translator')->getFromJson('restaurant.add_booking'); ?>
                                </button>
                            </div>
                        </div>
                        <br>
                        <div class="row">
                            <div class="col-sm-12">
                                <div id="calendar"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-sm-2">
                <div class="box box-solid">
                    <div class="box-header with-border">
                        <h3 class="box-title">Legend</h3>
                    </div>
                    <div class="box-body">
                        <div class="external-event bg-yellow text-center" style="position: relative;">
                            <small><?php echo app('translator')->getFromJson('lang_v1.waiting'); ?></small>
                        </div>
                        <div class="external-event bg-light-blue text-center" style="position: relative;">
                            <small><?php echo app('translator')->getFromJson('restaurant.booked'); ?></small>
                        </div>
                        <div class="external-event bg-green text-center" style="position: relative;">
                            <small><?php echo app('translator')->getFromJson('restaurant.completed'); ?></small>
                        </div>
                        <div class="external-event bg-red text-center" style="position: relative;">
                            <small><?php echo app('translator')->getFromJson('restaurant.cancelled'); ?></small>
                        </div>
                        <div class="external-event bg-purple text-center" style="position: relative;">
                            <small><i class="fa fa-globe"></i> Online Booking</small>
                        </div>
                        <hr>
                        <small>
                            <p class="help-block">
                                <i><?php echo app('translator')->getFromJson('restaurant.click_on_any_booking_to_view_or_change_status'); ?><br><br>
                                    <?php echo app('translator')->getFromJson('restaurant.double_click_on_any_day_to_add_new_booking'); ?><br><br>
                                    <strong>Purple events</strong> are online bookings that can be converted to regular bookings.
                                </i>
                            </p>
                        </small>
                    </div>
                </div>
            </div>
        </div>

        <?php echo $__env->make('restaurant.booking.create', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>

        <!-- Contact Modal -->
        <div class="modal fade contact_modal" tabindex="-1" role="dialog" aria-labelledby="gridSystemModalLabel">
            <?php echo $__env->make('contact.create', ['quick_add' => true], \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
        </div>

        <!-- Guest Details Modal -->
        <div class="modal fade" id="view_guest_modal" tabindex="-1" role="dialog">
            <div class="modal-dialog modal-lg" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                        <h4 class="modal-title">
                            <i class="fa fa-user"></i> Guest Details
                        </h4>
                    </div>
                    <div class="modal-body" id="guest_details_content">
                        <!-- Guest details will be loaded here -->
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Booking Details Modal -->
        <div class="modal fade view_modal" tabindex="-1" role="dialog">
            <div class="modal-dialog modal-lg" role="document">
                <div class="modal-content">
                    <!-- Booking details will be loaded here -->
                </div>
            </div>
        </div>
    </section>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('javascript'); ?>
    <script type="text/javascript">
        $(document).ready(function() {
            var clickCount = 0;
            var todays_bookings_table, guest_checkins_table;

            // Initialize Today's Bookings Table
            try {
                todays_bookings_table = $('#todays_bookings_table').DataTable({
                    processing: true,
                    serverSide: true,
                    ordering: false,
                    searching: true,
                    pageLength: 10,
                    scrollX: true,
                    dom: 'Bfrtip',
                    buttons: [
                        {
                            extend: 'excel',
                            text: '<i class="fa fa-file-excel-o"></i> Export Excel',
                            className: 'btn btn-success btn-sm'
                        },
                        {
                            extend: 'pdf',
                            text: '<i class="fa fa-file-pdf-o"></i> Export PDF',
                            className: 'btn btn-danger btn-sm'
                        }
                    ],
                    ajax: {
                        url: "/bookings/get-todays-bookings",
                        type: "GET",
                        data: function(d) {
                            d.location_id = $('#business_location_id').val();
                        },
                        error: function(xhr, status, error) {
                            console.error('Today\'s Bookings AJAX Error:', {
                                status: status,
                                error: error,
                                response: xhr.responseText,
                                xhr: xhr
                            });
                            
                            let errorMsg = 'Failed to load today\'s bookings';
                            if (xhr.status === 403) {
                                errorMsg = 'Permission denied. Check user permissions.';
                            } else if (xhr.status === 404) {
                                errorMsg = 'Endpoint not found. Check routes.';
                            } else if (xhr.status === 500) {
                                errorMsg = 'Server error. Check Laravel logs.';
                            }
                            
                            toastr.error(errorMsg);
                        }
                    },
                    columns: [
                        { data: 'customer', width: '12%' },
                        { data: 'contact_info', width: '15%' },
                        { data: 'guest_info', width: '15%' },
                        { data: 'room_details', width: '12%' },
                        {
                            data: null,
                            render: function(data, type, row) {
                                return '<strong>In:</strong> ' + row.booking_start + '<br><strong>Out:</strong> ' + row.booking_end;
                            },
                            width: '15%'
                        },
                        { data: 'table', width: '8%' },
                        { data: 'location', width: '8%' },
                        { data: 'waiter', width: '8%' },
                        { data: 'price', width: '8%' },
                        { data: 'status', width: '7%' },
                        { data: 'action', orderable: false, searchable: false, width: '5%' }
                    ],
                    language: {
                        emptyTable: "No bookings found for today",
                        loadingRecords: "Loading bookings...",
                        processing: "Processing...",
                        zeroRecords: "No matching bookings found"
                    }
                });

                console.log('Today\'s Bookings Table initialized successfully');

            } catch (e) {
                console.error('Today\'s Bookings Table initialization failed:', e);
                toastr.error('Today\'s bookings table failed to load. Check console for details.');
            }

            // Initialize Guest Check-ins Table
            try {
                guest_checkins_table = $('#guest_checkins_table').DataTable({
                    processing: true,
                    serverSide: true,
                    ordering: false,
                    searching: true,
                    pageLength: 10,
                    scrollX: true,
                    dom: 'Bfrtip',
                    buttons: [
                        {
                            extend: 'excel',
                            text: '<i class="fa fa-file-excel-o"></i> Export Excel',
                            className: 'btn btn-success btn-sm'
                        }
                    ],
                    ajax: {
                        url: "/bookings/guest-checkins",
                        type: "GET",
                        data: function(d) {
                            d.location_id = $('#business_location_id').val();
                        },
                        error: function(xhr, status, error) {
                            console.error('Guest Check-ins AJAX Error:', {
                                status: status,
                                error: error,
                                response: xhr.responseText,
                                xhr: xhr
                            });
                            
                            let errorMsg = 'Failed to load guest check-ins';
                            if (xhr.status === 403) {
                                errorMsg = 'Permission denied. Check user permissions.';
                            } else if (xhr.status === 404) {
                                errorMsg = 'Endpoint not found. Check routes.';
                            } else if (xhr.status === 500) {
                                errorMsg = 'Server error. Check Laravel logs.';
                            }
                            
                            toastr.error(errorMsg);
                        }
                    },
                    columns: [
                        { data: 'full_name' },
                        { data: 'email' },
                        { data: 'phone' },
                        { data: 'gender' },
                        { data: 'nationality' },
                        { data: 'stay_purpose' },
                        { data: 'payment_method' },
                        { data: 'staff_acknowledged' },
                        { data: 'guest_acknowledged' },
                        { data: 'booking_status' },
                        { data: 'created_at' },
                        { data: 'action', orderable: false, searchable: false }
                    ],
                    language: {
                        emptyTable: "No guest check-ins found",
                        loadingRecords: "Loading guest check-ins...",
                        processing: "Processing...",
                        zeroRecords: "No matching guest check-ins found"
                    }
                });

                console.log('Guest Check-ins Table initialized successfully');

            } catch (e) {
                console.error('Guest Check-ins Table initialization failed:', e);
                toastr.error('Guest check-ins table failed to load. Check console for details.');
            }

            // Initialize FullCalendar
            try {
                $('#calendar').fullCalendar({
                    header: {
                        left: 'prev,next today',
                        center: 'title',
                        right: 'month,agendaWeek,agendaDay,listWeek'
                    },
                    eventLimit: 3,
                    events: {
                        url: '/bookings-calendar',
                        data: function() {
                            return {
                                location_id: $('#business_location_id').val()
                            };
                        },
                        error: function(xhr, status, error) {
                            console.error('Calendar AJAX Error:', {
                                status: status,
                                error: error,
                                response: xhr.responseText
                            });
                            toastr.error('Failed to load calendar events. Check console.');
                        }
                    },
                    eventRender: function(event, element) {
                        var title_html = event.customer_name || 'Unknown';

                        if (event.room_number) {
                            title_html += '<br>' + event.room_number;
                        }

                        if (event.booking_type === 'online') {
                            title_html += '<br><small><i class="fa fa-globe"></i> Online</small>';
                        } else {
                            title_html += '<br><small><i class="fa fa-user"></i> Front Desk</small>';
                        }

                        if (event.price) {
                            title_html += '<br><small>' + event.price + '</small>';
                        }

                        element.find('.fc-title').html(title_html);

                        if (event.booking_type === 'online') {
                            element.attr('data-booking-type', 'online');
                            element.attr('data-online-id', event.id.replace('online_', ''));
                            element.addClass('online-booking-event');
                            element.attr('title', 'Online Booking - Click to convert or view details');
                        } else {
                            element.attr('data-href', event.url);
                            element.attr('data-container', '.view_modal');
                            element.addClass('btn-modal');
                        }
                    },
                    eventClick: function(event, jsEvent, view) {
                        if (event.booking_type === 'online') {
                            showOnlineBookingDetails(event);
                        }
                    },
                    dayClick: function(date, jsEvent, view) {
                        clickCount++;
                        if (clickCount == 2) {
                            $('#add_booking_modal').modal('show');
                            if (typeof $('form#add_booking_form #start_time').data("DateTimePicker") !== 'undefined') {
                                $('form#add_booking_form #start_time').data("DateTimePicker").date(date).ignoreReadonly(true);
                                $('form#add_booking_form #end_time').data("DateTimePicker").date(date).ignoreReadonly(true);
                            }
                        }
                        var clickTimer = setInterval(function() {
                            clickCount = 0;
                            clearInterval(clickTimer);
                        }, 500);
                    }
                });

                console.log('Calendar initialized successfully');

            } catch (e) {
                console.error('FullCalendar initialization failed:', e);
                toastr.error('Calendar failed to load. Check console for details.');
            }

            // View Guest Details
            $(document).on('click', '.view-guest-details', function() {
                var guestId = $(this).data('id');

                $.ajax({
                    method: "GET",
                    url: '/bookings/guest-checkins/' + guestId,
                    dataType: "json",
                    success: function(data) {
                        var html = `
                        <div class="row">
                            <div class="col-md-6">
                                <div class="panel panel-primary">
                                    <div class="panel-heading">
                                        <h4 class="panel-title"><i class="fa fa-user"></i> Personal Information</h4>
                                    </div>
                                    <div class="panel-body">
                                        <table class="table table-condensed">
                                            <tr><td><strong>Full Name:</strong></td><td>${data.surname} ${data.name}</td></tr>
                                            <tr><td><strong>Email:</strong></td><td>${data.email || 'N/A'}</td></tr>
                                            <tr><td><strong>Phone:</strong></td><td>${data.phone}</td></tr>
                                            <tr><td><strong>Gender:</strong></td><td>${data.gender}</td></tr>
                                            <tr><td><strong>Nationality:</strong></td><td>${data.nationality}</td></tr>
                                        </table>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="panel panel-info">
                                    <div class="panel-heading">
                                        <h4 class="panel-title"><i class="fa fa-id-card"></i> Identification</h4>
                                    </div>
                                    <div class="panel-body">
                                        <table class="table table-condensed">
                                            <tr><td><strong>ID Type:</strong></td><td>${data.id_type || 'N/A'}</td></tr>
                                            <tr><td><strong>ID Number:</strong></td><td>${data.id_number || 'N/A'}</td></tr>
                                            <tr><td><strong>Passport No:</strong></td><td>${data.passport_no || 'N/A'}</td></tr>
                                            <tr><td><strong>Company:</strong></td><td>${data.company || 'N/A'}</td></tr>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="panel panel-success">
                                    <div class="panel-heading">
                                        <h4 class="panel-title"><i class="fa fa-suitcase"></i> Stay Details</h4>
                                    </div>
                                    <div class="panel-body">
                                        <table class="table table-condensed">
                                            <tr><td><strong>Purpose:</strong></td><td>${data.stay_purpose}</td></tr>
                                            <tr><td><strong>Payment Method:</strong></td><td>${data.payment_method}</td></tr>
                                            <tr><td><strong>Check-in Time:</strong></td><td>${data.created_at}</td></tr>
                                        </table>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="panel panel-warning">
                                    <div class="panel-heading">
                                        <h4 class="panel-title"><i class="fa fa-check-circle"></i> Acknowledgments</h4>
                                    </div>
                                    <div class="panel-body">
                                        <table class="table table-condensed">
                                            <tr>
                                                <td><strong>Staff Acknowledged:</strong></td>
                                                <td>
                                                    ${data.staff_acknowledged ?
                            '<span class="label label-success">Yes</span>' :
                            '<span class="label label-warning">No</span>'}
                                                </td>
                                            </tr>
                                            <tr>
                                                <td><strong>Guest Acknowledged:</strong></td>
                                                <td>
                                                    ${data.guest_acknowledged ?
                            '<span class="label label-success">Yes</span>' :
                            '<span class="label label-warning">No</span>'}
                                                </td>
                                            </tr>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                        ${data.remarks ? `
                        <div class="row">
                            <div class="col-md-12">
                                <div class="panel panel-default">
                                    <div class="panel-heading">
                                        <h4 class="panel-title"><i class="fa fa-comments"></i> Remarks</h4>
                                    </div>
                                    <div class="panel-body">
                                        <p>${data.remarks}</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        ` : ''}`;

                        $('#guest_details_content').html(html);
                        $('#view_guest_modal').modal('show');
                    },
                    error: function(xhr) {
                        console.error('Failed to load guest details:', xhr.responseText);
                        toastr.error('Failed to load guest details. Check console for details.');
                    }
                });
            });

            // Location Change - Refresh All Tables
            $(document).on('change', 'select#business_location_id', function() {
                if (typeof $('#calendar').fullCalendar === 'function') {
                    $('#calendar').fullCalendar('refetchEvents');
                }
                if (todays_bookings_table) {
                    todays_bookings_table.ajax.reload();
                }
                if (guest_checkins_table) {
                    guest_checkins_table.ajax.reload();
                }
            });

            // Add New Booking Button
            $('button#add_new_booking_btn').click(function() {
                $('div#add_booking_modal').modal('show');
            });

            // Helper Functions
            function showOnlineBookingDetails(event) {
                var onlineId = event.id.replace('online_', '');

                var html = `
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                            <h4 class="modal-title">
                                <i class="fa fa-globe"></i> Online Booking Details
                            </h4>
                        </div>
                        <div class="modal-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <h5><strong>Guest Information</strong></h5>
                                    <p><strong>Name:</strong> ${event.customer_name}</p>
                                    <p><strong>Email:</strong> ${event.email || 'N/A'}</p>
                                    <p><strong>Phone:</strong> ${event.phone || 'N/A'}</p>
                                    <p><strong>Gender:</strong> ${event.gender || 'N/A'}</p>
                                </div>
                                <div class="col-md-6">
                                    <h5><strong>Booking Details</strong></h5>
                                    <p><strong>Check-in:</strong> ${moment(event.start).format('YYYY-MM-DD HH:mm')}</p>
                                    <p><strong>Check-out:</strong> ${moment(event.end).format('YYYY-MM-DD HH:mm')}</p>
                                    <p><strong>Room:</strong> ${event.room_number}</p>
                                    <p><strong>Adults:</strong> ${event.adults || 1}</p>
                                    <p><strong>Rooms:</strong> ${event.rooms || 1}</p>
                                    <p><strong>Nights:</strong> ${event.nights || 'N/A'}</p>
                                    <p><strong>Total Price:</strong> ${event.price || 'N/A'}</p>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        </div>
                    </div>`;

                $('.view_modal').html(html).modal('show');
            }

            // Enhanced datetime pickers (if they exist)
            if (typeof $('form#add_booking_form #start_time').datetimepicker === 'function') {
                $('form#add_booking_form #start_time').datetimepicker({
                    format: moment_date_format + ' ' + moment_time_format,
                    minDate: moment(),
                    ignoreReadonly: true
                });

                $('form#add_booking_form #end_time').datetimepicker({
                    format: moment_date_format + ' ' + moment_time_format,
                    minDate: moment(),
                    ignoreReadonly: true
                });
            }

            // Modal event handlers
            $('.view_modal').on('shown.bs.modal', function(e) {
                if (typeof $('form#edit_booking_form').validate === 'function') {
                    $('form#edit_booking_form').validate({
                        submitHandler: function(form) {
                            var data = $(form).serialize();
                            $.ajax({
                                method: "PUT",
                                url: $(form).attr("action"),
                                dataType: "json",
                                data: data,
                                beforeSend: function(xhr) {
                                    $(form).find('button[type="submit"]').attr('disabled', true);
                                },
                                success: function(result) {
                                    if (result.success) {
                                        $('div.view_modal').modal('hide');
                                        toastr.success(result.msg);
                                        if (typeof $('#calendar').fullCalendar === 'function') {
                                            $('#calendar').fullCalendar('refetchEvents');
                                        }
                                        if (todays_bookings_table) {
                                            todays_bookings_table.ajax.reload();
                                        }
                                        if (guest_checkins_table) {
                                            guest_checkins_table.ajax.reload();
                                        }
                                    } else {
                                        toastr.error(result.msg);
                                    }
                                    $(form).find('button[type="submit"]').removeAttr('disabled');
                                },
                                error: function(xhr) {
                                    toastr.error('An error occurred. Check console.');
                                    console.error(xhr.responseText);
                                    $(form).find('button[type="submit"]').removeAttr('disabled');
                                }
                            });
                        }
                    });
                }
            });

            // Delete Booking
            $(document).on('click', 'button#delete_booking', function() {
                if (typeof swal === 'function') {
                    swal({
                        title: LANG.sure || 'Are you sure?',
                        icon: "warning",
                        buttons: true,
                        dangerMode: true
                    }).then((willDelete) => {
                        if (willDelete) {
                            var href = $(this).data('href');
                            $.ajax({
                                method: "DELETE",
                                url: href,
                                dataType: "json",
                                success: function(result) {
                                    if (result.success) {
                                        $('div.view_modal').modal('hide');
                                        toastr.success(result.msg);
                                        if (typeof $('#calendar').fullCalendar === 'function') {
                                            $('#calendar').fullCalendar('refetchEvents');
                                        }
                                        if (todays_bookings_table) {
                                            todays_bookings_table.ajax.reload();
                                        }
                                        if (guest_checkins_table) {
                                            guest_checkins_table.ajax.reload();
                                        }
                                    } else {
                                        toastr.error(result.msg);
                                    }
                                },
                                error: function(xhr) {
                                    toastr.error('An error occurred. Check console.');
                                    console.error(xhr.responseText);
                                }
                            });
                        }
                    });
                } else {
                    if (confirm('Are you sure you want to delete this booking?')) {
                        var href = $(this).data('href');
                        $.ajax({
                            method: "DELETE",
                            url: href,
                            dataType: "json",
                            success: function(result) {
                                if (result.success) {
                                    $('div.view_modal').modal('hide');
                                    toastr.success(result.msg);
                                    if (typeof $('#calendar').fullCalendar === 'function') {
                                        $('#calendar').fullCalendar('refetchEvents');
                                    }
                                    if (todays_bookings_table) {
                                        todays_bookings_table.ajax.reload();
                                    }
                                    if (guest_checkins_table) {
                                        guest_checkins_table.ajax.reload();
                                    }
                                } else {
                                    toastr.error(result.msg);
                                }
                            },
                            error: function(xhr) {
                                toastr.error('An error occurred. Check console.');
                                console.error(xhr.responseText);
                            }
                        });
                    }
                }
            });

            // Quick Add Contact for traditional bookings
            $(document).on('click', '.add_new_customer', function() {
                $('.contact_modal').find('select#contact_type').val('customer').closest('div.contact_type_div').addClass('hide');
                $('.contact_modal').modal('show');
            });

            // Contact form validation (if exists)
            if (typeof $('form#quick_add_contact').validate === 'function') {
                $('form#quick_add_contact').submit(function(e) {
                    e.preventDefault();
                }).validate({
                    rules: {
                        contact_id: {
                            remote: {
                                url: '/contacts/check-contacts-id',
                                type: 'post',
                                data: {
                                    contact_id: function() {
                                        return $('#contact_id').val();
                                    },
                                    hidden_id: function() {
                                        return $('#hidden_id').length ? $('#hidden_id').val() : '';
                                    }
                                }
                            }
                        }
                    },
                    messages: {
                        contact_id: {
                            remote: LANG.contact_id_already_exists || 'Contact ID already exists'
                        }
                    },
                    submitHandler: function(form) {
                        var data = $(form).serialize();
                        $.ajax({
                            method: 'POST',
                            url: $(form).attr('action'),
                            dataType: 'json',
                            data: data,
                            beforeSend: function(xhr) {
                                $(form).find('button[type="submit"]').attr('disabled', true);
                            },
                            success: function(result) {
                                if (result.success) {
                                    $('select#booking_customer_id').append(
                                        $('<option>', { value: result.data.id, text: result.data.name })
                                    );
                                    $('select#booking_customer_id').val(result.data.id).trigger('change');
                                    $('div.contact_modal').modal('hide');
                                    toastr.success(result.msg);
                                } else {
                                    toastr.error(result.msg);
                                }
                                $(form).find('button[type="submit"]').removeAttr('disabled');
                            },
                            error: function(xhr) {
                                toastr.error('An error occurred. Check console.');
                                console.error(xhr.responseText);
                                $(form).find('button[type="submit"]').removeAttr('disabled');
                            }
                        });
                    }
                });
            }

            $('.contact_modal').on('hidden.bs.modal', function() {
                if ($('form#quick_add_contact').length) {
                    $('form#quick_add_contact').find('button[type="submit"]').removeAttr('disabled');
                    $('form#quick_add_contact')[0].reset();
                }
            });

            // Test endpoints button (for debugging - remove in production)
            if (window.location.hostname === 'localhost' || window.location.hostname.includes('dev')) {
                $('<button class="btn btn-warning btn-sm" style="position: fixed; top: 10px; right: 10px; z-index: 9999;">Test Endpoints</button>')
                    .appendTo('body')
                    .click(function() {
                        console.log('Testing endpoints...');
                        
                        // Test today's bookings endpoint
                        $.get('/bookings/get-todays-bookings')
                            .done(function(data) {
                                console.log('✅ Today\'s bookings endpoint working:', data);
                            })
                            .fail(function(xhr) {
                                console.error('❌ Today\'s bookings endpoint failed:', xhr.status, xhr.responseText);
                            });

                        // Test guest checkins endpoint
                        $.get('/bookings/guest-checkins')
                            .done(function(data) {
                                console.log('✅ Guest checkins endpoint working:', data);
                            })
                            .fail(function(xhr) {
                                console.error('❌ Guest checkins endpoint failed:', xhr.status, xhr.responseText);
                            });
                    });
            }

            console.log('Booking management page initialized successfully');
        });


        $('#guest_checkins_table').DataTable({
        processing: true,
        serverSide: true,
        ajax: '<?php echo e(route('bookings.get_guest_checkins'), false); ?>',
        columns: [
            { data: 'name', name: 'name' },
            { data: 'email', name: 'email' },
            { data: 'phone_number', name: 'phone_number' },
            { data: 'gender', name: 'gender' },
            { data: 'room_slug', name: 'room_slug' },
            { data: 'check_in', name: 'check_in' },
            { data: 'check_out', name: 'check_out' },
            { data: 'number_of_days', name: 'number_of_days' },
            { data: 'adults', name: 'adults' },
            { data: 'rooms', name: 'rooms' },
            {
                data: 'is_double_occupancy',
                render: function (data) {
                    return data ? 'Double' : 'Single';
                }
            },
            {
                data: 'price_per_room',
                render: $.fn.dataTable.render.number(',', '.', 2, 'KES ')
            },
            {
                data: 'total_price',
                render: $.fn.dataTable.render.number(',', '.', 2, 'KES ')
            },
            { data: 'created_at', name: 'created_at' },
            {
                data: 'id',
                orderable: false,
                searchable: false,
                render: function (data) {
                    return `<a href="/bookings/guest-checkins/${data}" class="btn btn-xs btn-info">View</a>`;
                }
            }
        ]
    });





    </script>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH D:\laragon\www\coffeegardensuite\resources\views/restaurant/booking/index.blade.php ENDPATH**/ ?>