<?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>
        .holdseat-page .SumoSelect {
            width: 100%;
            max-width: 100%;
        }

        .holdseat-page .SumoSelect > .CaptionCont {
            width: 100%;
        }

        .holdseat-page .SumoSelect > .optWrapper {
            min-width: 0 !important;
            width: 100% !important;
            max-width: 100%;
            box-sizing: border-box;
        }

        .holdseat-page .SumoSelect .options li label {
            white-space: normal;
            word-break: break-word;
        }

        .holdseat-page #booked_seat,
        .holdseat-page #blocked_seat {
            word-break: break-word;
            overflow-wrap: anywhere;
            margin-bottom: 0;
        }

        .holdseat-page .holdseat-seat-layout {
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
            padding: 0.25rem 0 0.5rem;
        }

        .holdseat-page .holdseat-seat-layout > div {
            margin-left: auto;
            margin-right: auto;
        }

        .holdseat-page .holdseat-actions {
            width: 100%;
        }

        .holdseat-page .holdseat-actions .btn {
            flex: 1 1 auto;
            min-width: 8.5rem;
            margin-top: 0 !important;
            padding-top: 0.5rem !important;
            border-top: none !important;
        }

        .holdseat-page .form-control,
        .holdseat-page .form-select,
        .holdseat-page .flatpickr-input,
        .holdseat-page .flatpickr-wrapper,
        .holdseat-page .input-group {
            width: 100%;
            max-width: 100%;
        }

        @media (max-width: 767.98px) {
            .holdseat-page .SumoSelect.open > .optWrapper {
                position: fixed !important;
                left: 0.75rem !important;
                right: 0.75rem !important;
                top: auto !important;
                bottom: 0 !important;
                width: auto !important;
                max-width: none;
                max-height: 70vh;
                margin: 0;
                z-index: 10060;
            }

            .holdseat-page .SumoSelect.open > .optWrapper > .options {
                max-height: calc(70vh - 3.5rem);
            }

            .holdseat-page .holdseat-actions .btn {
                width: 100%;
                min-width: 0;
            }

            .holdseat-page .holdseat-layout-col {
                order: 2;
            }

            .holdseat-page .holdseat-form-col {
                order: 1;
            }
        }

        @media (min-width: 768px) {
            .holdseat-page .SumoSelect > .optWrapper {
                min-width: 280px !important;
                max-width: min(400px, 100%);
            }
        }
    </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 holdseat-page">
    <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 g-3">
                <div class="col-12 col-lg-6 holdseat-form-col">
                    <div class="row g-3">

                        <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 value=""><?php echo lang('Localize.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('Localize.trip_location') ?> <abbr class="required" title="Required field">*</abbr></label>
                            <select class="form-select w-100" name="tripid" id="tripid" required>
                                <option value=""><?php echo lang('Localize.select_trip'); ?></option>
                            </select>
                        </div>

                                                 <div class="col-12 col-md-6 col-lg-4 form-group">
                             <label for="subtrip"><?php echo lang('Localize.subtrip_location') ?> <abbr class="required" title="Required field">*</abbr></label>
                             <select class="form-select w-100" name="subtripid[]" id="subtripid" multiple>
                             </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 mb-0">
                            <label for="notes"><?php echo lang('Localize.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-12 col-lg-6 holdseat-layout-col">
                    <label class="form-label d-lg-none"><?php echo lang('Localize.seat_layout'); ?></label>
                    <div id="seatLayoutContainer" class="holdseat-seat-layout mt-lg-4"></div>
                </div>
            </div>


            <!--<div class="text-danger">-->
            <!--    <?php if (isset($validation)) : ?>-->
            <!--        <?= $validation->listErrors(); ?>-->
            <!--    <?php endif ?>-->
            <!--</div>-->
            <div class="row mt-3">
                <div class="col-12">
                    <div class="d-flex flex-wrap gap-2 justify-content-center holdseat-actions">
                        <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 lang('Localize.seat_layout'); ?></button>
                        <button type="button" class="btn btn-success" id="sync" onclick="callDateAjax()"><?php echo lang('Localize.sync'); ?></button>
                    </div>
                </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>
var holdSeatLang = <?php echo json_encode([
    'selectTrip' => lang('Localize.select_trip'),
    'selectSubtrip' => lang('Localize.select_subtrip'),
    'selectSeatBlock' => lang('Localize.select_seat_block'),
    'selectSeatUnblock' => lang('Localize.select_seat_unblock'),
    'selectAllSubtrips' => lang('Localize.select_all_subtrips'),
    'noTripsAvailable' => lang('Localize.no_trips_available'),
    'none' => lang('Localize.none'),
    'ok' => lang('Localize.ok'),
    'cancel' => lang('Localize.cancel'),
    'selectAll' => lang('Localize.select_all'),
    'sumoSelectPlaceholder' => lang('Localize.sumo_select_placeholder'),
    'holdEndAfterStart' => lang('Localize.hold_end_after_start'),
    'holdWindowMinMinutes' => lang('Localize.hold_window_min_minutes'),
    'pleaseSelectTrip' => lang('Localize.please_select_trip'),
    'pleaseSelectSubtrip' => lang('Localize.please_select_subtrip'),
    'pleaseSelectSeatBlock' => lang('Localize.please_select_seat_block'),
    'journeyEndAfterStart' => lang('Localize.journey_end_after_start'),
    'holdBlockMinMinutes' => 5,
], JSON_UNESCAPED_UNICODE); ?>;

function getSumoSelectOptions(placeholder) {
    return {
        okCancelInMulti: true,
        triggerChangeCombined: true,
        forceCustomRendering: true,
        selectAll: true,
        csvDispCount: 2,
        placeholder: placeholder || holdSeatLang.sumoSelectPlaceholder,
        locale: [holdSeatLang.ok, holdSeatLang.cancel, holdSeatLang.selectAll]
    };
}

$(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="">' + holdSeatLang.selectTrip + '</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="">' + holdSeatLang.noTripsAvailable + '</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();

                    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) {
                         $.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="">' + holdSeatLang.noTripsAvailable + '</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(holdSeatLang.holdEndAfterStart);
        }
        return false;
    }
    var diffMin = (end.getTime() - start.getTime()) / 60000;
    if (diffMin < holdBlockMinMinutes) {
        if (showAlert) {
            alert(holdSeatLang.holdWindowMinMinutes.replace('{minutes}', holdBlockMinMinutes));
        }
        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(holdSeatLang.pleaseSelectTrip);
        return false;
    }
    if (!$('#subtripid').val() || ($('#subtripid').val() || []).length === 0) {
        e.preventDefault();
        alert(holdSeatLang.pleaseSelectSubtrip);
        return false;
    }
    if (!$('#seatblock').val() || ($('#seatblock').val() || []).length === 0) {
        e.preventDefault();
        alert(holdSeatLang.pleaseSelectSeatBlock);
        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(getSumoSelectOptions(holdSeatLang.selectSeatBlock));
          }
          
          if ($('#subtripid').length > 0) {
              $('#subtripid').SumoSelect(getSumoSelectOptions(holdSeatLang.selectSubtrip));
          }
          
          if ($('#seatunblock').length > 0) {
              $('#seatunblock').SumoSelect(getSumoSelectOptions(holdSeatLang.selectSeatUnblock));
          }
      } 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();

                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(holdSeatLang.none);
                }

                if (response.blocked && response.blocked.length > 0) {
                    $("#blocked_seat").html(response.blocked.join(','));
                } else {
                    $("#blocked_seat").html(holdSeatLang.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
                     
                     $.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(holdSeatLang.journeyEndAfterStart);
             $('#journeydateend').val(""); // clear invalid end date
             return;
         }
         callDateAjax();
     }
 });

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