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

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

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

    <div class="card mb-4">
        <div class="card-body">
            <form action="<?php echo base_url(route_to('update-trip', $trip->id)) ?>" id="employee" method="post" class="row g-3" accept-charset="utf-8" enctype="multipart/form-data">
                <?php echo $this->include('common/securityupdate') ?>

                <div class="bg-light p-3 my-2">
                    <strong class="mb-1"><?php echo lang("Localize.trip") ?> <?php echo lang("Localize.section") ?></strong>

                    <div class="row">
                        <?php if(session()->get('role_id') == "1"){ ?>
                            <div class="col-12 col-md-6 col-lg-3 mt-2">
                                <?php echo $this->include('common/filter/company') ?>
                            </div>
                        <?php } ?> 
                        <div class="col-12 col-md-6 col-lg-3 mt-2">
                            <label for="pick_location_id" class="form-label"><?php echo lang("Localize.pick_up") ?> <abbr title="Required field">*</abbr></label>
                            <select class="form-select select2" name="pick_location_id" id="pick_location_id" required>
                                <option value="">None</option>

                                <?php
                                foreach ($location as $locationvalue) :
                                    $checkSelected = ($locationvalue->id == $trip->pick_location_id) ? 'selected' : '';
                                    $checkDisabled = ($locationvalue->id == $trip->drop_location_id) ? 'disabled' : '';
                                ?>

                                    <option value="<?php echo $locationvalue->id ?>" <?php echo $checkSelected . " " . $checkDisabled ?>>
                                        <?php echo $locationvalue->name ?>
                                    </option>
                                <?php endforeach ?>

                            </select>
                        </div>
                        <div class="col-12 col-md-6 col-lg-3 mt-2">
                            <label for="drop_location_id" class="form-label"><?php echo lang("Localize.drop") ?> <abbr title="Required field">*</abbr></label>
                            <select class="form-select select2" name="drop_location_id" id="drop_location_id" required>
                                <option value="">None</option>

                                <?php
                                foreach ($location as $locationvalue) :
                                    $checkSelected = ($locationvalue->id == $trip->drop_location_id) ? 'selected' : '';
                                    $checkDisabled = ($locationvalue->id == $trip->pick_location_id) ? 'disabled' : '';
                                ?>
                                    <option value="<?php echo $locationvalue->id ?>" <?php echo $checkSelected . " " . $checkDisabled ?>>
                                        <?php echo $locationvalue->name ?>
                                    </option>
                                <?php endforeach ?>

                            </select>
                        </div>
                        <div class="col-12 col-md-6 col-lg-3 mt-2">
                            <label for="stoppage" class="form-label"><?php echo lang("Localize.stoppage") ?> <?php echo lang("Localize.point") ?> <abbr title="Required field">*</abbr></label>
                            <select name="stoppage[]" id="stoppage" class="form-control" multiple>

                                <?php
                                foreach ($location as $dropkye => $dlocationvalue) :
                                    $checkSelected = in_array($dlocationvalue->id, $stoppage) ? 'selected' : '';
                                    $checkDisabled = in_array($dlocationvalue->id, [$trip->pick_location_id, $trip->drop_location_id]) ? 'disabled' : '';
                                ?>

                                    <option value="<?php echo $dlocationvalue->id ?>" <?php echo $checkSelected . " " . $checkDisabled ?>>
                                        <?php echo $dlocationvalue->name ?>
                                    </option>

                                <?php endforeach ?>

                            </select>
                        </div>
                        <div class="col-12 col-md-6 col-lg-3 mt-2">
                            <label for="schedule_id" class="form-label"><?php echo lang("Localize.schedule") ?> <?php echo lang("Localize.time") ?> <abbr title="Required field">*</abbr></label>
                            <select name="schedule_id" class="testselect1" required>
                                <option value="">None</option>
                                <?php foreach ($schedule as $schedulevalue) : ?>

                                    <?php if ($schedulevalue->id == $trip->schedule_id) : ?>
                                        <option value="<?php echo $schedulevalue->id ?>" selected><?php echo $schedulevalue->start_time ?>  <?php //echo $schedulevalue->end_time ?></option>
                                    <?php else : ?>
                                        <option value="<?php echo $schedulevalue->id ?>"><?php echo $schedulevalue->start_time ?>  <?php //echo $schedulevalue->end_time ?></option>
                                    <?php endif ?>


                                <?php endforeach ?>
                            </select>
                        </div>
                        <div class="col-12 col-md-6 col-lg-3 mt-2">
                            <label for="fleettype" class="form-label"><?php echo lang("Localize.fleet") ?> <?php echo lang("Localize.type") ?> <abbr title="Required field">*</abbr></label>
                            <select name="fleet_id" id="fleet_id" class="form-select select2" data-minimum-results-for-search="-1" required>
                                <option value=""><?php echo lang("Localize.none") ?></option>
                                
                                <?php foreach ($fleet_types as $fleet_type) : ?>
                                
                                    <?php if ($fleet_type->id == $trip->fleet_id) : ?>
                                        <option value="<?php echo $fleet_type->id ?>" selected><?php echo $fleet_type->type ?></option>
                                    <?php else : ?>
                                        <option value="<?php echo $fleet_type->id ?>"><?php echo $fleet_type->type ?></option>
                                    <?php endif ?>
                                <?php endforeach ?>

                            </select>
                        </div>
                        <div class="col-12 col-md-6 col-lg-3 mt-2">
                            <label for="trip_category_id" class="form-label"><?php echo lang("Localize.category") ?> <?php echo lang("Localize.type") ?> <abbr title="Required field">*</abbr></label>
                            <select name="trip_category_id" id="trip_category_id" class="form-select select2" data-minimum-results-for-search="-1" required>
                                <option value=""><?php echo lang("Localize.none") ?></option>
                                
                                <?php foreach ($TripCategories as $TripCategory) : ?>
                                
                                    <?php if ($TripCategory->id == $trip->trip_category_id) : ?>
                                        <option value="<?php echo $TripCategory->id ?>" selected><?php echo $TripCategory->name ?></option>
                                    <?php else : ?>
                                        <option value="<?php echo $TripCategory->id ?>"><?php echo $TripCategory->name ?></option>
                                    <?php endif ?>
                                <?php endforeach ?>

                            </select>
                        </div>
                        <div class="col-12 col-md-6 col-lg-3 mt-2">
                            <label for="trip_bus_type_id" class="form-label"><?php echo lang("Localize.bus") ?> <?php echo lang("Localize.type") ?> <abbr title="Required field">*</abbr></label>
                            <select name="trip_bus_type_id" id="trip_bus_type_id" class="form-select select2" data-minimum-results-for-search="-1" required>
                                <option value=""><?php echo lang("Localize.none") ?></option>
                                
                                <?php foreach ($TripBusTypes as $TripBusType) : ?>
                                
                                    <?php if ($TripBusType->id == $trip->trip_bus_type_id) : ?>
                                        <option value="<?php echo $TripBusType->id ?>" selected><?php echo $TripBusType->name ?></option>
                                    <?php else : ?>
                                        <option value="<?php echo $TripBusType->id ?>"><?php echo $TripBusType->name ?></option>
                                    <?php endif ?>
                                <?php endforeach ?>

                            </select>
                        </div>
                        <div class="col-12 col-md-6 col-lg-3 mt-2">
                            <label for="trip_type" class="form-label"><?php echo lang("Localize.trip") ?> <?php echo lang("Localize.type") ?> <abbr title="Required field">*</abbr></label>
                            <select name="trip_type" id="trip_type" class="form-select select2" data-minimum-results-for-search="-1" required>
                                <option value=""><?php echo lang("Localize.none") ?></option>
                                <option <?php if($trip->trip_type == "Main"){ echo "selected"; } ?> value="Main"><?php echo lang("Localize.main") ?></option>
                                <option <?php if($trip->trip_type == "Add On"){ echo "selected"; } ?> value="Add On"><?php echo lang("Localize.add_on") ?></option>

                            </select>
                        </div>
                        <div class="col-12 col-md-6 col-lg-3 d-none">
                            <label for="company_name" class="form-label"><?php echo lang("Localize.company") ?> <?php echo lang("Localize.name") ?> <abbr title="Required field">*</abbr></label>
                            <input type="text" id="company_name" name="company_name" class="form-control" value="<?= old('company_name') ?? $trip->company_name ?>" placeholder="<?php echo lang("Localize.company") ?> <?php echo lang("Localize.name") ?>" required />
                        </div>
                    </div>
                </div>

                <?php echo $this->include($viewpath . '/trip/editarrival') ?>
                <?php echo $this->include($viewpath . '/trip/editdeparture') ?>

                <div class="bg-light p-3 my-2">
                    <strong class="mb-1"><?php echo lang("Localize.class").', '.lang("Localize.seat") . ', ' . lang("Localize.fair") ?></strong>

                    <div class="row">
                        <!-- <div class="col-12 col-md-6 col-lg-3">
                            <label for="child_seat" class="form-label"><?php echo lang("Localize.children") ?> <?php echo lang("Localize.seat") ?> </label>
                            <input type="number" id="child_seat" name="child_seat" class="form-control" value="<?= old('child_seat') ?? $trip->child_seat ?>" placeholder="<?php echo lang("Localize.children") ?> <?php echo lang("Localize.seat") ?>" min="0">
                        </div>

                        <div class="col-12 col-md-6 col-lg-3">
                            <label for="child_fair" class="form-label"><?php echo lang("Localize.children") ?> <?php echo lang("Localize.fair") ?></label>
                            <input type="number" id="child_fair" name="child_fair" class="form-control" value="<?= old('child_fair') ?? $trip->child_fair ?>" placeholder="<?php echo lang("Localize.children") ?> <?php echo lang("Localize.fair") ?>" min="0">
                        </div>

                        <div class="col-12 col-md-6 col-lg-3">
                            <label for="special_seat" class="form-label"><?php echo lang("Localize.special") ?> <?php echo lang("Localize.seat") ?></label>
                            <input type="number" id="special_seat" name="special_seat" class="form-control" value="<?= old('special_seat') ?? $trip->special_seat ?>" placeholder="<?php echo lang("Localize.special") ?> <?php echo lang("Localize.seat") ?>" min="0">
                        </div>

                        <div class="col-12 col-md-6 col-lg-3">
                            <label for="special_fair" class="form-label"><?php echo lang("Localize.special") ?> <?php echo lang("Localize.fair") ?> </label>
                            <input type="number" id="special_fair" name="special_fair" class="form-control" value="<?= old('special_fair') ?? $trip->special_fair ?>" placeholder="<?php echo lang("Localize.special") ?> <?php echo lang("Localize.seat") ?> <?php echo lang("Localize.fair") ?>" min="0">
                        </div>

                        <div class="col-12 col-md-6 col-lg-3">
                            <label for="vip_seat" class="form-label"><?php echo lang("Localize.vip") ?> <?php echo lang("Localize.seat") ?></label>
                            <input type="number" id="vip_seat" name="vip_seat" class="form-control" value="<?= old('vip_seat') ?? $trip->vip_seat ?>" placeholder="<?php echo lang("Localize.vip") ?> <?php echo lang("Localize.seat") ?>" min="0">
                        </div>

                        <div class="col-12 col-md-6 col-lg-3">
                            <label for="vip_fair" class="form-label"><?php echo lang("Localize.vip") ?> <?php echo lang("Localize.fair") ?> </label>
                            <input type="number" id="vip_fair" name="vip_fair" class="form-control" value="<?= old('vip_fair') ?? $trip->vip_fair ?>" placeholder="<?php echo lang("Localize.vip") ?> <?php echo lang("Localize.seat") ?> <?php echo lang("Localize.fair") ?>" min="0">
                        </div> -->

                        <div class="col-12 col-md-6 col-lg-3 mt-2">
                            <label for="adult_fair" class="form-label"><?php echo lang("Localize.adult") ?> <?php echo lang("Localize.fair") ?> <abbr title="Required field">*</abbr></label>
                            <input type="number" id="adult_fair" name="adult_fair" class="form-control" value="<?= old('adult_fair') ?? $trip->adult_fair ?>" placeholder="<?php echo lang("Localize.adult") ?> <?php echo lang("Localize.seat") ?> <?php echo lang("Localize.fair") ?> *" min="1" required>
                        </div>

                        <div class="col-12 col-md-6 col-lg-3 mt-2">
                            <label for="adult_fair" class="form-label"><?php echo lang("Localize.distance") ?> <abbr title="Required field">*</abbr></label>
                            <input type="number" id="distance" name="distance" class="form-control" value="<?= old('distance') ?? $trip->distance ?>" placeholder="<?php echo lang("Localize.distance") ?>" min="1" required />
                        </div>

                        <div class="col-12 col-md-6 col-lg-3 mt-2">
                            <label for="journey_hour" class="form-label"><?php echo lang("Localize.approximate") ?> <?php echo lang("Localize.time") ?> <abbr title="Required field">*</abbr></label>
                            <input type="number" id="journey_hour" name="journey_hour" class="form-control" value="<?= old('journey_hour') ?? $trip->journey_hour ?>" placeholder="<?php echo lang("Localize.approximate") ?> <?php echo lang("Localize.time") ?>" step=any>
                        </div>

                        <div class="col-12 col-md-6 col-lg-3 mt-2">
                            <label for="startdate" class="form-label"><?php echo lang("Localize.trip") ?> <?php echo lang("Localize.start") ?> <?php echo lang("Localize.date") ?> <abbr title="Required field">*</abbr></label>
                            <div class="input-group date datepicker" id="startdate">
                                <input type="text" class="form-control" name="startdate" value="<?php echo date("Y-m-d", strtotime($trip->startdate)) ?>" readonly required />
                                <div class="input-group-addon"></div>
                            </div>
                        </div>

                        <div class="col-12 col-md-6 col-lg-3 mt-2">
                            <label for="facility" class="form-label"><?php echo lang("Localize.facility") ?> </label>
                            <select multiple="multiple" name="facility[]" class="testselect3">
                                <option value="">None</option>
                                <?php foreach ($facility as $fkye => $facilityvalue) : ?>

                                    <?php if (in_array($facilityvalue->id, $facilityold)) : ?>
                                        <option value="<?php echo $facilityvalue->id ?>" selected><?php echo $facilityvalue->name ?></option>
                                    <?php else : ?>
                                        <option value="<?php echo $facilityvalue->id ?>"><?php echo $facilityvalue->name ?></option>

                                    <?php endif ?>

                                <?php endforeach ?>
                            </select>
                        </div>
                    </div>
                    
                    <?php
                    
                    $seatsfareData = [];
                    $SeatsCounter = 1;
                    if($trip->seatclass != ""){ 
                        
                        $seatsfareArr = json_decode($trip->seatclass, 1);

                        if(!empty($seatsfareArr)){
                            $seatsfareData = $seatsfareArr;
                        }

                    } 

                    if (!empty($seatsfareData)){ 
                        
                        $totalSeatsCount = count($seatsfareData);
                        $SeatsCounter = $totalSeatsCount;

                        for ($j = 0; $j < $totalSeatsCount; $j++){ ?>

                            <div class="row mt-3" id="extraRow<?php echo $j; ?>">
                                <div class="col-12 col-md-6 col-lg-3">
                                    <label class="form-label"><?php echo lang("Localize.class"); ?></label>
                                    <select class="form-select select2 seatClass" name="seatClass[]" id="seatClass<?php echo $j; ?>" required>
                                        <?php foreach ($class as $classvalue) : ?>
                                            <?php if ($classvalue->id == $seatsfareData[$j]['seatClass']) : ?>
                                                <option value="<?php echo $classvalue->id; ?>" selected><?php echo $classvalue->name; ?></option>
                                            <?php else : ?>
                                                <option value="<?php echo $classvalue->id; ?>"><?php echo $classvalue->name; ?></option>
                                            <?php endif ?>
                                            
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-12 col-md-6 col-lg-3">
                                    <?php $selectedseatNo = $seatsfareData[$j]['seatNo']; ?>
                                    <label class="form-label"><?php echo lang("Localize.seat"); ?></label>
                                    <select name="seatNo[<?php echo $j; ?>][]" class="form-control seatNo" id="seatNo<?php echo $j; ?>" multiple>
                                        <?php 
                                        $totalSeats = ($total_layout_seats) ? $total_layout_seats : 50;
                                        $seats = range(1, $totalSeats); // Generate seat numbers dynamically
                                        foreach ($seats as $seatvalue) :
                                            $selected = (in_array($seatvalue, $selectedseatNo)) ? 'selected' : ''; 
                                        ?>
                                            <option value="<?php echo $seatvalue; ?>" <?php echo $selected; ?>><?php echo $seatvalue; ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-12 col-md-6 col-lg-3">
                                    <label class="form-label"><?php echo lang("Localize.fair"); ?></label>
                                    <input type="number" name="fares[]" id="fares<?php echo $j; ?>" value="<?php echo $seatsfareData[$j]['fare']; ?>" class="form-control">
                                </div>
                                <div class="col-12 col-md-6 col-lg-3">
                                    <label style="display:block;" class="form-label">&nbsp;</label>
                                        <?php if($j == 0){ ?>
                                            <button type="button" class="btn btn-success" id="addMoreClass">Add More</button>
                                        <?php } else { ?>
                                            <button type="button" class="btn btn-danger deleteBtn" data-row-id="extraRow<?php echo $j; ?>">Delete</button>
                                        <?php } ?>
                                </div>
                            </div>
                        <?php } ?>

                    <?php } else { ?>
                        <div class="row mt-3" id="extraRow0">
                            <div class="col-12 col-md-6 col-lg-3">
                                <label class="form-label"><?php echo lang("Localize.class"); ?></label>
                                <select class="form-select select2 seatClass" name="seatClass[]" id="seatClass0" required>
                                    <?php foreach ($class as $classvalue) : ?>
                                        <option value="<?php echo $classvalue->id; ?>"><?php echo $classvalue->name; ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-12 col-md-6 col-lg-3">
                                <label for="seatNo0" class="form-label"><?php echo lang("Localize.seat"); ?></label>
                                <select name="seatNo[0][]" id="seatNo0" class="form-control seatNo" multiple>
                                    <?php 
                                    $totalSeats = ($total_layout_seats) ? $total_layout_seats : 50;
                                    $seats = [];
                                    for ($i = 1; $i <= $totalSeats; $i++) {
                                        $seats[] = $i;
                                    }
                                    foreach ($seats as $seatvalue) : ?>
                                        <option value="<?php echo $seatvalue; ?>"><?php echo $seatvalue; ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-12 col-md-6 col-lg-3">
                                <label for="fares0" class="form-label"><?php echo lang("Localize.fair"); ?></label>
                                <input type="number" name="fares[]" id="fares0" class="form-control">
                            </div>
                            <div class="col-12 col-md-6 col-lg-3">
                                <label style="display:block;" class="form-label">&nbsp;</label>
                                <button type="button" class="btn btn-success" id="addMoreClass">Add More</button>
                            </div>
                        </div>
                    <?php } ?>
                    <div id="addedExtraseatDiv">
                    </div>
                </div>
                
                <div class="bg-light p-3 my-2">
                    <strong class="mb-1"><?php echo lang("Date Settings") ?></strong>

                    <div class="row">
                        
                        <!--//bus opration date type-->
                        <div class="col-12 col-md-6 mt-2">
                            <label for="oprationDatetype" class="form-label"><?php echo lang("Bus Opration Date Type") ?> </label>
                        </div>
                        <div class="col-12 col-md-6 mt-2">
                            <select name="oprationDatetype" id="oprationDatetype" class="form-select select2" onchange="toggleRepetedFields()" required>
                                <option value=""><?php echo lang("Localize.none") ?></option>
                                
                                <option value="repeted" <?= ($trip->oprationDatetype == 'repeted') ? 'selected' : '' ?>>
                                    <?php echo lang("Repeted") ?>
                                </option>
                                
                                <option value="nonRepeted" <?= ($trip->oprationDatetype == 'nonRepeted') ? 'selected' : '' ?>>
                                    <?php echo lang("Non-Repeted") ?>
                                </option>
                            </select>
                        </div>


                        <!--repeted start date-->
                        <div class="col-12 col-md-6 mt-2">
                            <label for="repetedstartdate" class="form-label"><?php echo lang("Repeted") ?> <?php echo lang("Localize.start") ?> <?php echo lang("Localize.date") ?>  <abbr title="Required field">*</abbr></label>
                        </div>
                        <div class="col-12 col-md-6 mt-2">
                            <div class="input-group date datepicker">
                                <input type="text" class="form-control" id="repetedstartdate" name="repetedstartdate" value="<?= $trip->repetedstartdate ?>"  required />
                                <div class="input-group-addon"></div>
                            </div>
                        </div>

                        <!--repeted end date-->
                        <div class="col-12 col-md-6 mt-2">
                            <label for="repetedenddate" class="form-label"><?php echo lang("Repeted") ?> <?php echo lang("Localize.end") ?> <?php echo lang("Localize.date") ?>  <abbr title="Required field">*</abbr></label>
                        </div>
                        <div class="col-12 col-md-6 mt-2">
                            <div class="input-group date datepicker">
                                <input type="text" class="form-control" id="repetedenddate" name="repetedenddate" value="<?= $trip->repetedenddate ?>" readonly required />
                                <div class="input-group-addon"></div>
                            </div>
                        </div>

                        <!--repeted after-->
                        <div class="col-12 col-md-6 mt-2">
                            <label for="repeted_after" class="form-label"><?php echo lang("Repeted After") ?> </label>
                        </div>
                        <div class="col-12 col-md-6 mt-3">
                            <input type="number" id="repeted_after" name="repeted_after" class="form-control" value="<?= old('repeted_after') ?><?= $trip->repeted_after ?>" min="0">
                        </div>

                        
                        
                        <!--maximum day for booking-->
                        <div class="col-12 col-md-6 mt-2">
                            <label for="maxdayforbooking" class="form-label"><?php echo lang("Maximum Day For Booking") ?> </label>
                            
                        </div>
                        <div class="col-12 col-md-6 mt-2">
                            
                            <input type="number" id="maxdayforbooking" name="maxdayforbooking" class="form-control" value="<?= old('maxdayforbooking') ?><?= $trip->maxdayforbooking ?>" min="0">
                        </div>
                        
                        <div class="col-12 col-md-6 col-lg-4 mt-2">
                            <label for="weekend" class="form-label"><?php echo lang("Days Off") ?> </label>
                            
                        </div>
                        <div class="col-12 col-md-6 col-lg-8 mt-2 text-end">
                            
                            <!--<div class="d-flex flex-wrap">-->
                            <!--    <?php foreach ($weekday as $key => $weekdayvalue) : ?>-->
                            <!--    <div class="form-check me-3">-->
                            <!--    <input class="form-check-input" type="checkbox" style="border-color:green;" name="weekend[]" value="<?php echo $key ?>" id="weekend_<?php echo $key ?>">-->
                            <!--    <label class="form-check-label" for="weekend_<?php echo $key ?>">-->
                            <!--    <?php echo $weekdayvalue ?>-->
                            <!--    </label>-->
                            <!--    </div>-->
                            <!--    <?php endforeach ?>-->
                            <!--</div>-->
                            
                            
                            <div class="d-flex flex-wrap">
                                <?php foreach ($weekday as $key => $weekdayvalue) : ?>
                                <div class="form-check me-3">
                                    <input class="form-check-input" type="checkbox" style="border-color:green;" name="weekend[]" value="<?php echo $key ?>" id="weekend_<?php echo $key ?>"
                                    <?php if (in_array($key, $weekoff)) echo 'checked'; ?>>
                                    <label class="form-check-label" for="weekend_<?php echo $key ?>">
                                    <?php echo $weekdayvalue ?>
                                    </label>
                                </div>
                                <?php endforeach ?>
                            </div>
                        </div>
                        
                        <!--off dates-->
                        <div class="col-12 col-md-6 col-lg-4 mt-2">
                            <label for="offdates" class="form-label"><?php echo lang("Off Dates") ?> </label>
                        </div>
                        <div class="col-12 col-md-6 col-lg-8 mt-2 text-end">
                            <div id="dateoffinput">
                                <?php
                                $offdatesArr = [];
                                if (!empty($trip->offdates)) {
                                    $offdatesArr = explode(',', $trip->offdates);
                                }
                                ?>
                                <?php if (count($offdatesArr) > 0): ?>
                                    <?php
                                        $today = date('Y-m-d');
                                        foreach ($offdatesArr as $key => $offdate):
                                            $isPast = (strtotime($offdate) < strtotime($today));
                                    ?>
                                        <div class="row mb-2" style="margin-right: -100%;">
                                            <div class="col-12 col-md-6 col-lg-4 text-end date datepicker">
                                                <input type="text" class="form-control" name="addDateoff[]" value="<?= esc($offdate) ?>"
                                                    <?= $isPast ? 'readonly disabled' : 'onchange="updateOffdatesField()" placeholder="select date" readonly required' ?> />
                                                <div class="input-group-addon"></div>
                                            </div>
                                            <div class="col-12 col-md-6 col-lg-2">
                                                <?php if ($key == 0): ?>
                                                    <a class="btn btn-success mt-1 text-white" onclick="addfielddateoff()"><b>+</b></a>
                                                <?php elseif (!$isPast): ?>
                                                    <a class="btn btn-danger mt-1 text-white" onclick="removerow(this)"><b>&times;</b></a>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <div class="row mb-2" style="margin-right: -100%;">
                                        <div class="col-12 col-md-6 col-lg-4 text-end date datepicker">
                                            <input type="text" class="form-control" name="addDateoff[]" onchange="updateOffdatesField()" placeholder="select date" readonly required />
                                            <div class="input-group-addon"></div>
                                        </div>
                                        <div class="col-12 col-md-6 col-lg-2">
                                            <a class="btn btn-success mt-1 text-white" onclick="addfielddateoff()"><b>+</b></a>
                                        </div>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <input type="hidden" value="<?= $trip->offdates ?>" name="offdates" id="offdates"/>
                        </div>
                        
                        
                        <!--off dates in range-->
                        <div class="col-12 col-md-6 col-lg-4 mt-2">
                            <label for="offdatesInrange" class="form-label"><?php echo lang("Off Dates In Range") ?> </label>
                        </div>
                        <div class="col-12 col-md-6 col-lg-8 mt-2 text-end">
                            <div id="offDateRangesList" class="mb-2"></div> <!-- Show all ranges here -->
                            <span id="startdateinrange1"></span><span id="enddateinrange1"></span>
                            <input type="hidden" name="startdateinrange2" id="startdateinrange2" />
                            <input type="hidden" name="enddateinrange2" id="enddateinrange2" />
                            <input type="hidden" name="offdateranges" id="offdateranges" />
                            <button onclick="offdateinrange()" type='button' style="background-color: #4CAF50;color: white;padding: 10px 20px;margin-bottom: 10px;border: none;cursor: pointer;">Add New Off Date Range</button>
                        </div>
                    </div>
                    <div class="row">
                        <input type='hidden' name="vehicle_id" value='0'/>
                    </div>
                </div>

                <label for="status" class="form-label"><?php echo lang("Localize.trip") ?> <?php echo lang("Localize.status") ?></label>

                <?php if ($trip->status == 1) : ?>
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="status" id="active" value="1" checked>
                        <label class="form-check-label" for="active">
                            <?php echo lang("Localize.active") ?>
                        </label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="status" value="0" id="disable">
                        <label class="form-check-label" for="disable">
                            <?php echo lang("Localize.disable") ?>
                        </label>
                    </div>
                <?php else : ?>
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="status" id="active" value="1">
                        <label class="form-check-label" for="active">
                            <?php echo lang("Localize.active") ?>
                        </label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="status" value="0" id="disable" checked>
                        <label class="form-check-label" for="disable">
                            <?php echo lang("Localize.disable") ?>
                        </label>
                    </div>
                <?php endif ?>

                <div class="text-danger">
                    <?php if (isset($validation)) : ?>
                        <?= $validation->listErrors(); ?>
                    <?php endif ?>
                </div>

                <input type="hidden" name="id" value="<?= esc($trip->id) ?>">
                <input type="hidden" id="baseurl" name="baseurl" value="<?php echo esc(base_url()) ?>">

                <div class="col-12">
                    <button type="submit" class="btn btn-success"><?php echo lang("Localize.submit") ?></button>
                </div>

            </form>

        </div>
    </div>
    
    
    <!--model for wallet-->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js"></script>
    <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Add New Off Date</h5>
        <button type="button" class="close"  onclick='modelClose()' data-dismiss="exampleModal" aria-label="Close">
        <span aria-hidden="true">&times;</span>
        </button>
      </div>
        <form>
            <?php echo $this->include('common/security') ?>
            <div class="modal-body">
                <div class="row">
                    
                    <div class="col-md-6">
                       <label for="">Add Date Off</label>
                        
                        <div class="input-group date datepicker" id="repetedenddate">
                            <input type="text" class="form-control" name="addDateoff" onchange="valuepassdayoff()" id="addDateoff" readonly required />
                            <div class="input-group-addon"></div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" onclick='modelClose()' class="btn btn-secondary" data-dismiss="exampleModal">Close</button>
                <button type="button" onclick="modelClose()" class="btn btn-primary" data-dismiss="exampleModal">submit</submit>
            </div>
        </form>
    </div>
  </div>
