<?php
$sessiondata = \Config\Services::session(); // Needed for Point 5

if ($sessiondata->has('grandtotal')) {
    $singleTripTotal  = $sessiondata->grandtotal;
    $rouondTripTotal = (float) $singleTripTotal + (float) $grandtotal;
}

$isrountripPost  = $sessiondata->has('isrountrip') ? $sessiondata->isrountrip : 0;
?>

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

<?php echo $this->section('css') ?>
    <link rel="stylesheet" href="<?php echo base_url('public/css/datepicker.css'); ?>" type="text/css">
    <link href="<?php echo base_url('public/plugins/select2/select2.min.css'); ?>" rel="stylesheet" />
    <link rel="stylesheet" href="<?php echo base_url('public/css/sumoselect.min.css'); ?>" type="text/css">
    <link rel="stylesheet" href="<?php echo base_url('public/css/customestyle.css'); ?>" type="text/css">
    <!-- Include Flatpickr CSS & JS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <style>
        /* Fix SubTrip Location dropdown only */
        /* Force SubTrip dropdown to expand left instead of right */
        .SumoSelect .optWrapper {
            min-width: 400px !important;  /* widen dropdown */
            white-space: nowrap;
        }
        /*.SumoSelect .optWrapper {
            left: auto !important;
            right: 0 !important;
            min-width: 400px !important;
            white-space: nowrap;
        }*/
        .SumoSelect .options li label {
            white-space: nowrap;
        }
    </style>
<?php echo $this->endSection() ?>

<?php echo $this->section('content') ?>
<?php if (session()->getFlashdata('error')) : ?>
    <div class="alert alert-danger"><?= esc(session()->getFlashdata('error')) ?></div>
<?php endif ?>
<?php if (session()->getFlashdata('success')) : ?>
    <div class="alert alert-success"><?= esc(session()->getFlashdata('success')) ?></div>
