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





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



    <style>

        .trip-group {

            display: flex;

            align-items: center;

            font-weight: bold;

            padding: 8px;

            background-color: #f8f9fa;

            border-radius: 5px;

            margin-bottom: 5px;

        }



        .subtrip-container {

            margin-left: 20px;

            padding-left: 10px;

            border-left: 2px solid #ccc;

            max-height: 150px; /* Set a max height for scrolling */

            overflow-y: auto;

        }



        #tripContainer {

            max-height: 300px; /* Set a height for scrolling */

            overflow-y: auto;

            padding: 10px;

            border: 1px solid #ddd;

            border-radius: 5px;

            background-color: #fff;

        }



        /* Style checkboxes */

        input[type="checkbox"] {

            margin-right: 8px;

            transform: scale(1.2);

            cursor: pointer;

        }



    </style>

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

    

    <div class="card mb-4">

        <div class="card-body">



            <form action="<?php echo base_url(route_to('create-offer')) ?>" id="offerform" method="post" class="row g-3" accept-charset="utf-8" enctype="multipart/form-data">

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

                <div class="row justify-content-center">

                    <div class="col-12 col-md-6 col-lg-4">

                        <div class="row">



                            <?php if ($roleId == 1): ?>

                                <div class="col-12 mt-3">

                                    <label for="company_name"><?php echo lang("Localize.select_company") ?><abbr title="<?php echo lang("Localize.required_field") ?>">*</abbr></label>

                                    <select name="company[]" id="company" class="form-control" multiple>

                                        <option value="" disabled selected><?php echo lang("Localize.none") ?></option>

                                        <?php foreach ($companies as $companyvalue) : ?>

                                            <option value="<?php echo $companyvalue->id ?>"><?php echo $companyvalue->name ?></option>

                                        <?php endforeach ?>

                                    </select>

                                </div>

                            <?php elseif ($roleId == 7): ?>

                                <input type="hidden" name="company[]" value="<?= $companyId ?>" />

                            <?php endif; ?>



                            <!-- Type is always online, so we'll use hidden field -->

                            <input type="hidden" name="offer_type" value="1">



                            <div class="col-12 mt-3">

                                <label for="code" class=""><?php echo lang("Localize.offer") ?> <?php echo lang("Localize.code") ?></label>

                                <input type="text" id="code" name="code" class="form-control" required />

                            </div>



                            <div class="col-12 mt-3">

                                <label for="offer_title" class=""><?php echo lang("Localize.offer_title") ?> <abbr title="<?php echo lang("Localize.required_field") ?>">*</abbr></label>

                                <input type="text" id="offer_title" name="offer_title" class="form-control" required />

                            </div>



                            <div class="col-12 mt-3">

                                <label for="offer_description" class=""><?php echo lang("Localize.offer_description") ?></label>

                                <textarea class="form-control" name="offer_description" id="offer_description" rows="3"></textarea>

                            </div>



                            <div class="col-12 mt-3" id="payment_method">

                                <label for="subtrip_id">

                                    <?php echo lang("Localize.sub") ?> <?php echo lang("Localize.trip") ?>

                                </label>



                                <div class="col-12 mt-3" id="tripContainer"></div>

                            </div>





                            <?php if ($roleId == 7): ?>

                                <div class="col-12 mt-3" id="tripContainer">

                                    <?php foreach ($tripGroups as $trip) : ?>

                                        <div class="trip-group">

                                            <label>

                                            <input type="checkbox" class="main-trip" name="main_trips[]" value="<?= $trip->id ?>" data-trip-id="<?= $trip->id ?>" />

                                                <strong><?= $trip->picklocation ?> ➔ <?= $trip->droplocation ?><?php echo "( ". $trip->id. " )" ?></strong>

                                            </label>

                                            <ul>

                                                <?php foreach ($trip->children as $subtrip) : ?>

                                                    <li>

                                                        <input type="checkbox" class="sub-trip" 

                                                            data-parent-id="<?= $trip->id ?>" 

                                                            name="subtrips[<?= $trip->id ?>][]" 

                                                            value="<?= $subtrip->id ?>" />

                                                        <?= $subtrip->picklocation ?> ➔ <?= $subtrip->droplocation ?>

                                                    </li>

                                                <?php endforeach; ?>

                                            </ul>

                                        </div>

                                    <?php endforeach; ?>

                                </div>

                            <?php endif; ?>



                            <div class="col-12 mt-3">

                                <label for="start_date" class="form-label"><?php echo lang("Localize.offer_start_date") ?> <abbr title="<?php echo lang("Localize.required_field") ?>">*</abbr></label>

                                <div class="input-append date datepicker" id="start_date" data-date-format="yyyy-mm-dd">

                                    <input size="16" type="text" name="start_date" class="form-control will-fill-by-plugin" required readonly />

                                    <span class="add-on"><i class="icon-th"></i></span>

                                </div>

                            </div>



                            <div class="col-12 mt-3">

                                <label for="end_date" class="form-label"><?php echo lang("Localize.offer_end_date") ?> <abbr title="<?php echo lang("Localize.required_field") ?>">*</abbr></label>

                                <div class="input-append date datepicker" id="end_date" data-date-format="yyyy-mm-dd">

                                    <input size="16" type="text" name="end_date" class="form-control will-fill-by-plugin" required readonly />

                                    <span class="add-on"><i class="icon-th"></i></span>

                                </div>

                            </div>



                            <div class="col-12 mt-3">

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

                                <div class="input-append date datepicker" id="booking_start_date" data-date-format="yyyy-mm-dd">

                                    <input size="16" type="text" name="booking_start_date" class="form-control will-fill-by-plugin" readonly />

                                    <span class="add-on"><i class="icon-th"></i></span>

                                </div>

                            </div>



                            <div class="col-12 mt-3">

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

                                <div class="input-append date datepicker" id="booking_end_date" data-date-format="yyyy-mm-dd">

                                    <input size="16" type="text" name="booking_end_date" class="form-control will-fill-by-plugin" readonly />

                                    <span class="add-on"><i class="icon-th"></i></span>

                                </div>

                            </div>



                            <div class="col-12 mt-3">

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

                                <div class="input-append date datepicker" id="travel_start_date" data-date-format="yyyy-mm-dd">

                                    <input size="16" type="text" name="travel_start_date" class="form-control will-fill-by-plugin" readonly />

                                    <span class="add-on"><i class="icon-th"></i></span>

                                </div>

                            </div>



                            <div class="col-12 mt-3">

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

                                <div class="input-append date datepicker" id="travel_end_date" data-date-format="yyyy-mm-dd">

                                    <input size="16" type="text" name="travel_end_date" class="form-control will-fill-by-plugin" readonly />

                                    <span class="add-on"><i class="icon-th"></i></span>

                                </div>

                            </div>



                            <div class="col-12 mt-3">

                                <label for="min_passengers" class=""><?php echo lang("Localize.minimum_passengers") ?></label>

                                <input type="number" id="min_passengers" name="min_passengers" class="form-control" min="1" value="1" />

                            </div>

                            <div class="col-12 mt-3" >

                                <label for="discount_type"><?php echo lang("Localize.discount_type") ?> <abbr title="<?php echo lang("Localize.required_field") ?>">*</abbr></label>

                                <select class="form-select" name="discount_type" id="discount_type" required onchange="getDiscountType()">

                                   <option value=""><?php echo lang("Localize.select") ?></option>

                                   <option value='1'><?php echo lang("Localize.fixed_amount") ?> (₹)</option>

                                   <option value='2'><?php echo lang("Localize.percentage") ?> (%)</option>

                                </select>

                            </div>

                            <div class="col-12 mt-3">

                                <label for="discount" class=""><?php echo lang("Localize.discount_value") ?> <span id='partype'></span> <abbr title="<?php echo lang("Localize.required_field") ?>">*</abbr></label>

                                <input type="number" id="discount" name="discount" value="<?php echo esc(old('discount')) ?>" class="form-control" placeholder="<?php echo lang("Localize.enter_discount_value") ?>" min="0" required />

                            </div>

                            <div class="col-12 mt-3" id="discount_cap_section" style="display: none;">

                                <label for="discount_cap" class=""><?php echo lang("Localize.maximum_discount_cap") ?> (₹)</label>

                                <input type="number" id="discount_cap" name="discount_cap" class="form-control" min="0" placeholder="<?php echo lang("Localize.maximum_discount_amount") ?>" />

                            </div>

                            <div class="col-12 mt-3" id="min_discount_section" style="display: none;">

                                <label for="min_discount" class=""><?php echo lang("Localize.minimum_discount") ?> (₹)</label>

                                <input type="number" id="min_discount" name="min_discount" class="form-control" min="0" placeholder="<?php echo lang("Localize.minimum_discount_amount") ?>" />

                            </div>

                            <div class="col-12 mt-3" id="max_discount_section" style="display: none;">

                                <label for="max_discount" class=""><?php echo lang("Localize.maximum_discount") ?> (₹)</label>

                                <input type="number" id="max_discount" name="max_discount" class="form-control" min="0" placeholder="<?php echo lang("Localize.maximum_discount_amount") ?>" />

                            </div>



                            <div class="col-12 mt-3">

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

                                <input type="file" id="offer_image" name="offer_image" class="form-control" accept="image/*" />

                                <small class="form-text text-muted"><?php echo lang("Localize.upload_offer_image") ?></small>

                            </div>



                            <div class="col-12 mt-3">

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

                                <select class="form-select" name="seat_class[]" id="seat_class" multiple>

                                    <?php // foreach ($seatClasses as $seatClass): ?>

                                        <!--<option value="<?php //echo $seatClass->id; ?>"><?php //echo esc($seatClass->name); ?></option>-->

                                    <?php //endforeach; ?>

                                </select>

                                <small class="form-text text-muted"><?php echo lang("Localize.select_seat_classes") ?></small>

                            </div>



                            <div class="col-12 mt-3">

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

                                <select class="form-select" name="trip_category[]" id="trip_category" multiple>

                                    <?php foreach ($tripCategories as $tripCategory): ?>

                                        <option value="<?php echo $tripCategory->id; ?>"><?php echo esc($tripCategory->name); ?></option>

                                    <?php endforeach; ?>

                                </select>

                                <small class="form-text text-muted"><?php echo lang("Localize.select_trip_categories") ?></small>

                            </div>



                            <div class="col-12 mt-3">

                                <label for="condition" class="form-label"><?php echo lang("Localize.terms_conditions") ?> <abbr title="<?php echo lang("Localize.required_field") ?>">*</abbr></label>

                                <textarea class="form-control" name="condition" id="condition" rows="3" required><?php echo old('condition') ?></textarea>

                            </div>



                            <div class="text-danger">

                                <?php if (isset($validation)) : ?>

                                    <?= $validation->listErrors(); ?>

                                <?php endif ?>

                            </div>



                            <div class="col-12 mt-3">

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

                            </div>

                        </div>

                    </div>

                </div>

            </form>

        </div>

    </div>



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

    <script src="<?php echo base_url('public/js/jquery.sumoselect.min.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>

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