</div>  


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js"></script>
<div class="modal fade" id="offdateinrange" tabindex="-1" role="dialog" aria-labelledby="offdateinrangeLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="offdateinrangeLabel">Add Day Off in Range Date</h5>
        <button type="button" class="close"  onclick='bmodelClosePopup()' data-dismiss="offdateinrange" aria-label="Close">
        <span aria-hidden="true">&times;</span>
        </button>
      </div>
        <form>
            <?php echo $this->include('common/security') ?>
            <div class="modal-body">
                <div class="row">
                    
                    <div class="col-md-6">
                       <label for="">Start</label>
                        
                        <div class="input-group date datepicker" >
                            <input type="text" class="form-control" name="daysInRangeStart" onchange="valuepassdayoffinRange()" id="daysInRangeStart" required />
                            <div class="input-group-addon"></div>
                        </div>
                    </div>
                    <div class="col-md-6">
                       <label for="">End</label>
                        
                        <div class="input-group date datepicker" >
                            <input type="text" class="form-control" name="daysInRangeEnd" onchange="valuepassdayoffinRange()" id="daysInRangeEnd" required />
                            <div class="input-group-addon"></div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" onclick='bmodelClosePopup()' class="btn btn-secondary" data-dismiss="offdateinrange">Close</button>
                <button type="button" onclick="bmodelClose()" class="btn btn-primary" data-dismiss="offdateinrange">submit</submit>
            </div>
        </form>
    </div>
  </div>