<?php endif ?>
<div class="card mb-4">
    <div class="card-body">
        <form action="<?php echo base_url(route_to('holdseat')) ?>" method="post" id="createbooking" accept-charset="utf-8" enctype="multipart/form-data">
            <?php echo $this->include('common/security') ?>

            <input type="hidden" name="baseurl" id="baseurl" value="<?php echo base_url(); ?>">

            <input type="hidden" name="total_seat" id="total_seat"/>
            <input type="hidden" name="layout" id="layout"/>
            <input type="hidden" name="seat_number" id="seat_number"/>
            <input type="hidden" name="forth_seat" id="forth_seat"/>
            <input type="hidden" name="last_seat" id="last_seat"/>
            <input type="hidden" name="wc" id="wc"/>
            <div class="row">
                <div class="booking-payments mb-4 col-md-6">
                    <div class="row">

                        <div class="col-12 col-md-6 col-lg-4 form-group">
                            <label for="trip"><?php echo lang("Localize.company") ?> <abbr class="required" title="Required field">*</abbr></label>
                            <select class="form-select" name="company_id" id="trip_company_id"  required>
                                <option>select Company</option>
                                <?php foreach($companies as $company)
                                { ?>
                                    <option value="<?php echo $company->id ?>"><?php echo $company->name; ?></option>
                                <?php } ?>
                            </select>
                        </div>

                        <div class="col-12 col-md-6 col-lg-4 form-group">
                            <label for="trip"><?php echo lang("Trip Location") ?> <abbr class="required" title="Required field">*</abbr></label>
                            <select class="form-select w-100" name="tripid" id="tripid" required>
                                <option>select trip</option>
                                <!-- 
                                <?php foreach($trip as $trip) { ?>
                                    <option value="<?php echo $trip->tripid ?>">
                                        <?php echo $trip->start_time . "- " . $trip->pic_location_name . " - " . $trip->drop_location_name . " ( ". $trip->tripid . " ) "?>
                                    </option>
                                <?php } ?> 
                                -->
                                <option>city</option>
                            </select>
                        </div>

                                                 <div class="col-12 col-md-6 col-lg-4 form-group">
                             <label for="subtrip"><?php echo lang("SubTrip Location") ?> <abbr class="required" title="Required field">*</abbr></label>
                             <select class="form-select w-100" name="subtripid[]" id="subtripid" multiple>
                                 <option value="">Select SubTrip</option>
                             </select>
                         </div>

                        <div class="col-12 col-md-6 col-lg-4 mt-2">
                            <label for="journeydate" class="form-label"> <?php echo lang("Localize.journey").lang("Localize.start").lang("Localize.date") ?>  <abbr title="Required field">*</abbr></label>
                            <div class="input-group">
                                <input type="text" class="form-control" name="journeydate" id="journeydate" required />
                                <div class="input-group-addon"></div>
                            </div>
                        </div>
                        <div class="col-12 col-md-6 col-lg-4 mt-2">
                            <label for="journeydateend" class="form-label"> <?php echo lang("Localize.journey").lang("Localize.end").lang("Localize.date") ?>  <abbr title="Required field">*</abbr></label>
                            <div class="input-group">
                                <input type="text" class="form-control" name="journeydateend" id="journeydateend" required />
                                <div class="input-group-addon"></div>
                            </div>
                        </div>
                        <div class="col-12 col-md-6 col-lg-4 mt-2">
                            <label for="booked" class="form-label"><?php echo lang("Localize.booked_seat") ?> </label>
                            <div>
                                <p id="booked_seat"></p>
                            </div>
                        </div>
                        <div class="col-12 col-md-6 col-lg-4 mt-2">
                            <label for="startdate" class="form-label"> <?php echo lang("Localize.start") ?> <?php echo lang("Localize.date") ?>  <abbr title="Required field">*</abbr></label>
                            <div class="input-group">
                                <input type="text" class="form-control" name="startdate" id="startdate" required />
                                <div class="input-group-addon"></div>
                            </div>
                        </div>
                            <!--repeted end date-->
                        <div class="col-12 col-md-6 col-lg-4 mt-2">
                            <label for="enddate" class="form-label"> <?php echo lang("Localize.end") ?> <?php echo lang("Localize.date") ?>  <abbr title="Required field">*</abbr></label>
                            <div class="input-group">
                                <input type="text" class="form-control"  name="enddate" id="enddate" required />
                                <div class="input-group-addon"></div>
                            </div>
                        </div>
                        <div class="col-12 col-md-6 col-lg-4 mt-2">
                            <label for="blocked" class="form-label"><?php echo lang("Localize.blocked_seat") ?> </label>
                            <div>
                                <p id="blocked_seat"></p>
                            </div>
                        </div>
                        <div class="col-12 col-md-6 col-lg-4 form-group">
                            <label for="seat_to_block"><?php echo lang("Localize.seat_to_block") ?> <abbr class="required" title="Required field">*</abbr></label>
                            <select class="form-select" name="seatblock[]" id="seatblock" multiple>
                            </select>
                        </div>

                        <!-- <div class="col-12 col-md-6 col-lg-4 form-group">
                            <label for="seat_to_unblock"><?php // echo lang("Localize.seat_unblock") ?> <abbr class="required" title="Required field">*</abbr></label>
                            <select class="form-select" name="seatunblock[]" id="seatunblock" multiple>
                            </select>
                        </div> -->
                        <div class="col-12 form-group">
                            <label for="notes"><?php echo lang("note") ?> <abbr class="required" title="Required field">*</abbr></label>
                            <textarea class="form-control" name="notes" id="notes" rows="3"></textarea>
                        </div>

                    </div>
                </div>
                <div class="col-md-6">
                    <div id="seatLayoutContainer" class="mt-4"></div>
                </div>
            </div>


            <!--<div class="text-danger">-->
            <!--    <?php if (isset($validation)) : ?>-->
            <!--        <?= $validation->listErrors(); ?>-->
            <!--    <?php endif ?>-->
            <!--</div>-->
            <div class="row">
                <div class="col-12 text-center">
                    <button type="submit" class="btn btn-success" id="submit-booking"><?php echo lang("Localize.submit") ?></button>
                    <button type="button" class="btn btn-success" id="layoutButton"><?php echo "seatLayout"; ?></button>
                    <button type="button" class="btn btn-success" id="sync" onclick="callDateAjax()"><?php echo "Sync"; ?></button>
                </div>
            </div>
        </form>
    </div>
