 <?php echo $this->extend('template/admin/main') ?>

 <?php echo $this->section('css') ?>
    <link rel="stylesheet" href="<?php echo base_url('public/css/customestyle.css'); ?>" type="text/css">
 <?php echo $this->endSection() ?>

 <?php echo $this->section('content') ?>

    <?php echo $this->include('common/message') ?>

    <div class="card mb-4">
        <div class="card-body">
                <div class="text-end">
                    <a class="btn btn-success" href="<?php echo base_url(route_to('pre-trip')) ?>">
                        <i class="fas fa-suitcase"></i> <sup><i class="fas fa-plus small"></i></sup>
                        <?php echo lang("add_pretrip") ?>
                    </a>
                </div>

            <div class="table-responsive">
                <table class="table display table-bordered table-striped table-hover basic test" id="ticketbookinglist"  style="width: 100%; table-layout: auto; border-collapse: collapse;">
                    <thead>
                        <tr>
                            <th scope="col">#</th>
                            <th scope="col"><?php echo lang("Localize.company") ?> </th>
                            <th scope="col"><?php echo "pre-trip no" ?> </th>
                            <th scope="col"><?php echo "Bus plate no" ?> </th>
                            <th scope="col"><?php echo "Bus no" ?> </th>
                            <th scope="col"><?php echo "Bus start meter" ?></th>
                            <th scope="col"><?php echo lang("Localize.trip") ?> </th>
                            <th scope="col"><?php echo lang("Localize.pick_up") ?> </th>
                            <th scope="col"><?php echo lang("Localize.drop") ?> </th>
                            <th scope="col"><?php echo "Trip".lang("Localize.date") ?></th>
                            <th scope="col"><?php echo lang("Localize.time") ?></th>
                            <th scope="col"><?php echo lang("Localize.driver") ?></th>
                            <th scope="col"><?php echo lang("assistace") ?> </th>
                            <th scope="col"><?php echo "Bus Plate" ?> <?php echo lang("Localize.number") ?> </th>
                            <th scope="col"><?php echo lang("Localize.create_by") ?></th>
                            <th scope="col"><?php echo lang("Localize.seat") ?></th>
                            <th scope="col"><?php echo lang("Localize.note") ?></th>
                            <th scope="col"><?php echo "Created".lang("Localize.date") ?></th>
                            <th scope="col"><?php echo lang("Localize.action") ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Data will be loaded via AJAX -->
                    </tbody>
                </table>
            </div>

        </div>
    </div>
    <?php echo $this->include('common/datatable_default_lang_change') ?>
    <?php echo $this->include('common/confirmation-modal') ?>
    
    <!-- CSRF Token for AJAX -->
    <input type="hidden" name="<?php echo csrf_token(); ?>" id="csrf_token" value="<?php echo csrf_hash(); ?>">
    
 <?php echo $this->endSection() ?>

 <?php echo $this->section('js') ?>
 <script>
     $(document).ready(function() {
         // Check if DataTable is loaded
         if (typeof $.fn.DataTable === 'undefined') {
             console.error('DataTables is not loaded. Please check if datatables.min.js is included.');
             return;
         }
         
         // Get company name from hidden input or use default
         var companyname = $("#logotext").val() || "<?php echo lang('Localize.pretrip_list') ?? 'Pre Trip List'; ?>";
         
         // Check if table exists
         if ($('#ticketbookinglist').length === 0) {
             console.error("Table #ticketbookinglist not found!");
             return;
         }
         
         // Destroy existing DataTable instance if it exists (from mydatatable.js client-side init)
         if ($.fn.DataTable.isDataTable('#ticketbookinglist')) {
             $('#ticketbookinglist').DataTable().destroy();
             console.log("Destroyed existing client-side DataTable instance for #ticketbookinglist");
         }
         
         console.log("Initializing server-side DataTable for #ticketbookinglist");
         console.log("Number of header columns:", $('#ticketbookinglist thead th').length);

         var table = $('#ticketbookinglist').DataTable({
             processing: true,
             serverSide: true,
             order: [[17, 'desc']],
             lengthMenu: [[10, 15, 20, 25, 30, 40, 50, -1], [10, 15, 20, 25, 30, 40, 50, "All"]],
             pageLength: 10,
             dom: 'lBfrtip',
             language: {
                 search: search,
                 lengthMenu: lengthMenu,
                 zeroRecords: zeroRecords,
                 info: info,
                 infoEmpty: infoEmpty,
                 infoFiltered: infoFiltered,
                 paginate: {
                     first: first,
                     previous: previous,
                     next: next,
                     last: last
                 }
             },
             ajax: {
                 url: "<?= base_url(route_to('server-list-pretrip')); ?>",
                 type: "POST",
                 data: function(d) {
                     // Add CSRF token to the request data
                     var csrfToken = $('#csrf_token').val() || $('input[name="<?php echo csrf_token(); ?>"]').val();
                     if (csrfToken) {
                         d.<?php echo csrf_token(); ?> = csrfToken;
                     }
                     return d;
                 },
                 beforeSend: function(xhr) {
                     // Set CSRF token in header
                     var csrfToken = $('#csrf_token').val() || $('input[name="<?php echo csrf_token(); ?>"]').val();
                     if (csrfToken) {
                         xhr.setRequestHeader('X-CSRF-TOKEN', csrfToken);
                         xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
                     }
                 },
                 dataSrc: 'data',
                 error: function(xhr, error, code) {
                     console.error("DataTables AJAX Error:", error, code);
                     console.error("Response:", xhr.responseText);
                     if (xhr.status === 403) {
                         alert("CSRF token validation failed. Please refresh the page and try again.");
                     }
                 }
             },
             buttons: [
                 {
                     extend: 'copy',
                     title: companyname,
                     messageTop: companyname,
                     exportOptions: {columns: [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]}
                 },
                 {
                     extend: 'csv',
                     title: companyname,
                     messageTop: companyname,
                     exportOptions: {columns: [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]}
                 },
                 {
                     extend: 'excel',
                     title: companyname,
                     messageTop: companyname,
                     exportOptions: {columns: [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]}
                 },
                 {
                     extend: 'pdf',
                     title: companyname,
                     messageTop: companyname,
                     exportOptions: {columns: [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]}
                 },
                 {
                     extend: 'print',
                     title: companyname,
                     messageTop: companyname,
                     exportOptions: {columns: [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]}
                 }
             ],
             columns: [
                 { data: "index", orderable: false },
                 { data: "company" },
                 { data: "pretrip_id" },
                 { data: "reg_no" },
                 { data: "bus_plate_no" },
                 { data: "bus_meter" },
                 { data: "trip_id" },
                 { data: "pic_location_name" },
                 { data: "drop_location_name" },
                 { data: "trip_date" },
                 { data: "schedule_time" },
                 { data: "driverName" },
                 { data: "assistanceName" },
                 { data: "bus_plate_number" },
                 { data: "createdBy" },
                 { data: "Number_of_Seats" },
                 { data: "notes" },
                 { data: "updatedAt" },
                 { data: "action", orderable: false, searchable: false }
             ],
             responsive: true,
             initComplete: function () {
                 var api = this.api();
                 console.log("DataTables initialized. Columns:", api.columns().count());
             },
             drawCallback: function(settings) {
                 console.log("DataTables draw callback fired");
             }
         });
     });
 </script>
 <?php echo $this->endSection() ?>