</div>

<script>
    function toggleRepetedFields() {
        var oprationDatetype = document.querySelector('select[name="oprationDatetype"]').value;
        var repetedstartdate = document.getElementById('repetedstartdate');
        var repetedenddate = document.getElementById('repetedenddate');
        var repeted_after = document.getElementById('repeted_after');
        
        if (oprationDatetype === 'nonRepeted') {
            repetedstartdate.disabled = true;
            repetedenddate.disabled = true;
            repeted_after.disabled = true;
            repetedstartdate.required = false;
            repetedenddate.required = false;
        } else {
            repetedstartdate.disabled = false;
            repetedenddate.disabled = false;
            repeted_after.disabled = false;
            repetedstartdate.required = true;
            repetedenddate.required = true;
        }
    }

    // Call the function initially to set the correct state based on the initial value
    document.addEventListener('DOMContentLoaded', toggleRepetedFields);
</script>
</script>

<script>
    
    function valuepassdayoff(){
        
       let addDateoff = $('#addDateoff').val();
        $('#adddayoffid').html(addDateoff);
        $('#offdates').val(addDateoff);
    }
    
    function valuepassdayoffinRange(){
        let daysInRangeStart = $('#daysInRangeStart').val();
        let daysInRangeEnd = $('#daysInRangeEnd').val();
            $('#startdateinrange1').html("start "+daysInRangeStart);
            $('#startdateinrange2').val(daysInRangeStart);
            $('#enddateinrange1').html(", end "+daysInRangeEnd);    
            $('#enddateinrange2').val(daysInRangeEnd);
    }


    function offdateinrange(){
        $("#offdateinrange").modal("show");
    }
    
    function bmodelClose(){ 
        let start = $('#daysInRangeStart').val();
        let end = $('#daysInRangeEnd').val();
        if(start && end){
            if (new Date(end) <= new Date(start)) {
                alert('End date must be greater than start date.');
                return;
            }
            offDateRanges.push({start: start, end: end});
            updateOffDateRangesList();
        }
        $("#offdateinrange").modal("hide");
        $('#daysInRangeStart').val('');
        $('#daysInRangeEnd').val('');
    }
    function bmodelClosePopup(){
        $("#offdateinrange").modal("hide");
        $('#daysInRangeStart').val('');
        $('#daysInRangeEnd').val('');   
    }

    function addnewdaysoff(){
        $("#exampleModal").modal("show");
    }

    function modelClose(){
        $("#exampleModal").modal("hide");
    }
    const formData = <?php echo json_encode($seatclass); ?>;

    function populateForm(data) {
        data.forEach((item, index) => {
            const counter = index + 1; // Unique counter for each row

            // Create a new row for each item in the data
            const newRow = `
                <div class="row mt-3" id="extraRow${counter}">
                    <div class="col-12 col-md-6 col-lg-3">
                        <label class="form-label"><?php echo lang("Localize.class"); ?></label>
                        <select class="form-select select2 seatClass" name="seatClass[]" id="seatClass${counter}" required>
                            <option value="1" ${item.seatClass == "1" ? "selected" : ""}>Class 1</option>
                            <option value="3" ${item.seatClass == "3" ? "selected" : ""}>Class 3</option>
                        </select>
                    </div>
                    <div class="col-12 col-md-6 col-lg-3">
                        <label for="seatNo${counter}" class="form-label"><?php echo lang("Localize.seat"); ?></label>
                        <select name="seatNo[${counter}][]" class="form-control seatNo" id="seatNo${counter}" multiple>
                        </select>
                    </div>
                    <div class="col-12 col-md-6 col-lg-3">
                        <label for="fares${counter}" class="form-label"><?php echo lang("Localize.fair"); ?></label>
                        <input type="number" name="fares[]" id="fares${counter}" class="form-control" value="${item.fare}">
                    </div>
                    <div class="col-12 col-md-6 col-lg-3">
                        <label style="display:block;" class="form-label">&nbsp;</label>
                        <button type="button" class="btn btn-danger deleteBtn" data-row-id="extraRow${counter}">Delete</button>
                    </div>
                </div>
            `;
            
            // Append the new row to the container
            $('#extraRowContainer').append(newRow);

            // Populate the seat options dynamically for the new row
            const seatSelect = $(`#seatNo${counter}`);
            const maxSeats = 50; // Adjust based on your requirement

            for (let i = 1; i <= maxSeats; i++) {
                const selected = item.seatNo.includes(i.toString()) ? "selected" : "";
                seatSelect.append(`<option value="${i}" ${selected}>${i}</option>`);
            }
        });
    }

    $(document).ready(function () {
        // Call the function to populate the form with the data
        populateForm(formData);
    });