</div>

<?php echo $this->endSection() ?>

<?php echo $this->section('js') ?>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<!-- <script src="<?php // echo base_url('js/booking.js'); ?>"></script> -->
<script src="<?php echo base_url('public/js/ajax.js'); ?>"></script>
<script src="<?php echo base_url('public/js/bootstrap-datepicker.js'); ?>"></script>
<script src="<?php echo base_url('public/js/bus365datapick.js'); ?>"></script>
<script src="<?php echo base_url('public/js/ajax.js'); ?>"></script>
<script src="<?php echo base_url('public/js/dynamicinput.js'); ?>"></script>
<script src="<?php echo base_url('public/plugins/select2/select2.min.js'); ?>"></script>
<script src="<?php echo base_url('public/js/jquery.sumoselect.min.js'); ?>"></script>
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

<script>
$(document).ready(function () {
    $('#trip_company_id').on('change', function () {
        var companyId = $(this).val();
        var baseurl = "<?php echo base_url(); ?>";

        if (companyId > 0) {
            $.ajax({
                url: baseurl + "/modules/backend/tickets/get-trips-by-company/" + companyId,
                type: "GET",
                dataType: "json",
                success: function (response) {
                    var tripSelect = $('#tripid');
                    tripSelect.empty();
                    tripSelect.append('<option value="">Select Trip</option>');

                    if (response.length > 0) {
                        $.each(response, function (index, trip) {
                            tripSelect.append(
                                '<option value="' + trip.tripid + '">' +
                                trip.start_time + " - " + trip.pic_location_name + " - " + trip.drop_location_name + " (" + trip.tripid + ")" +
                                '</option>'
                            );
                        });
                    } else {
                        tripSelect.append('<option value="">No trips available</option>');
                    }
                }
            });
        }
    });
    $('#tripid').on('change', function () {
        var companyId = $('#trip_company_id').val();
        var tripId = $(this).val();
        var baseurl = "<?php echo base_url(); ?>";

        if (tripId > 0) {
            $.ajax({
                url: baseurl + "/modules/backend/holdseat/get-subtrip-details/" + tripId + "/" +companyId,
                type: "GET",
                dataType: "json",
               success: function (response) {
                    console.log(response);
                    var subtripSelect = $('#subtripid');
                    var seatBlockSelect = $('#seatblock');
                    var seatUnBlockSelect = $('#seatunblock');
                    subtripSelect.empty();
                    seatBlockSelect.empty();
                    seatUnBlockSelect.empty();
                    // subtripSelect.append('<option value="">Select SubTrip</option>');
                    seatBlockSelect.append('<option value="">Select Seat Block</option>');
                    seatUnBlockSelect.append('<option value="">Select Seat UnBlock</option>');

                    var seatNumbers = [];
                    var blockedSeats = response.blocked.map(Number); // convert to int
                    var boockedSeats = response.booked_seats.map(Number);
                    console.log(blockedSeats);
                    console.log(boockedSeats);
                    if(response.booked_seats && response.booked_seats.length > 0){
                        $("#booked_seat").html(response.booked_seats.join(','));
                    }
                    if(response.blocked && response.blocked.length > 0){
                        $("#blocked_seat").html(response.blocked.join(','));
                    }

                                         if (response.subtrips && response.subtrips.length > 0) {
                         // Add "Select All" option at the beginning
                         subtripSelect.append('<option value="select_all" class="select-all-option">--- Select All SubTrips ---</option>');
                         
                         $.each(response.subtrips, function (index, subtrip) {
                             $('#total_seat').val(subtrip.total_seat);
                             $('#layout').val(subtrip.layout);
                             $('#seat_number').val(subtrip.seat_number);
                             $('#forth_seat').val(subtrip.forth_seat);
                             $('#last_seat').val(subtrip.last_seat);
                             $('#wc').val(subtrip.wc);

                             subtripSelect.append(
                                 '<option value="' + subtrip.id + '">' +
                                 subtrip.pic_location_name + " - " + subtrip.drop_location_name + " (" + subtrip.id + ")" +
                                 '</option>'
                             );

                             seatNumbers = subtrip.seat_number.split(',').map(Number); // convert to int
                         });

                        seatNumbers.forEach(function (seat) {
                            if (!blockedSeats.includes(seat) && !boockedSeats.includes(seat)) {
                                seatBlockSelect.append('<option value="' + seat + '">' + seat + '</option>');
                            }
                        });

                        blockedSeats.forEach(function (seat) {
                            seatUnBlockSelect.append('<option value="' + seat + '">' + seat + '</option>');
                        });

                                                 // Reload SumoSelects if initialized
                         safeReloadSumoSelect('#seatblock');
                         safeReloadSumoSelect('#subtripid');
                         safeReloadSumoSelect('#seatunblock');

                        $('#layoutButton').click();
                                         } else {
                         subtripSelect.append('<option value="">No trips available</option>');
                         safeReloadSumoSelect('#subtripid');
                     }
                }

            });
        }
    });

    $('#layoutButton').click(function() {
        var totalSeat = $('#total_seat').val();
        var layout = $('#layout').val();
        var seatNumber = $('#seat_number').val();
        var forth_seat = $('#forth_seat').val();
        var last_seat = $('#last_seat').val();
        var wc = $('#wc').val();


        $.ajax({
            url: '<?php echo base_url('modules/backend/fleets/getSeatLayout'); ?>',
            type: 'GET',
            headers: { "X-CSRF-TOKEN": "<?= csrf_hash() ?>" },
            data: {
                totalSeat:totalSeat,
                seatLayout:layout,
                seat_number:seatNumber,
                forth_seat:forth_seat,
                last_seat:last_seat,
                wc:wc,

            },
            success: function(response) {
                $('#seatLayoutContainer').html(response);
            },
            error: function(xhr, status, error) {
                console.error('Error fetching seat layout:', error);
            }
        });
    });
});
var holdBlockMinMinutes = 5;

