@extends('counter_manager.layouts.app')
@section('panel')
    <div class="row">
        <div class="col-xl-5 col-lg-12">
            <div class="card">
                <form action="{{ route('counter.manager.booked', $trip->id) }}" class="mt-2" id="booking-form" method="POST">
                    @csrf
                    <div class="card-body">
                        <input type="hidden" name="price" value="{{ $price ? number_format($price, 2, '.', '') : null }}" />
                        <input type="hidden" name="seat_number" />

                        <h5 class=" text-center">@lang('Passenger Details')</h5>

                        <div class="form-group">
                            <label>@lang('Date of Journey')</label>
                            <input name="date_of_journey" type="text" class="form-control" value="{{ showDateTime($trip->start_time, 'm/d/Y') }}" required readonly>
                        </div>
                        <div class="form-group">
                            <label>@lang('Pickup Point')</label>
                            <select class="form-control select2" name="pick_up_point" required @readonly(true)>
                                <option selected value="">@lang('Select One')</option>
                                @foreach ($stoppages as $stoppage)
                                    <option value="{{ $stoppage->id }}" @selected($stoppage->id == $from)>{{ __($stoppage->name) }} - {{ __($stoppage?->city?->name) }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="form-group">
                            <label>@lang('Dropping Point')</label>
                            <select class="select2 form-control" name="dropping_point" required>
                                <option selected value="">@lang('Select One')</option>
                                @foreach ($stoppages as $stoppage)
                                    <option value="{{ $stoppage->id }}" @selected($stoppage->id == $to && $price > 0)>{{ __($stoppage->name) }} - {{ __($stoppage?->city?->name) }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="form-group">
                            <label>@lang('Boarding Point')</label>
                            <select class="select2 form-control" name="boarding_point" required>
                                <option selected value="">@lang('Select One')</option>
                                @foreach ($stoppages as $stoppage)
                                    <option value="{{ $stoppage->id }}">{{ __($stoppage->name) }} - {{ __($stoppage?->city?->name) }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="booked-seat-details my-3 d-none">
                            <label>@lang('Selected Seats')</label>
                            <ul class="list-group seat-details-animate">
                                <li class="list-group-item bg--primary">@lang('Seat Details')</li>
                            </ul>
                        </div>
                        <div class="form-group">
                            <label>@lang('Mobile Number')</label>
                            <input type="text" name="mobile_number" class="form-control" required autocomplete="off" />
                        </div>
                        <div class="form-group">
                            <label>@lang('Name')</label>
                            <input type="text" name="name" class="form-control" autocomplete="off" required />
                        </div>
                        <div class="form-group">
                            <label>@lang('Email')</label>
                            <input type="email" name="email" class="form-control" autocomplete="off">
                        </div>
                        <div class="form-group mb-0">
                            <label>@lang('Gender')</label>
                            <div class="d-flex align-items-center flex-wrap gap-3">
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="gender" id="male" value="1" required>
                                    <label class="form-check-label" for="male">@lang('Male')</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="gender" id="female" required value="2">
                                    <label class="form-check-label" for="female">@lang('Female')</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="gender" id="other" required value="0">
                                    <label class="form-check-label" for="other">@lang('Others')</label>
                                </div>
                            </div>
                        </div>
                        <input type="hidden" name="book_user_id">
                        <input type="hidden" name="book_user_type">
                    </div>
                    <div class="card-footer">
                        <button type="submit" class="btn btn--primary w-100 h-45" formtarget="_blank">@lang('Book')</button>
                    </div>
                </form>
            </div>
        </div>
        <div class="col-xl-7 col-lg-12 text-center">
            @include('partials.vehicle_seat_layout')
        </div>
    </div>

    <div class="modal fade" id="modelId">
        <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">@lang('Ticket Prices: Stoppage to Stoppage')</h5>
                    <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
                        <i class="las la-times"></i>
                    </button>
                </div>
                <div class="modal-body">
                    <ul class="list-group list-group-flush">
                        @foreach ($ticketPrices as $item)
                            @if ($item->price > 0 && empty(array_diff($item->source_destination, $stoppageIds)))
                                @php
                                    $stoppageInfo = getStoppageInfo($item->source_destination);
                                @endphp
                                <li class="list-group-item d-flex justify-content-between align-items-center">
                                    {{ $stoppageInfo[0]->name }} - {{ $stoppageInfo[1]->name }}
                                    <span class="fw-bolder">
                                        {{ showAmount($item->price, currencyFormat: false) }}{{ gs('cur_sym') }}
                                    </span>
                                </li>
                            @endif
                        @endforeach
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="alertModal">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-body text-center">
                    <i class="las la-times-circle f-size--100 text--danger mb-15"></i>
                    <h5 class="text--danger mb-15 error-message"></h5>
                    <button type="button" class="btn btn--danger closeModal">
                        @lang('Continue')
                    </button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="bookConfirm">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">@lang('Confirm Booking')</h5>
                    <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
                        <i class="las la-times"></i>
                    </button>
                </div>
                <div class="modal-body">
                    <p>@lang('Are you sure to book these seats?')</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn--primary" id="confirm-book">@lang('Yes')</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="helpModal">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">@lang('How to book a ticket?')</h5>
                    <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
                        <i class="las la-times"></i>
                    </button>
                </div>
                <div class="modal-body">
                    <h5 class="text--info mb-2">@lang('Check off days before booking')</h5>
                    <ul class="list-group list-group-flush">
                        <li class="list-group-item d-flex justify-content-between">
                            @lang('Step 1') <span>@lang('Select date of journey')</span>
                        </li>
                        <li class="list-group-item d-flex justify-content-between">
                            @lang('Step 2') <span>@lang('Select pickup point')</span>
                        </li>
                        <li class="list-group-item d-flex justify-content-between">
                            @lang('Step 3') <span>@lang('Select dropping point')</span>
                        </li>
                        <li class="list-group-item d-flex justify-content-between">
                            @lang('Step 4') <span>@lang('Select one or more seats')</span>
                        </li>
                        <li class="list-group-item d-flex justify-content-between">
                            @lang('Step 5') <span>@lang('Fill up passenger\'s details')</span>
                        </li>
                        <li class="list-group-item d-flex justify-content-between">
                            @lang('Step 6') <span>@lang('Click or tap on book button')</span>
                        </li>
                        <li class="list-group-item d-flex justify-content-between">
                            @lang('Step 7') <span> <i class="la la-print"></i> @lang('Ticket')</span>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
@endsection

@push('breadcrumb-plugins')
    <button type="button" class="btn btn-sm btn--primary ticketPriceBtn">
        @lang('Ticket Price List') <i class="lar la-list-alt"></i>
    </button>

    <button type="button" class="btn btn--info btn-sm helpBtn">
        @lang('Help') <i class="las la-question-circle"></i>
    </button>
@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('script')
    <script>
        'use strict';

        (function($) {
            let minYear = parseInt(moment().format('YYYY'), 10);
            const allStoppages = @json($stoppages);

            $('input[name="date_of_journey"]').daterangepicker({
                singleDatePicker: true,
                showDropdowns: true,
                minYear: minYear,
                maxYear: minYear + 20,
                minDate: moment()
            });

            $('.closeModal').on('click', function() {
                $('#alertModal').modal('hide');
            });

            $('.ticketPriceBtn').on('click', function() {
                $('#modelId').modal('show');
            });

            $('.helpBtn').on('click', function() {
                $('#helpModal').modal('show');
            });

            var booked_seats = @json($bookedTickets);

            $.each(booked_seats, function(i, book) {
                let title = `${book.pickup?.name} To ${book.drop?.name}`;
                let genderClass = 'booked-others';
                let gender = (book.user_id > 0) ? book.user?.gender : book.guest_user?.gender;
                if (gender == 1) {
                    genderClass = 'booked';
                } else if (gender == 2) {
                    genderClass = 'booked-female';
                }
                $.each(book.seats, function(index, seat) {
                    $(`.seat-btn[value="${seat}"]`).addClass(genderClass).attr('disabled',
                        'disabled').attr('title', `${title}`);
                });
            });


            $(document).on('click', '.seat-btn', function() {
                var pick_up_point = $('select[name="pick_up_point"]').val();
                var dropping_point = $('select[name="dropping_point"]').val();
                if (pick_up_point && dropping_point) {
                    $(this).toggleClass('selected');
                    var seats = $('.selected').map((_, el) => el.value).get();
                    var price = $('input[name=price]').val();
                    var seat_data =
                        `<li class="list-group-item d-flex justify-content-between fw-bolder"> Deck - Seat <span>@lang('Price')</span></li>`;
                    if (seats.length > 0) {
                        $('.booked-seat-details').removeClass('d-none');
                        $.each(seats, function(i, v) {
                            seat_data +=
                                `<li class="list-group-item d-flex justify-content-between"> ${v} <span class="text--indigo">${price}</span></li>`;
                        });
                        seat_data +=
                            `<li class="list-group-item d-flex justify-content-between fw-bold"> Subtotal <span>${(seats.length * price).toFixed(2)}</span></li>`;
                        $('.booked-seat-details .list-group').html(seat_data);
                    } else {
                        $('.booked-seat-details .list-group').html('');
                        $('.booked-seat-details').addClass('d-none');
                    }
                    $('input[name=seat_number]').val(seats);
                } else {
                    var modal = $('#alertModal');
                    modal.find('.error-message').text(
                        "{{ trans('Please select pickup point and dropping point before select any seat') }}"
                    );
                    modal.modal('show');
                }
            });

            $(document).on('change', 'select[name="pick_up_point"], select[name="dropping_point"], input[name="date_of_journey"]', function(e) {
                resetSeat();
                var date = $('input[name="date_of_journey"]').val();
                var sourceId = $('select[name="pick_up_point"]').find("option:selected").val();
                var destinationId = $('select[name="dropping_point"]').find("option:selected").val();

                $('select[name="boarding_point"]').val('');

                if (sourceId == destinationId && destinationId != '') {
                    var modal = $('#alertModal');
                    modal.find('.error-message').text(
                        "{{ trans('Source Point and Destination Point Must Not Be Same') }}");
                    modal.modal('show');
                    $('select[name="pick_up_point"]').val('').trigger('change');
                    $('select[name="dropping_point"]').val('').trigger('change');
                    return false;
                } else if (sourceId != destinationId) {

                    var routeId = '{{ $trip->route->id }}';
                    var fleetTypeId = '{{ $trip->fleetType->id }}';

                    if (sourceId && destinationId) {
                        getprice(routeId, fleetTypeId, sourceId, destinationId, date)
                    }
                }
            });

            function resetSeat() {
                $(`.single-row`).find('.seat-btn').removeClass('booked-others booked booked-female selected').removeAttr('disabled').removeAttr('title');
                $('input[name=seat_number]').val('');
                $('.booked-seat-details .list-group').html('');
                $('.booked-seat-details').addClass('d-none');
            }



            function fillBookedSeats(response) {
                $.each(response.booked_seats, function(i, book) {
                    let title = `${book.pickup?.name} To ${book.drop?.name}`;
                    let genderClass = 'booked-others';
                    let gender = (book.user_id > 0) ? book.user?.gender : book.guest_user?.gender;
                    if (gender == 1) {
                        genderClass = 'booked';
                    } else if (gender == 2) {
                        genderClass = 'booked-female';
                    }
                    $.each(book.seats, function(index, seat) {
                        $(`.seat-btn[value="${seat}"]`).addClass(genderClass).attr('disabled',
                            'disabled').attr('title', `${title}`);
                    });
                });
            }

            $('#alertModal').on('hidden.bs.modal', event => {
                $('select[name="dropping_point"]').val('');
                $('.select2-basic').select2({
                    dropdownParent: $('.card-body form')
                });
            });

            $(document).on('submit', '#booking-form', function(e) {
                var modal = $('#bookConfirm');
                e.preventDefault();
                let seat = $("input[name='seat_number']").val();
                if (seat == "") {
                    notify("error", ["Please select at least one seat"])
                } else {
                    modal.modal('show');
                }
            });

            $(document).on('click', '#confirm-book', function(e) {
                var modal = $('#bookConfirm');
                modal.modal('hide');
                $('#booking-form').attr('target', '_blank');
                document.getElementById("booking-form").submit();
            });

            $('#booking-form').on('submit', function(e) {
                setTimeout(() => {
                    window.location.reload();
                }, 3000);
            });

            function getprice(routeId, fleetTypeId, sourceId, destinationId, date) {
                var data = {
                    "trip_id": '{{ $trip->id }}',
                    "vehicle_route_id": routeId,
                    "fleet_type_id": fleetTypeId,
                    "source_id": sourceId,
                    "destination_id": destinationId,
                    "date": date,
                }

                $.ajax({
                    type: "get",
                    url: "{{ route('counter.manager.ticket.get-price') }}",
                    data: data,
                    success: function(response) {

                        if (response.error) {
                            var modal = $('#alertModal');
                            modal.find('.error-message').text(response.error);
                            modal.modal('show');
                        } else {
                            var stoppages = response.stoppages;
                            var req_source = response.req_source;
                            var req_destination = response.req_destination;

                            req_source = stoppages.indexOf(req_source.toString());
                            req_destination = stoppages.indexOf(req_destination.toString());

                            var title = ``;
                            $.each(response.bookedSeats, function(i, book) {
                                var booked_source = book.pickup_point; //Booked
                                var booked_destination = book.dropping_point; //Booked

                                let title = `${book.pickup?.name} To ${book.drop?.name}`;
                                let genderClass = 'booked-others';
                                let gender = (book.user_id > 0) ? book.user?.gender : book.guest_user?.gender;
                                if (gender == 1) {
                                    genderClass = 'booked';
                                } else if (gender == 2) {
                                    genderClass = 'booked-female';
                                }

                                booked_source = stoppages.indexOf(booked_source.toString());
                                booked_destination = stoppages.indexOf(booked_destination
                                    .toString());

                                if (req_destination <= booked_source || req_source >=
                                    booked_destination) {
                                    $.each(book.seats, function(index, val) {
                                        $(`.seat-btn[value="${val}"]`).removeClass(genderClass).removeAttr('disabled').removeAttr('title');
                                    });
                                } else {
                                    $.each(book.seats, function(index, val) {
                                        $(`.seat-btn[value="${val}"]`).addClass(genderClass).attr('disabled', 'disabled').attr('title', `${title}`);
                                    });
                                }
                            });

                            if (response.price.error) {
                                var modal = $('#alertModal');
                                modal.find('.error-message').text(response.price.error);
                                modal.modal('show');
                            } else {
                                $('input[name=price]').val(parseInt(response.price).toFixed(2));
                            }
                        }
                    }
                });
            }

            $(`[name="mobile_number"]`).on('focusout', function() {
                const search = $(this).val();
                let id = '';
                let type = '';
                let name = '';
                let email = '';
                let gender = '';
                $.ajax({
                    type: "get",
                    url: "{{ route('counter.manager.booking.user') }}",
                    data: {
                        search: search
                    },
                    success: function(response) {
                        if (response.registeredUser) {
                            let user = response.registeredUser;
                            id = user.id;
                            type = "user";
                            name = user.firstname + ' ' + user.lastname;
                            email = user.email;
                            gender = user.gender;
                        } else if (response.guestUser) {
                            let user = response.guestUser;
                            id = user.id;
                            type = "guest";
                            name = user.name;
                            email = user.email;
                            gender = user.gender;
                        }
                        $('input[name="book_user_id"]').val(id);
                        $('input[name="book_user_type"]').val(type);
                        $('input[name="name"]').val(name);
                        $('input[name="email"]').val(email);
                        $('input[name="gender"][value="' + gender + '"]').prop('checked', ((gender == '') ? false : true));
                    }
                });
            });

            $(`select[name="boarding_point"]`).on('change', function() {
                const pickupPoint = $(`select[name="pick_up_point"]`).val();
                const droppingPoint = $(`select[name="dropping_point"]`).val();
                const boardingPoint = $(this).val();

                if (pickupPoint && droppingPoint && boardingPoint) {
                    const pickupIndex = allStoppages.findIndex(stop => stop.id == pickupPoint);
                    const boardingIndex = allStoppages.findIndex(stop => stop.id == boardingPoint);
                    const droppingIndex = allStoppages.findIndex(stop => stop.id == droppingPoint);
                    if (pickupIndex > boardingIndex) {
                        notify('error', "@lang('Boarding point must be after or equal to the pickup point.')");
                        $(this).val("");
                    } else if (boardingIndex >= droppingIndex) {
                        notify('error', "@lang('Boarding point must be before to the dropping point.')");
                        $(this).val("");
                    }
                } else {
                    notify('error', "@lang('First, Select pickup point & dropping point')");
                    $(this).val("");
                }
            });

        })(jQuery);
    </script>
@endpush