</script>
    <!--model end-->
<?php echo $this->endSection() ?>

<?php echo $this->section('js') ?>
    <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>
        $(document).ready(function () {
        
            var maxSeats = <?php echo $totalSeats; ?>; // Default max seats
            // Initialize Select2 for the first row
            //$('.select2').select2();

            // Counter to generate unique IDs for new rows
            let counter = <?php echo $SeatsCounter ?>;

            // Add More functionality
            $('#addMoreClass').on('click', function (e) {
                
                e.preventDefault();

                // Generate a new row
                const newRow = `
                <div class="row mt-3" id="extraRow${counter}">
                    <div class="col-12 col-md-6 col-lg-3">
                        <label class="form-label"><?php echo lang("Localize.class"); ?></label>
                        <select class="form-select select2 seatClass" name="seatClass[]" id="seatClass${counter}" required>
                            <?php foreach ($class as $classvalue) : ?>
                                <option value="<?php echo $classvalue->id; ?>"><?php echo $classvalue->name; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-12 col-md-6 col-lg-3">
                        <label for="seatNo${counter}" class="form-label"><?php echo lang("Localize.seat"); ?></label>
                        <select name="seatNo[${counter}][]" id="seatNo${counter}" class="form-control seatNo" multiple>
                            <?php 
                            $seats = [];
                            for ($i = 1; $i <= $totalSeats; $i++) {
                                $seats[] = $i;
                            }
                            foreach ($seats as $seatvalue) : ?>
                                <option value="<?php echo $seatvalue; ?>"><?php echo $seatvalue; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-12 col-md-6 col-lg-3">
                        <label for="fares${counter}" class="form-label"><?php echo lang("Localize.fair"); ?></label>
                        <input type="number" name="fares[]" id="fares${counter}" class="form-control">
                    </div>
                    <div class="col-12 col-md-6 col-lg-3">
                        <label style="display:block;" class="form-label">&nbsp;</label>
                        <button type="button" class="btn btn-danger deleteBtn" data-row-id="extraRow${counter}">Delete</button>
                    </div>
                </div>
                `;

                // Append the new row to the div
                $('#addedExtraseatDiv').append(newRow);
                
                const seatSelect = $(`#seatNo${counter}`); // Target the new seat select element
                seatSelect.empty();
                for (let i = 1; i <= maxSeats; i++) {
                    seatSelect.append(`<option value="${i}">${i}</option>`);
                }

                // Reinitialize Select2 for the new row
                $(`#seatClass${counter}`).select2();
                
                $(`#seatNo${counter}`).SumoSelect({ 
                    okCancelInMulti: true ,
                    triggerChangeCombined: true,
                    forceCustomRendering: true  
                });

                updateSeatClassUniqueness();
                updateSeatNoUniqueness();

                // Increment the counter
                counter++;
            });

            // Delete functionality
            $(document).on('click', '.deleteBtn', function () {
                const rowId = $(this).data('row-id');
                $(`#${rowId}`).remove(); // Remove the row
                updateSeatClassUniqueness();
                updateSeatNoUniqueness();
            });

            $('#fleet_id').on('change', function () {
                const fleetId = $(this).val(); // Get the selected fleet_id value

                const fleetData = <?php echo json_encode($fleet_types); ?>;

                const selectedFleet = fleetData.find(fleet => fleet.id == fleetId);

                if (selectedFleet) {
                    maxSeats = selectedFleet.total_seat;
                }
                /* const seatSelect = $('#seatNo0');

                // Destroy the existing SumoSelect
                seatSelect[0].sumo.unload(); 

                // Clear and append new options
                seatSelect.empty();
                seatSelect.append('<option value="" disabled selected>None</option>');
                for (let i = 1; i <= maxSeats; i++) {
                    seatSelect.append(`<option value="${i}">${i}</option>`);
                }

                // Reinitialize SumoSelect
                seatSelect.SumoSelect({ placeholder: 'Select Seats', csvDispCount: 3 }); */
                $(".seatNo").each(function (index) {
                    var $select = $(this);

                    // Destroy existing SumoSelect instance if initialized
                    if ($select.hasClass("SumoUnder")) {
                        $select[0].sumo.unload(); // Properly remove SumoSelect
                    }

                    $select.empty(); // Clear existing options
                    //$select.append('<option value="" disabled selected>None</option>'); // Default option

                    for (var i = 1; i <= maxSeats; i++) {
                        $select.append('<option value="' + i + '">' + i + '</option>');
                    }

                    // Reinitialize SumoSelect
                    $select.SumoSelect({ 
                        okCancelInMulti: true ,
                        triggerChangeCombined: true,
                        forceCustomRendering: true  
                    });
                });

            });

            // Function to Update seatClass Uniqueness
            function updateSeatClassUniqueness() {
                const selectedClasses = new Set();

                // Collect all selected seatClass values
                $('.seatClass').each(function() {
                    const selectedValue = $(this).val();
                    if (selectedValue) {
                        selectedClasses.add(selectedValue);
                    }
                });

                // Loop through all seatClass dropdowns to disable selected options
                $('.seatClass').each(function() {
                    $(this).find('option').each(function() {
                        if (selectedClasses.has($(this).val()) && !$(this).is(':selected')) {
                            $(this).prop('disabled', true);
                        } else {
                            $(this).prop('disabled', false);
                        }
                    });
                    $(this).select2(); // Reinitialize Select2 to update options
                });
            }

            // Function to Update seatNo Uniqueness
            function updateSeatNoUniqueness() {
                const selectedSeats = new Set();

                // Collect all selected seat numbers
                $('.seatNo').each(function() {
                    const selected = $(this).val();
                    if (selected) {
                        selected.forEach(seat => selectedSeats.add(seat));
                    }
                });

                // Loop through all seatNo dropdowns to disable selected options
                $('.seatNo').each(function() {
                    const currentSelect = $(this);
                    const currentSelected = currentSelect.val() || [];

                    currentSelect.find('option').each(function() {
                        const optionValue = $(this).val();
                        if (optionValue && selectedSeats.has(optionValue) && !currentSelected.includes(optionValue)) {
                            $(this).prop('disabled', true);
                        } else {
                            $(this).prop('disabled', false);
                        }
                    });

                    // Destroy existing SumoSelect instance if initialized
                    if (currentSelect.hasClass('SumoUnder')) {
                        currentSelect[0].sumo.unload(); // Properly remove SumoSelect
                    }

                    // Reinitialize SumoSelect
                   /*  currentSelect.SumoSelect({ 
                        placeholder: 'Select Seats', 
                        csvDispCount: 3,
                        okCancelInMulti: true
                    }); */

                    currentSelect.SumoSelect({ okCancelInMulti: true ,
                        triggerChangeCombined: true,
                        forceCustomRendering: true  
                    });
                });
            }

            // Initial call for the first row
            updateSeatClassUniqueness();
            updateSeatNoUniqueness();

            // Event Listener for seatClass change
            $(document).on('change', '.seatClass', function() {
                updateSeatClassUniqueness();
            });

            $(document).on('click', '.SumoSelect .btnOk', function() {
                updateSeatNoUniqueness();
            });
        });
    </script>
    