function parseHoldBlockDate(val) {
    if (!val) {
        return null;
    }
    var normalized = String(val).trim().replace(' ', 'T');
    var d = new Date(normalized);
    return isNaN(d.getTime()) ? null : d;
}

function validateHoldBlockWindow(showAlert) {
    var start = parseHoldBlockDate($('#startdate').val());
    var end = parseHoldBlockDate($('#enddate').val());
    if (!start || !end) {
        return true;
    }
    if (end <= start) {
        if (showAlert) {
            alert('End date must be after start date (Egypt time).');
        }
        return false;
    }
    var diffMin = (end.getTime() - start.getTime()) / 60000;
    if (diffMin < holdBlockMinMinutes) {
        if (showAlert) {
            alert('Hold window must be at least ' + holdBlockMinMinutes + ' minutes. Please set a longer end time.');
        }
        return false;
    }
    return true;
}

function syncSumoSelectToNative(selector) {
    var $el = $(selector);
    if ($el.length === 0) {
        return;
    }
    var values = [];
    if ($el[0].sumo && typeof $el[0].sumo.getValue === 'function') {
        values = $el[0].sumo.getValue() || [];
    } else {
        values = $el.val() || [];
    }
    if (!Array.isArray(values)) {
        values = values ? [values] : [];
    }
    values = values.filter(function (v) {
        return v !== null && String(v).trim() !== '' && String(v) !== 'select_all';
    });
    $el.val(values);
    if ($el[0].sumo && typeof $el[0].sumo.reload === 'function') {
        $el[0].sumo.reload();
    }
}

