@extends('admin.layouts.app')

@section('panel')
    <div class="row mb-none-30">
        <div class="col-xl-12 col-lg-12 col-md-12 mb-30">
            <div class="card">
                <h5 class="card-header">@lang('Information About Trip') </h5>
                <div class="card-body">
                    @if(!isset($trip))
                    <div class="d-flex gap-2 mb-4 flex-sm-nowrap flex-wrap">
                        <div class="flex-grow-1">
                            <select name="trip_id" class="select2 w-100 fo" required>
                                <option value="">@lang('Select a trip')</option>
                                @foreach ($trips as $copyTrip)
                                    <option value="{{ $copyTrip }}">{{ __($copyTrip->title) }}</option>
                                @endforeach
                            </select>
                        </div>
                        <button class="btn btn--primary copyTrip flex-shirnk-0 flex-grow-1 flex-sm-grow-0 h-45" id="basic-addon2">@lang('Clone Trip for New Trip')</button>
                    </div>
                    @endif
                    <form action="{{ route('admin.trip.store', $trip->id ?? '') }}" method="POST">
                        @csrf
                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label> @lang('Title')</label>
                                    <input type="text" class="form-control" name="title" value="{{ old('title', $trip->title ?? '') }}" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label> @lang('Fleet Type')</label>
                                    <select name="fleet_type_id" class="select2" required>
                                        <option value="">@lang('Select an option')</option>
                                        @foreach ($fleetTypes as $item)
                                            <option value="{{ $item->id }}" data-vehicles="{{ $item->vehicles }}" data-name="{{ $item->name }}">
                                                {{ __($item->name) }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label> @lang('Route')</label>
                                    <select name="vehicle_route_id" class="select2" required>
                                        <option value="">@lang('Select an option')</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 }}" @selected(old('vehicle_route_id', $trip->vehicle_route_id ?? '') == $route->id)> {{ __($route->name) }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label> @lang('Start From')</label>
                                    <select name="start_from" class="select2" data-minimum-results-for-search="-1"  required></select>
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="mb-0"> @lang('End To')</label>
                                    <select name="end_to" class="select2" required data-minimum-results-for-search="-1" ></select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label> @lang('Start Time')</label>
                                    <input type="search" name="start_time" class="form-control date-range" value="{{ old('start_time', $trip->start_time ?? '') }}" required autocomplete="off">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label> @lang('Expected End Time')</label>
                                    <input type="search" name="expected_end_time" class="form-control date-range" value="{{ old('expected_end_time', $trip->expected_end_time ?? '') }}" required autocomplete="off">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label> @lang('Vehicle')</label>
                                    <select class="select2 form-control" name="vehicle_id">
                                        <option value="">@lang('Select an option')</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>@lang('Driver')</label>
                                    <select class="select2 from-control" name="driver_id">
                                        <option selected value="">@lang('Select One')</option>
                                        @foreach ($drivers as $driver)
                                            <option value="{{ $driver->id }}" @selected(old('driver_id', $trip->driver_id ?? '') == $driver->id)>
                                                {{ __($driver->fullname) }} {{ $driver->trips()->where('id', '!=', $trip->id ?? '')->active()->first() ? '*' : null }}
                                            </option>
                                        @endforeach
                                    </select>
                                    <div class="mt-2">
                                        <small class="text-warning">
                                            <i class="la la-warning la-lg"></i>
                                            <strong>*</strong> @lang('Indicates the driver is currently assigned to an active trip.')
                                        </small>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>@lang('Supervisor')</label>
                                    <select class="select2 form-control" name="supervisor_id">
                                        <option selected value="">@lang('Select One')</option>
                                        @foreach ($supervisors as $supervisor)
                                            <option value="{{ $supervisor->id }}" @selected(old('supervisor_id', $trip->supervisor_id ?? '') == $supervisor->id)>
                                                {{ __($supervisor->fullname) }} {{ $supervisor->trips()->where('id', '!=', $trip->id ?? '')->active()->first() ? '*' : null }}
                                            </option>
                                        @endforeach
                                    </select>
                                    <div class="mt-2">
                                        <small class="text-warning">
                                            <i class="la la-warning la-lg"></i>
                                            <strong>*</strong> @lang('Indicates the supervisor is currently assigned to an active trip.')
                                        </small>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>@lang('Status')</label>
                                    <select class="select2 form-control" name="status" data-minimum-results-for-search="-1" required>
                                        <option value="{{ Status::TRIP_INITIATED }}" @selected((old('status', ($trip->status ?? ''))) == Status::TRIP_INITIATED)>@lang('Initiated')</option>
                                        <option value="{{ Status::TRIP_RUNNING }}" @selected((old('status', ($trip->status ?? ''))) == Status::TRIP_RUNNING)>@lang('Running')</option>
                                        <option value="{{ Status::TRIP_COMPLETED }}" @selected((old('status', ($trip->status ?? ''))) == Status::TRIP_COMPLETED)>@lang('Completed')</option>
                                        <option value="{{ Status::TRIP_CANCELED }}" @selected((old('status', ($trip->status ?? ''))) == Status::TRIP_CANCELED)>@lang('Cancel')</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6 tripCompletedArea {{ ((old('status', ($trip->status ?? ''))) == Status::TRIP_COMPLETED) ? '' : 'd-none' }}">
                                <div class="form-group">
                                    <label> @lang('End Time')</label>
                                    <input type="search" name="end_time" class="form-control date-range" value="{{ old('end_time', $trip->end_time ?? '') }}" autocomplete="off" required>
                                </div>
                            </div>
                            <div class="col-md-6 tripRunningArea {{ ((old('status', ($trip->status ?? ''))) == Status::TRIP_RUNNING) ? '' : 'd-none' }}">
                                <div class="form-group">
                                    <label> @lang('Running Time')</label>
                                    <input type="search" name="running_time" class="form-control date-range" value="{{ old('running_time', $trip->running_time ?? '') }}" autocomplete="off" required>
                                </div>
                            </div>
                            <div class="col-md-6 cancelReasonArea {{ ((old('status', ($trip->status ?? ''))) == Status::TRIP_CANCELED) ? '' : 'd-none' }}">
                                <div class="form-group">
                                    <label>@lang('Cancel Reason')</label>
                                    <textarea name="cancel_reason" class="form-control cancel_reason" rows="2" maxlength="255" required>{{ old('cancel_reason', $trip->cancel_reason ?? '') }}</textarea>
                                </div>
                            </div>
                        </div>
                        <button type="submit" class="btn btn--primary h-45 w-100 submit-button">@lang('Submit')</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