<script>
function addfielddateoff() {
    var html = '<div class="row mb-2" style="margin-right: -100%;">';
    html += '<div class="col-12 col-md-6 col-lg-4 text-end date datepicker">';
    html += '<input type="text" class="form-control" name="addDateoff[]" onchange="updateOffdatesField()" placeholder="select date" readonly required />';
    html += '<div class="input-group-addon"></div>';
    html += '</div>';
    html += '<div class="col-12 col-md-6 col-lg-2">';
    html += '<a class="btn btn-danger mt-1 text-white" onclick="removerow(this)"><b>&times;</b></a>';
    html += '</div>';
    html += '</div>';
    $("#dateoffinput").append(html);
    // Only initialize datepicker for new fields
    $("#dateoffinput .datepicker input:not([disabled])").datepicker({
        format: 'yyyy-mm-dd',
        autoclose: true,
        todayHighlight: true,
        startDate: 'today'
    });
}
function removerow(el) {
    $(el).closest('.row').remove();
    updateOffdatesField();
}
function updateOffdatesField() {
    var dates = [];
    $('input[name="addDateoff[]"]').each(function() {
        if ($(this).val()) {
            dates.push($(this).val());
        }
    });
    $('#offdates').val(dates.join(','));
}
$(document).ready(function(){
    $('.datepicker input, .datepicker').datepicker({
        format: 'yyyy-mm-dd',
        autoclose: true,
        todayHighlight: true,
        startDate: 'today'
    });
    $('input[name="addDateoff[]"]:not([disabled])').each(function() {
        $(this).datepicker({
            format: 'yyyy-mm-dd',
            autoclose: true,
            todayHighlight: true,
            startDate: 'today'
        });
    });
    updateOffdatesField();
    $(document).on('change', 'input[name="addDateoff[]"]', updateOffdatesField);
});
</script>
<script>
    // --- Off Date Ranges Logic for Edit Page ---
    // Parse existing JSON from PHP
    var offDateRanges = [];
    <?php if (!empty($trip->offdateranges)): ?>
        try {
            offDateRanges = JSON.parse('<?= addslashes($trip->offdateranges) ?>');
        } catch(e) { offDateRanges = []; }
    <?php endif; ?>

    // Render the list of ranges
    function updateOffDateRangesList(){
        let html = '';
        offDateRanges.forEach(function(r, idx){
            html += `<div>
                <span>${r.start} to ${r.end}</span>
                <button type="button" class="btn btn-sm btn-danger ms-2" onclick="removeOffDateRange(${idx})">&times;</button>
            </div>`;
        });
        $('#offDateRangesList').html(html);
        $('#offdateranges').val(JSON.stringify(offDateRanges));
    }

    // Remove a range by index
    function removeOffDateRange(idx){
        offDateRanges.splice(idx, 1);
        updateOffDateRangesList();
    }

    let editIndex = null; // Global: -1 for add, number for edit
    function bmodelClose(){
        let start = $('#daysInRangeStart').val();
        let end = $('#daysInRangeEnd').val();
        if(start && end){
            let startDate = new Date(start);
            let endDate = new Date(end);
            if (new Date(end) <= new Date(start)) {
                alert('End date must be greater than start date.');
                return;
            }
            // Check for exact duplicate (ignore current index if editing)
        let isDuplicate = offDateRanges.some(function(range, index) {
            return index !== editIndex && range.start === start && range.end === end;
        });

        if (isDuplicate) {
            alert('This exact date range already exists.');
            return;
        }

        // Check for overlapping ranges (ignore current index if editing)
        let isOverlapping = offDateRanges.some(function(range, index) {
            if (index === editIndex) return false;
            let existingStart = new Date(range.start);
            let existingEnd = new Date(range.end);
            return startDate <= existingEnd && endDate >= existingStart;
        });

        if (isOverlapping) {
            alert('The selected date range overlaps with an existing range.');
            return;
        }

        // If editing, update the range
        if (editIndex !== null) {
            offDateRanges[editIndex] = { start: start, end: end };
            editIndex = null; // Reset
        } else {
            // If adding, push new range
            offDateRanges.push({ start: start, end: end });
        }
            // offDateRanges.push({start: start, end: end});
            updateOffDateRangesList();
        }
        $("#offdateinrange").modal("hide");
        $('#daysInRangeStart').val('');
        $('#daysInRangeEnd').val('');
    }

    // Show modal
    function offdateinrange() {
        $("#offdateinrange").modal("show");
    }

    // On form submit, ensure hidden input is updated
    $('form').on('submit', function() {
        updateOffDateRangesList();
    });

    // On page load, show existing ranges
    $(function(){
        updateOffDateRangesList();
    });
</script>
<?php echo $this->endSection() ?>