$('#createbooking').on('submit', function (e) {
    syncSumoSelectToNative('#subtripid');
    syncSumoSelectToNative('#seatblock');

    var startEl = document.querySelector('#startdate');
    var endEl = document.querySelector('#enddate');
    if (startEl && startEl._flatpickr) {
        $('#startdate').val(startEl._flatpickr.input.value);
    }
    if (endEl && endEl._flatpickr) {
        $('#enddate').val(endEl._flatpickr.input.value);
    }

    if (!$('#tripid').val() || parseInt($('#tripid').val(), 10) <= 0) {
        e.preventDefault();
        alert('Please select a trip.');
        return false;
    }
    if (!$('#subtripid').val() || ($('#subtripid').val() || []).length === 0) {
        e.preventDefault();
        alert('Please select at least one subtrip.');
        return false;
    }
    if (!$('#seatblock').val() || ($('#seatblock').val() || []).length === 0) {
        e.preventDefault();
        alert('Please select at least one seat to block.');
        return false;
    }
    if (!validateHoldBlockWindow(true)) {
        e.preventDefault();
        return false;
    }
});

flatpickr("#startdate", {
    enableTime: true,
    dateFormat: "Y-m-d H:i:00",
    altInput: true,
    altFormat: "Y-m-d H:i",
    time_24hr: true,
    allowInput: true
});
flatpickr("#journeydate", {
    dateFormat: "Y-m-d",
    allowInput: true
});
flatpickr("#journeydateend", {
    dateFormat: "Y-m-d",
    allowInput: true
});
flatpickr("#enddate", {
    enableTime: true,
    dateFormat: "Y-m-d H:i:00",
    altInput: true,
    altFormat: "Y-m-d H:i",
    time_24hr: true,
    allowInput: true
});

function fetchTripData(){
    var tripId = $('#tripLocation').val();
}
   // Initialize SumoSelect with proper error handling
  function initializeSumoSelects() {
      try {
          if ($('#seatblock').length > 0) {
              $('#seatblock').SumoSelect({ 
                  okCancelInMulti: true,
                  triggerChangeCombined: true,
                  forceCustomRendering: true  
              });
          }
          
          if ($('#subtripid').length > 0) {
              $('#subtripid').SumoSelect({ 
                  okCancelInMulti: true,
                  triggerChangeCombined: true,
                  forceCustomRendering: true  
              });
          }
          
          if ($('#seatunblock').length > 0) {
              $('#seatunblock').SumoSelect({
                  okCancelInMulti: true,
                  triggerChangeCombined: true,
                  forceCustomRendering: true
              });
          }
      } catch (error) {
          console.log('SumoSelect initialization error:', error);
      }
  }
  
  // Initialize SumoSelects when document is ready
  initializeSumoSelects();
  
  // Function to safely reload SumoSelects
  function safeReloadSumoSelect(selector) {
      try {
          var element = $(selector);
          if (element.length > 0 && element[0].sumo) {
              element[0].sumo.reload();
          }
      } catch (error) {
          console.log('Error reloading SumoSelect for', selector, ':', error);
      }
  }