@endsection
@push('breadcrumb-plugins')
    <x-back route="{{ route('admin.trip.index') }}" />
@endpush

@push('script-lib')
    <script src="{{ asset('assets/global/js/moment.min.js') }}"></script>
    <script src="{{ asset('assets/global/js/daterangepicker.min.js') }}"></script>
@endpush

@push('style-lib')
    <link rel="stylesheet" type="text/css" href="{{ asset('assets/global/css/daterangepicker.css') }}">
@endpush

@push('style')
<style>
@media screen and (max-width: 767px) {
    span.value-change-button i {
    transform: rotate(90deg);
}

}
.value-change-button {
    padding: 0px 10px;
    border-radius: 5px;
}
</style>
@endpush

@push('script')
    <script>
        "use strict";

        (function($) {
            @if($trip ?? false)
                $('select[name=fleet_type_id]').val({{ old('fleet_type_id', $trip->fleet_type_id) }}).trigger('change');
                $('select[name=vehicle_route_id]').val({{ old('vehicle_route_id', $trip->vehicle_route_id) }}).trigger('change');
                vehicleOptions('{{ old('vehicle_id', $trip->vehicle_id) }}');
                startEndPoint();
            @endif
            $('#end_time, #running_time, #cancel_reason').prop('required', false);

            $('select[name="vehicle_route_id"]').on('change', function() {
                startEndPoint();
                checkTicketPrice();
            });

            async function vehicleOptions(oldVehicleId = 0) {
                const vehicles = $('select[name="fleet_type_id"]').find(':selected').data('vehicles');
                let options = `<option value="">@lang('Select an option')</option>`;

                let existsIds = await getExistsVehicleIds();
                vehicles.forEach(vehicle => {
                    if (existsIds?.includes(vehicle.id)) return;
                    options += `<option value="${vehicle.id}" ${oldVehicleId == vehicle.id ? 'selected' : null}>@lang('${vehicle.vehicle_no}') (@lang('${vehicle.register_no}'))</option>`
                });
                $(`select[name="vehicle_id"]`).html(options).trigger('change');
            }

            $('select[name="fleet_type_id"]').on('change', function() {
                checkTicketPrice();
                makeTitle();
                vehicleOptions('{{ old('vehicle_id', $trip->vehicle_id ?? NULL) }}');
            });


            function checkTicketPrice() {
                var fleetTypeId = $('select[name="fleet_type_id"]').val();
                var RouteId = $('select[name="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,
                        },
                        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);
                    });
                }
            }

            $('select[name="status"]').on('change', function() {
                let endTime = $('#end_time');
                let runningTime = $('#running_time');
                let cancelReason = $('#cancel_reason');
                endTime.val('');
                runningTime.val('');
                $('.tripCompletedArea').addClass('d-none');
                $('.tripRunningArea').addClass('d-none');
                $('.cancelReasonArea').addClass('d-none');
                if($(this).val() == '{{ Status::TRIP_COMPLETED }}') {
                    $('.tripCompletedArea').removeClass('d-none');
                } else if($(this).val() == '{{ Status::TRIP_RUNNING }}') {
                    $('.tripRunningArea').removeClass('d-none');
                } else if($(this).val() == '{{ Status::TRIP_CANCELED }}') {
                   $('.cancelReasonArea').removeClass('d-none');
                }
                endTime.prop('required', $(this).val() == '{{ Status::TRIP_COMPLETED }}');
                runningTime.prop('required', $(this).val() == '{{ Status::TRIP_RUNNING }}');
                cancelReason.prop('required', $(this).val() == '{{ Status::TRIP_CANCELED }}');
            });


            function startEndPoint()
            {
                let source = $('select[name="vehicle_route_id"]').find("option:selected").data('source');
                let source_id = $('select[name="vehicle_route_id"]').find("option:selected").data('source_id');
                let destination = $('select[name="vehicle_route_id"]').find("option:selected").data('destination');
                let destination_id = $('select[name="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>`;
                $('select[name="start_from"]').html(fromOption).trigger('change');
                $('select[name="end_to"]').html(endOption).trigger('change');
            }

            const datePicker = $('.date-range').daterangepicker({
                singleDatePicker: true,
                autoUpdateInput: false,
                locale: {
                    cancelLabel: 'Clear',
                    format: 'YYYY-MM-DD H:mm'
                },
                showDropdowns: true,
                timePicker: true,
                timePicker24Hour: true,
                timePickerIncrement: 1
            });

            const changeDatePickerText = (event, selectedDate) => {
                $(event.target).val(selectedDate.format('YYYY-MM-DD H:mm'));
            }

            $('.date-range').on('apply.daterangepicker', (event, picker) => {
                changeDatePickerText(event, picker.startDate);
                makeTitle();
            });

            if ($('.date-range').val()) {
                let selectedDate = $('.date-range').val();
                $('.date-range').data('daterangepicker').setStartDate(new Date(selectedDate));
            }

            $('.copyTrip').on('click', function () {
                const trip = JSON.parse($('#trip_id').val());
                $('select[name=fleet_type_id]').val(trip.fleet_type_id).trigger('change');
                $('select[name=vehicle_route_id]').val(trip.vehicle_route_id).trigger('change');
                vehicleOptions(trip.vehicle_id);
                startEndPoint();
                $('input[name="start_time"]').val(trip.start_time);
                $('input[name="expected_end_time"]').val(trip.expected_end_time);
                $('select[name="vehicle_id"]').val(trip.vehicle_id).trigger('change');
                $('select[name="driver_id"]').val(trip.driver_id).trigger('change');
                $('select[name="supervisor_id"]').val(trip.supervisor_id).trigger('change');
                $('select[name="status"]').val(trip.status).trigger('change');
                $('input[name="title"]').val(trip.title);
            })

            function getTime(dateTime) {
                let time = '';
                if (typeof moment !== 'undefined') {
                    time = moment(dateTime, 'YYYY-MM-DD HH:mm:ss').format('hh:mm A');
                } else {
                    let normalizedTime = dateTime.replace(' ', 'T');
                    let dateObj = new Date(normalizedTime);

                    if (!isNaN(dateObj.getTime())) {
                        time = dateObj.toLocaleTimeString([], {
                            hour: '2-digit',
                            minute: '2-digit',
                            hour12: true,
                        });
                    }
                }
                return time;
            }


            $('select[name="vehicle_route_id"]').on('change', function() {
                makeTitle();

            });

            function makeTitle() {
                let data1 = $('select[name="fleet_type_id"]').find("option:selected").data('name');
                let data2 = $('select[name="vehicle_route_id"]').find("option:selected").data('name');
                let data3 = $('select[name="start_from"]').find("option:selected").data('name');
                let data4 = $('select[name="end_to"]').find("option:selected").data('name');
                let startTime = $('input[name="start_time"]').val();
                let expectedEndTime = $('input[name="expected_end_time"]').val();
                let data = [];
                let title = '';

                if (data1 != undefined) data.push(data1);

                if (data2 != undefined) data.push(data2);

                if (data3 != undefined) data.push(data3);

                if (data4 != undefined) data.push(data4);

                $.each(data, function(index, value) {
                    if (index > 0) {
                        title += index > 3 ? ' to ' : ' - ';
                    }
                    title += value;
                });
                if(startTime != '') {
                    title += ' - ' + formatDateTime(startTime);
                }
                if(expectedEndTime != '') {
                    title += ' - ' + formatDateTime(expectedEndTime);
                }
                $('input[name="title"]').val(title);
            }

            function formatDateTime(dateTimeString) {
                let date = new Date(dateTimeString);

                let hours = date.getHours();
                let minutes = date.getMinutes();
                let ampm = hours >= 12 ? 'pm' : 'am';

                hours = hours % 12 || 12;
                minutes = minutes.toString().padStart(2, '0');

                return `${hours}:${minutes} ${ampm}`;
            }


            function getExistsVehicleIds() {
                const formData = {
                    fleet_type_id: $('select[name="fleet_type_id"]').val(),
                    start_time: $('input[name="start_time"]').val(),
                    expected_end_time: $('input[name="expected_end_time"]').val(),
                    id: '{{ $trip->id ?? "" }}',
                    _token: '{{ csrf_token() }}',
                }
                return new Promise((resolve, reject) => {
                    $.ajax({
                        type: "POST",
                        url: "{{ route('admin.trip.exists.vehicles') }}",
                        data: formData,
                        success: function (existsIds) {
                            resolve(existsIds);
                        },
                        error: function (xhr, status, error) {
                            reject(error);
                        }
                    });
                });
            }


        })(jQuery)
    </script>
@endpush