<script>

    function getDiscountType() {

        var discountType = document.getElementById('discount_type').value;

        if(discountType == 1){

            $("#partype").html(" (₹)");

            $('#discount').attr('placeholder', "<?php echo lang("Localize.enter_discount_amount_in_currency") ?>");

            $('#discount_cap_section').hide();

            $('#min_discount_section').hide();

            $('#max_discount_section').hide();

        }else if(discountType == 2){

            $("#partype").html(" (%)");

            $('#discount').attr('placeholder', "<?php echo lang("Localize.enter_discount_percentage") ?>");

            $('#discount_cap_section').show();

            $('#min_discount_section').show();

            $('#max_discount_section').show();

        }else{

            $("#partype").html("");

            $('#discount').attr('placeholder', "<?php echo lang("Localize.enter_discount_value") ?>");

            $('#discount_cap_section').hide();

            $('#min_discount_section').hide();

            $('#max_discount_section').hide();

        }

    }



    $(document).ready(function () {

        // Initialize SumoSelect for seat class and trip category

        // $('#seat_class').SumoSelect();
        window.seatClassSumo = $('#seat_class').SumoSelect();


        $('#trip_category').SumoSelect();



        // Auto-select all sub-trips when main trip is selected

        $(document).on('change', '.main-trip', function () {

            const tripId = $(this).data('trip-id');

            $(`.sub-trip[data-parent-id="${tripId}"]`).prop('checked', $(this).prop('checked'));
            
            updateSeatClassFilter();


        });



        // Check main trip if any sub-trip is selected

        $(document).on('change', '.sub-trip', function () {

            const tripId = $(this).data('parent-id');

            // If at least one sub-trip is checked, check the main trip

            const anySubChecked = $(`.sub-trip[data-parent-id="${tripId}"]:checked`).length > 0;

            $(`.main-trip[data-trip-id="${tripId}"]`).prop('checked', anySubChecked);
            
            updateSeatClassFilter();


        });
        
        function updateSeatClassFilter() {

            // Get all checked subtrip IDs

            const checkedSubtrips = [];

            $('.sub-trip:checked').each(function() {

                checkedSubtrips.push($(this).val());

            });

            // If no subtrips selected, don't make AJAX call

            if (checkedSubtrips.length === 0) {

                return;

            }

            // Make AJAX call to get seat classes using GET method

            // Build URL with query parameters

            var url = '<?php echo base_url(route_to("get-seat-classes-by-subtrips")) ?>';

            // Convert array to comma-separated string for GET request

            var subtripIdsParam = checkedSubtrips.join(',');

            url += '?subtrip_ids=' + encodeURIComponent(subtripIdsParam);

            

            $.ajax({

                url: url,

                type: 'GET',

                dataType: 'json',

                success: function(response) {

                    // Get the seat_class select element

                    const $seatClassSelect = $('#seat_class');

                    

                    // Get the original select element (SumoSelect wraps it)

                    var $originalSelect = $('#seat_class');

                    // Unload SumoSelect first to access the original select

                    try {

                        if (window.seatClassSumo && window.seatClassSumo.sumo) {

                            var currentlySelected = window.seatClassSumo.sumo.val() || [];

                            // Unload SumoSelect to access original select

                            window.seatClassSumo.sumo.unload();

                            // Get the original select element again

                            $originalSelect = $('#seat_class');

                            

                            if (response.success && response.seat_classes && response.seat_classes.length > 0) {

                                // Clear all existing options

                                $originalSelect.empty();

                                

                                // Add seat classes from the response (replace with only these)

                                response.seat_classes.forEach(function(seatClass) {

                                    const seatClassId = seatClass.id.toString();

                                    const option = $('<option></option>')

                                        .attr('value', seatClassId)

                                        .text(seatClass.name);

                                    $originalSelect.append(option);

                                });

                                

                                // Reinitialize SumoSelect with new options

                                window.seatClassSumo = $originalSelect.SumoSelect();

                                

                                // Restore previously selected values if they still exist in the new options

                                let validSelections = [];

                                if (currentlySelected.length > 0) {

                                    validSelections = currentlySelected.filter(function(val) {

                                        return $originalSelect.find('option[value="' + val + '"]').length > 0;

                                    });

                                }

                                

                                // Set selected values if any are valid

                                if (validSelections.length > 0 && window.seatClassSumo && window.seatClassSumo.sumo) {

                                    window.seatClassSumo.sumo.val(validSelections);

                                }

                            } else {

                                // If no seat classes, clear the select

                                $originalSelect.empty();

                                

                                // Reinitialize SumoSelect with empty options

                                window.seatClassSumo = $originalSelect.SumoSelect();

                            }

                        } else {

                            // If SumoSelect instance not found, just work with the select directly

                            if (response.success && response.seat_classes && response.seat_classes.length > 0) {

                                $originalSelect.empty();

                                

                                response.seat_classes.forEach(function(seatClass) {

                                    const seatClassId = seatClass.id.toString();

                                    const option = $('<option></option>')

                                        .attr('value', seatClassId)

                                        .text(seatClass.name);

                                    $originalSelect.append(option);

                                });

                                

                                // Initialize SumoSelect if not already initialized

                                if (!window.seatClassSumo) {

                                    window.seatClassSumo = $originalSelect.SumoSelect();

                                } else {

                                    window.seatClassSumo.sumo.reload();

                                }

                            }

                        }

                    } catch(e) {

                        console.log('Error updating seat class filter:', e);

                        // Fallback: try to reinitialize everything

                        try {

                            var $select = $('#seat_class');

                            if (window.seatClassSumo && window.seatClassSumo.sumo) {

                                window.seatClassSumo.sumo.unload();

                            }

                            

                            if (response.success && response.seat_classes && response.seat_classes.length > 0) {

                                $select.empty();

                                response.seat_classes.forEach(function(seatClass) {

                                    const seatClassId = seatClass.id.toString();

                                    $select.append($('<option></option>').attr('value', seatClassId).text(seatClass.name));

                                });

                            }

                            

                            window.seatClassSumo = $select.SumoSelect();

                        } catch(e2) {

                            console.log('Fallback initialization failed:', e2);

                        }

                    }

                    // The else case is already handled in the main try block above

                },

                error: function(xhr, status, error) {

                    console.error('Error fetching seat classes:', error);

                    if (xhr.status === 403) {

                        alert('CSRF token validation failed. Please refresh the page and try again.');

                    } else {

                        console.error('Response:', xhr.responseText);

                    }

                }

            });

        }

    });



</script>

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