function callDateAjax() {

    var startdate = $('#startdate').val();
    var enddate   = $('#enddate').val();
    var tripId    = $('#tripid').val();
    var companyId = $('#trip_company_id').val();
    var csrfName = '<?= csrf_token() ?>';
    var csrfHash = '<?= csrf_hash() ?>';
    var journeydate = $('#journeydate').val();
    var journeydateend = $('#journeydateend').val();
    var subtripselected = $('#subtripid').val();



    var baseurl   = "<?php echo base_url(); ?>";

    if (startdate && enddate || 1) {
        $.ajax({
            url: baseurl + "/modules/backend/holdseat/check-dates",
            type: "GET",
            dataType: "json",
            headers: { "X-CSRF-TOKEN": "<?= csrf_hash() ?>" },
            data: {
                [csrfName]: csrfHash,
                startdate: startdate,
                enddate: enddate,
                trip_id: tripId,
                journeydate: journeydate,
                journeydateend: journeydateend,
                company_id: companyId,
                subtripselected: subtripselected
            },
            success: function (response) {
                console.log("Date AJAX Response:", response);
                var subtripSelect     = $('#subtripid');
                var seatBlockSelect   = $('#seatblock');
                var seatUnBlockSelect = $('#seatunblock');

                // Store current selections before clearing (get from SumoSelect if available)
                var previousSelections = [];
                if (subtripSelect[0] && subtripSelect[0].sumo) {
                    // Get value from SumoSelect instance
                    try {
                        previousSelections = subtripSelect[0].sumo.getValue() || [];
                    } catch(e) {
                        // Fallback to native select value if getValue fails
                        previousSelections = subtripSelect.val() || [];
                    }
                } else {
                    // Fallback to regular select value
                    previousSelections = subtripSelect.val() || [];
                }
                if (!Array.isArray(previousSelections)) {
                    previousSelections = previousSelections ? [previousSelections] : [];
                }
                // Filter out empty values and 'select_all'
                previousSelections = previousSelections.filter(function(sel) {
                    return sel && sel !== '' && sel !== 'select_all';
                });
                console.log('Previous selections to preserve:', previousSelections);

                subtripSelect.empty();
                seatBlockSelect.empty();
                seatUnBlockSelect.empty();

                seatBlockSelect.append('<option value="">Select Seat Block</option>');
                seatUnBlockSelect.append('<option value="">Select Seat UnBlock</option>');

                var seatNumbers  = [];
                var blockedSeats = response.blocked.map(Number);
                var bookedSeats  = response.booked_seats.map(Number);

                // show booked / blocked in UI
                if (response.booked_seats && response.booked_seats.length > 0) {
                    $("#booked_seat").html(response.booked_seats.join(','));
                } else {
                    $("#booked_seat").html("None");
                }

                if (response.blocked && response.blocked.length > 0) {
                    $("#blocked_seat").html(response.blocked.join(','));
                } else {
                    $("#blocked_seat").html("None");
                }

                                 if (response.subtrips && response.subtrips.length > 0) {
                     // Collect subtrip IDs from response for selection restoration and duplicate prevention
                     var responseSubtripIds = [];
                     var addedSubtripIds = {}; // Track already added subtrips to prevent duplicates
                     
                     // Add "Select All" option at the beginning
                     subtripSelect.append('<option value="select_all" class="select-all-option">--- Select All SubTrips ---</option>');
                     
                     $.each(response.subtrips, function (index, subtrip) {
                         var subtripId = subtrip.id.toString();
                         
                         // Skip if this subtrip was already added (prevent duplicates)
                         if (addedSubtripIds[subtripId]) {
                             return; // continue to next iteration
                         }
                         addedSubtripIds[subtripId] = true;
                         responseSubtripIds.push(subtripId);
                         
                         $('#total_seat').val(subtrip.total_seat);
                         $('#layout').val(subtrip.layout);
                         $('#seat_number').val(subtrip.seat_number);
                         $('#forth_seat').val(subtrip.forth_seat);
                         $('#last_seat').val(subtrip.last_seat);
                         $('#wc').val(subtrip.wc);

                         subtripSelect.append(
                             '<option value="' + subtrip.id + '">' +
                             subtrip.pic_location_name + " - " + subtrip.drop_location_name + " (" + subtrip.id + ")" +
                             '</option>'
                         );

                         seatNumbers = subtrip.seat_number.split(',').map(Number);
                     });

                    // only free seats go into "seatBlock"
                    seatNumbers.forEach(function (seat) {
                        if (!blockedSeats.includes(seat) && !bookedSeats.includes(seat)) {
                            seatBlockSelect.append('<option value="' + seat + '">' + seat + '</option>');
                        }
                    });

                    // blocked go into "seatUnblock"
                    blockedSeats.forEach(function (seat) {
                        seatUnBlockSelect.append('<option value="' + seat + '">' + seat + '</option>');
                    });

                    // Restore previous selections if they still exist in the new options
                    var selectionsToRestore = previousSelections.filter(function(sel) {
                        var selStr = sel.toString();
                        return selStr && responseSubtripIds.includes(selStr);
                    });
                    console.log('Selections to restore:', selectionsToRestore);
                    console.log('Available subtrip IDs:', responseSubtripIds);

                                         // Set value on native select first (before reload)
                     if (selectionsToRestore.length > 0) {
                         // Convert to array of strings for comparison
                         var restoreValues = selectionsToRestore.map(function(v) { return v.toString(); });
                         
                         // Set selected attribute on matching options
                         subtripSelect.find('option').each(function() {
                             var optionValue = $(this).val().toString();
                             if (restoreValues.includes(optionValue)) {
                                 $(this).prop('selected', true);
                             }
                         });
                     }
                     
                     // reload sumo selects
                     safeReloadSumoSelect('#seatblock');
                     safeReloadSumoSelect('#subtripid');
                     safeReloadSumoSelect('#seatunblock');
                     
                     // Restore selections after reload - use setTimeout to ensure SumoSelect is ready
                     if (selectionsToRestore.length > 0) {
                         setTimeout(function() {
                             // Set value on the native select element
                             subtripSelect.val(selectionsToRestore);
                             
                             // Then update SumoSelect if it's initialized
                             if (subtripSelect[0] && subtripSelect[0].sumo) {
                                 try {
                                     // Use setValue method for SumoSelect
                                     var sumoInstance = subtripSelect[0].sumo;
                                     sumoInstance.setValue(selectionsToRestore);
                                 } catch(e) {
                                     console.log('Error setting SumoSelect value:', e);
                                     // Fallback: try setting on native select and reload
                                     subtripSelect.val(selectionsToRestore);
                                     sumoInstance.reload();
                                 }
                             }
                         }, 150);
                     }
                }
            },
            error: function (xhr, status, error) {
                console.error("Error fetching date data:", error);
            }
        });
    }
}
$('#startdate').on("change", function () {
    if ($('#enddate').val()) {
        callDateAjax();
    }
});

$('#enddate').on("blur", function () {
    if (!validateHoldBlockWindow(true)) {
        return;
    }
    if ($('#startdate').val() && $('#enddate').val()) {
        callDateAjax();
    }
});

 $('#journeydateend').on("blur", function () {
     let start = $('#journeydate').val();
     let end = $('#journeydateend').val();

     if (start && end) {
         if (new Date(end) < new Date(start)) {
             alert("End date must be greater than Start date!");
             $('#journeydateend').val(""); // clear invalid end date
             return;
         }
         callDateAjax();
     }
 });

      // Handle "Select All" option in dropdown
   $('#subtripid').on('change', function () {
       let selected = $(this).val();

       // if "select_all" is selected
       if (selected && selected.includes("select_all")) {
           // select all options
           $('#subtripid option').prop('selected', true);
           // remove duplicate "select_all" 
           $('#subtripid option[value="select_all"]').prop('selected', false);

           // refresh SumoSelect UI
           $('#subtripid')[0].sumo.reload();
       }
   });

 </script>
<?php echo $this->endSection() ?>