@extends('admin.layouts.app')
@section('panel')
    <div class="row">
        <div class="col-md-12">
            <div class="alert alert-primary alert-custom p-3" role="alert">
                <p>
                    <i class="la la-info-circle la-lg"></i>
                    @lang('Using a ')
                    <a href="{{ route('admin.cron.index') }}">@lang('cron job‌')</a>,
                    @lang('advanced trips will be automatically created each day based on the')
                    <a href="{{ route('admin.setting.general') }}">@lang('‘Trip Generation Days’')</a>
                    @lang('set in the general settings.')
                </p>
            </div>
        </div>
        <div class="col-md-12">
            <div class="card">
                <div class="card-body p-0">
                    <div class="table-responsive--sm table-responsive">
                        <table class="table table--light style--two">
                            <thead>
                                <tr>
                                    <th>@lang('Fleet Type')</th>
                                    <th>@lang('Route')</th>
                                    <th>@lang('AC / Non-AC')</th>
                                    <th>@lang('From')</th>
                                    <th>@lang('To')</th>
                                    <th>@lang('Day Off')</th>
                                    <th>@lang('Status')</th>
                                    <th>@lang('Action')</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse($tripSchedules as $tripSchedule)
                                    <tr>
                                        <td>{{ __($tripSchedule?->fleetType?->name ?? '--') }}</td>
                                        <td>{{ __($tripSchedule?->route?->name ?? '--') }}</td>
                                        <td>{{ __($tripSchedule?->fleetType?->has_ac == Status::ENABLE ? 'AC' : 'Non-Ac') }}</td>
                                        <td>{{ __($tripSchedule?->startFrom?->name ?? '--') }}</td>
                                        <td>{{ __($tripSchedule?->endTo?->name ?? '--') }}</td>
                                        <td>
                                            @if ($tripSchedule?->day_off)
                                                @foreach ($tripSchedule?->day_off as $day)
                                                    {{ showDayOff($day) }}@if (!$loop->last)
                                                        ,
                                                    @endif
                                                @endforeach
                                            @else
                                                @lang('No Off Day')
                                            @endif
                                        </td>

                                        <td>@php echo $tripSchedule->statusBadge; @endphp </td>
                                        <td>
                                            <div class="button--group">
                                                <button type="button" class="btn btn-sm btn-outline--primary cuModalBtn"
                                                    data-resource="{{ $tripSchedule }}" data-modal_title="@lang('Edit Trip Schedule')">
                                                    <i class="la la-pencil"></i>@lang('Edit')
                                                </button>

                                                @if (!$tripSchedule->status)
                                                    <button type="button"
                                                        class="btn btn-sm btn-outline--success confirmationBtn"
                                                        data-action="{{ route('admin.trip.schedules.status', $tripSchedule->id) }}"
                                                        data-question="@lang('Are you sure to enable this trip schedule?')">
                                                        <i class="la la-eye"></i>@lang('Enable')
                                                    </button>
                                                @else
                                                    <button type="button"
                                                        class="btn btn-sm btn-outline--danger  confirmationBtn"
                                                        data-action="{{ route('admin.trip.schedules.status', $tripSchedule->id) }}"
                                                        data-question="@lang('Are you sure to disable this trip schedule?')">
                                                        <i class="la la-eye-slash"></i>@lang('Disable')
                                                    </button>
                                                @endif
                                            </div>
                                        </td>
                                    </tr>
                                    @empty
                                        <tr>
                                            <td class="text-muted text-center" colspan="100%">{{ __($emptyMessage) }}</td>
                                        </tr>
                                    @endforelse
                                </tbody>
                            </table>
                        </div>
                    </div>

                    @if ($tripSchedules->hasPages())
                        <div class="card-footer py-4">
                            {{ paginateLinks($tripSchedules) }}
                        </div>
                    @endif
                </div>
            </div>
        </div>

        <x-confirmation-modal />

        <div id="cuModal" class="modal fade" tabindex="-1" role="dialog">
            <div class="modal-dialog modal-xl" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title"></h5>
                        <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
                            <i class="las la-times"></i>
                        </button>
                    </div>
                    <form action="{{ route('admin.trip.schedules.store') }}" method="POST">
                        @csrf
                        <div class="modal-body">
                            <div id="overlay">
                                <div class="cv-spinner">
                                    <span class="spinner"></span>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-lg-4 col-md-6">
                                    <div class="form-group">
                                        <label>@lang('Fleet Type')</label>
                                        <select class="select2 form-control" name="fleet_type_id" required>
                                            <option selected value="">@lang('Select One')</option>
                                            @foreach ($fleetTypes as $fleetType)
                                                <option value="{{ $fleetType->id }}" data-name="{{ $fleetType->name }}"
                                                    @checked(old('fleet_type_id'))>
                                                    {{ __($fleetType->name) }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                </div>
                                <div class="col-lg-4 col-md-6">
                                    <div class="form-group ">
                                        <label>@lang('Route')</label>
                                        <select class="select2 form-control" name="vehicle_route_id" required>
                                            <option selected value="">@lang('Select One')</option>
                                            @foreach ($routes as $route)
                                                <option value="{{ $route->id }}" data-name="{{ $route->name }}"
                                                    data-source_id="{{ $route->start_from }}"
                                                    data-source="{{ $route?->startFrom?->name }}"
                                                    data-destination_id="{{ $route?->end_to }}"
                                                    data-destination="{{ $route?->endTo?->name }}" @checked(old('vehicle_route_id'))>
                                                    {{ __($route->name) }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                </div>
                                <div class="col-lg-4 col-md-12">
                                    <div class="form-group">
                                        <label>@lang('Day Off')</label>
                                        <select class="form-control select2-auto-tokenize" multiple="multiple"
                                            name="day_off[]">
                                            <option value="0" @selected(in_array('0', old('day_off', [])))>@lang('Sunday')</option>
                                            <option value="1" @selected(in_array('1', old('day_off', [])))>@lang('Monday')</option>
                                            <option value="2" @selected(in_array('2', old('day_off', [])))>@lang('Tuesday')</option>
                                            <option value="3" @selected(in_array('3', old('day_off', [])))>@lang('Wednesday')</option>
                                            <option value="4" @selected(in_array('4', old('day_off', [])))>@lang('Thursday')</option>
                                            <option value="5" @selected(in_array('5', old('day_off', [])))>@lang('Friday')</option>
                                            <option value="6" @selected(in_array('6', old('day_off', [])))>@lang('Saturday')</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>@lang('From')</label>
                                        <select class="form-control from_to" name="start_from" value="{{ old('start_from') }}" required></select>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>@lang('To')</label>
                                        <select class="form-control from_to" name="end_to" value="{{ old('end_to') }}" required></select>
                                    </div>
                                </div>
                                <div class="col-md-12 tripScheduleTimeSlot">
                                    <h6 class="title">@lang('Trip Time Slots')</h6>
                                    <div class="row">
                                        <div class="col-lg-4 col-md-6">
                                            <div class="form-group ">
                                                <label>@lang('Start Time')</label>
                                                <select class="select2 form-control" name="start_time[]" required>
                                                    <option selected value="">@lang('Select One')</option>
                                                    @foreach ($timeSlots as $slot)
                                                        <option value="{{ $slot->time }}"
                                                            data-name="{{ showDateTime($slot->time, 'h:i a') }}"
                                                            @checked(old('start_time'))>
                                                            {{ showDateTime($slot->time, 'h:i a') }}
                                                        </option>
                                                    @endforeach
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-xl-6 col-lg-5 col-md-6">
                                            <div class="form-group">
                                                <label>@lang('Expected End Time')</label>
                                                <div class="time-input-group-wrapper">
                                                    <div class="input-group">
                                                        <input type="number" class="form-control" name="expected_end_hour[]" value="" required autocomplete="off">
                                                        <span class="input-group-text" id="basic-addon1">@lang('Hours')</span>
                                                    </div>
                                                    <div class="input-group">
                                                        <input type="number" class="form-control" name="expected_end_minute[]" value="" autocomplete="off">
                                                        <span class="input-group-text" id="basic-addon1">@lang('Minutes')</span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-xl-2 col-lg-3 mt-lg-1">
                                            <button type="button" class="btn btn--primary h-45 w-100 mt-lg-4 addMoreTimeSlot"><i class="las la-plus"></i>@lang('Add More')</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="submit" class="btn h-45 w-100 btn--primary submit-button">@lang('Submit')</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
@endsection

@push('breadcrumb-plugins')
    <button type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasFilter" aria-controls="offcanvasFilter"  class="btn btn--primary showFilterBtn btn-sm">
        <i class="las la-filter"></i>
        @lang('Filter')
    </button>
    <button type="button" class="btn btn-outline--primary cuModalBtn" data-modal_title="@lang('Add New Trip Schedule')">
        <i class="las la-plus"></i> @lang('Add New')
    </button>

    <div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasFilter" aria-labelledby="offcanvasFilterLabel">
        <div class="offcanvas-header">
            <h5 id="offcanvasFilterLabel">@lang('Filter')</h5>
            <button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
        </div>
        <div class="offcanvas-body">
            <form>
                <div class="gap-5">
                    <div class="form-group">
                        <label for="fleet_type">@lang('Fleet Type')</label>
                        <select class="select2 form-control" id="fleet_type" name="fleet_type_id">
                            <option selected value="">@lang('All')</option>
                            @foreach ($fleetTypes as $fleetType)
                                <option value="{{ $fleetType->id }}" @checked(request('fleet_type_id'))>
                                    {{ __($fleetType->name) }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="form-group ">
                        <label for="vehicle_route">@lang('Route')</label>
                        <select class="select2 form-control" name="vehicle_route_id" id="vehicle_route">
                            <option selected value="">@lang('All')</option>
                            @foreach ($routes as $route)
                                <option value="{{ $route->id }}" @selected($route->id == request('vehicle_route_id'))>
                                    {{ __($route->name) }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="from">@lang('Start From')</label>
                        <select class="form-control select2" name="start_from" id="from" value="{{ request('start_from') }}">
                            <option value="">@lang('All')</option>
                            @foreach ($stoppages as $stoppage)
                                <option value="{{ $stoppage->id }}" @selected($stoppage->id == request('start_from'))> {{ __($stoppage->name) }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="to">@lang('End To')</label>
                        <select class="form-control select2" name="end_to" id="to" value="{{ request('end_to') }}">
                            <option selected value="">@lang('All')</option>
                            @foreach ($stoppages as $stoppage)
                                <option value="{{ $stoppage->id }}" @checked($stoppage->id == request('end_to'))> {{ __($stoppage->name) }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="form-group ">
                        <label for="startTime">@lang('Start Time')</label>
                        <select class="select2 form-control" name="start_time[]" id="startTime" multiple required>
                            @foreach ($timeSlots as $slot)
                                <option value="{{ $slot->time }}"
                                    data-name="{{ showDateTime($slot->time, 'h:i a') }}"
                                    @selected(in_array($slot->time, request('start_time', [])))>
                                    {{ showDateTime($slot->time, 'h:i a') }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    <div class="form-group">
                        <label>@lang('Status')</label>
                        <select class="form-control select2" name="status" value="{{ request('status') }}">
                            <option value="" >@lang('All')</option>
                            <option value="{{ Status::ENABLE }}" @selected(Status::ENABLE == request('status'))>@lang('Enabled')</option>
                            <option value="{{ Status::DISABLE }}" @selected(Status::DISABLE == request('status') && request('status') != '')>@lang('Disabled')</option>
                        </select>
                    </div>
                    <div class="form-group d-flex justify-content-between mb-0">
                        <button type="reset" class="btn btn--danger w-25 resetBtn"><i class="fas fa-time"></i>@lang('Reset')</button>
                        <button type="submit" class="btn btn--primary w-75 ms-2"><i class="fas fa-filter"></i>@lang('Filter')</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
@endpush

@push('script-lib')
    <script src="{{ asset('assets/admin/js/cu-modal.js') }}"></script>
@endpush

@push('script')
    <script>
        'use strict';
        (function($) {
            let id = 1;
            $('#vehicle_route_id').on('change', function() {
                let source = $('#vehicle_route_id').find("option:selected").data('source');
                let source_id = $('#vehicle_route_id').find("option:selected").data('source_id');
                let destination = $('#vehicle_route_id').find("option:selected").data(
                    'destination');
                let destination_id = $('#vehicle_route_id').find("option:selected").data(
                    'destination_id');
                let fromOption =
                    `<option value="${source_id ?? ''}" data-name="${source ?? ''}" selected>${source ?? ''}</option>`;
                let endOption = `<option value="${destination_id ?? ''}" data-name="${destination ?? ''}" selected>${destination ?? ''}</option>`;
                setTimeout(() => {
                    $('#start_from').html(fromOption).trigger('change');
                    $('#end_to').html(endOption).trigger('change');
                }, 500);

                checkTicketPrice();
            });

            $('#fleet_type_id').on('change', function() {
                checkTicketPrice();
            });

            function checkTicketPrice() {
                var fleetTypeId = $('#fleet_type_id').val();
                var RouteId = $('#vehicle_route_id').val();

                if (fleetTypeId != '' && RouteId != '') {
                    $("#overlay").fadeIn(300);
                    $.ajax({
                        type: "get",
                        url: "{{ route('admin.fare.ticket.check') }}",
                        data: {
                            fleet_type_id : fleetTypeId,
                            vehicle_route_id : RouteId,
                            type : 'schedule'
                        },
                        success: function(response) {
                            if (response.error) {
                                notify('error', response.error);
                                $('.submit-button').prop('disabled', true);
                            } else {
                                $('.submit-button').prop('disabled', false);
                            }
                        }
                    }).done(function() {
                        setTimeout(function() {
                            $("#overlay").fadeOut(300);
                        }, 500);
                    });
                }
            }


            $('.addMoreTimeSlot').on('click', function() {
                const timeSlot = `<div class="row">
                        <div class="col-lg-4 col-md-4">
                            <div class="form-group ">
                                <label for="start_time${id}">@lang('Start Time') <span class="text-danger">*</span></label>
                                <select class="select2 form-control" name="start_time[]" required id="start_time${id}">
                                    <option selected value="">@lang('Select One')</option>
                                    @foreach ($timeSlots as $slot)
                                        <option value="{{ $slot->time }}"
                                            data-name="{{ showDateTime($slot->time, 'h:i a') }}">
                                            {{ showDateTime($slot->time, 'h:i a') }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                        <div class="col-xl-6 col-lg-5 col-md-6">
                            <div class="form-group">
                                <label>@lang('Expected End Time')<span class="text-danger">*</span></label>
                                <div class="time-input-group-wrapper">
                                    <div class="input-group">
                                        <input type="number" class="form-control" name="expected_end_hour[]" value="" required autocomplete="off">
                                        <span class="input-group-text" id="basic-addon1">@lang('Hours')</span>
                                    </div>
                                    <div class="input-group">
                                        <input type="number" class="form-control" name="expected_end_minute[]" value="" autocomplete="off">
                                        <span class="input-group-text" id="basic-addon1">@lang('Minutes')</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-2 col-md-2 mt-1">
                            <button type="button" class="btn btn--danger h-45 w-100 mt-4 removeTimeSlot"><i class="las la-times"></i>@lang('Remove')</button>
                        </div>
                    </div>`;
                $('.tripScheduleTimeSlot').append(timeSlot).find(`#start_time${id}`).select2({
                    dropdownParent: $(this)
                });
                id++;
            });

            $(document).on('click', '.removeTimeSlot', function() {
                $(this).closest('.row').remove();
            });

            $(document).on("click", ".cuModalBtn", function () {
                $('.tripScheduleTimeSlot .row').not(':first').remove();
                const tripScheduleTimeSlots = $(this).data().resource?.trip_schedule_time_slots;
                if (tripScheduleTimeSlots != undefined && tripScheduleTimeSlots.length > 0) {
                    tripScheduleTimeSlots.forEach(function(tripScheduleTimeSlot, index) {
                        if (index == 0) {
                            const startTimeSelect = $('.tripScheduleTimeSlot').find('select[name="start_time[]"]');
                            startTimeSelect.val(tripScheduleTimeSlot.start_time).trigger('change');
                            $('.tripScheduleTimeSlot').find('input[name="expected_end_hour[]"]').val(tripScheduleTimeSlot.expected_end_hour);
                            $('.tripScheduleTimeSlot').find('input[name="expected_end_minute[]"]').val(tripScheduleTimeSlot.expected_end_minute);
                        } else {
                            const timeSlot = `<div class="row">
                                <div class="col-lg-4 col-md-4">
                                    <div class="form-group">
                                        <label for="start_time${index}${id}">@lang('Start Time') <span class="text-danger">*</span></label>
                                        <select class="form-control" name="start_time[]" id="start_time${index}${id}" required>
                                            <option selected value="">@lang('Select One')</option>
                                            @foreach ($timeSlots as $slot)
                                                <option value="{{ $slot->time }}"
                                                        data-name="{{ showDateTime($slot->time, 'h:i a') }}">
                                                    {{ showDateTime($slot->time, 'h:i a') }}
                                                </option>
                                            @endforeach
                                        </select>
                                    </div>
                                </div>
                                <div class="col-xl-6 col-lg-5 col-md-6">
                                    <div class="form-group">
                                        <label>@lang('Expected End Time')</label>
                                        <div class="time-input-group-wrapper">
                                            <div class="input-group">
                                                <input type="number" class="form-control" name="expected_end_hour[]" value="${tripScheduleTimeSlot.expected_end_hour}" required autocomplete="off">
                                                <span class="input-group-text" id="basic-addon1">@lang('Hours')</span>
                                            </div>
                                            <div class="input-group">
                                                <input type="number" class="form-control" name="expected_end_minute[]" value="${tripScheduleTimeSlot.expected_end_minute}" autocomplete="off">
                                                <span class="input-group-text" id="basic-addon1">@lang('Minutes')</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-lg-2 col-md-2 mt-1">
                                    <button type="button" class="btn btn--danger h-45 w-100 mt-4 removeTimeSlot"><i class="las la-times"></i>@lang('Remove')</button>
                                </div>
                            </div>`;

                            $('.tripScheduleTimeSlot').append(timeSlot);
                            $('.tripScheduleTimeSlot').children().last().find('select[name="start_time[]"]').val(tripScheduleTimeSlot.start_time);
                            const lastStartTime = $('.tripScheduleTimeSlot').children().last();
                            lastStartTime.find(`#start_time${index}${id}`).select2({
                                dropdownParent: lastStartTime
                            });
                        }
                    });
                }

            });

        })(jQuery)
    </script>
@endpush
@push('style')
    <style>
        .tripScheduleTimeSlot {
            margin-top: 12px;
        }

        .tripScheduleTimeSlot .title {
            margin-bottom: 10px;
            padding-bottom: 10px;
            color: #000000;
            border-bottom: 1px solid #dee2e6;
        }

        .time-input-group-wrapper {
            display: flex;
            flex-wrap: wrap;
            align-items: center;
        }

        .time-input-group-wrapper .input-group {
            width: 50%;
        }

        .time-input-group-wrapper .input-group:first-child .input-group-text {
            border-top-right-radius: 0;
            border-bottom-right-radius: 0;
            border-right: 0;
            border-left: 0;
        }
        .time-input-group-wrapper .input-group:last-child .input-group-text {
            border-left: 0;
        }
        .time-input-group-wrapper .input-group:last-child input {
             border-top-left-radius: 0;
            border-bottom-left-radius: 0;
        }

        @media (max-width: 991px) {
            .time-input-group-wrapper .input-group input {
                padding: 10px;
            }
            .time-input-group-wrapper .input-group .input-group-text {
                padding: 8px;
            }
        }
    </style>
@endpush
