{{-- Constants & Controls --}}
<script>
  //* Constants
    window.decrypt_data = "4ar51-e3067mnt-r35e-rv35-95b1";

  //* Data Controls
    // On window unload
    window.onbeforeunload = function() {
        localStorage.removeItem("isOverBooking");
        localStorage.removeItem("ReservationData");
    };

  //* General Control
    $(document).ready(function () {
        // On close Reservation form
        $('#reservation_ballot').on('hide.bs.modal', function () {
            document.activeElement.blur();
        });
    });
</script>

{{-- Reservation Controls --}}
<script>
  //* Modal Form Control
    function showModalForm(reservation_id) {
        $(`#reservation_ballot`).modal('hide');
        loadReserveForm(reservation_id);
    }

    function setAsNoShow(defer_message, reservation_id, no_show_type) {
        Swal.fire({
            icon: 'warning',
            title: defer_message,
            confirmButtonText: "{{ __('common_actions')['approve'] }} {{ __('common_actions')['accept'] }}",
            confirmButtonColor: `#0d6889`,
            showCancelButton: true,
            cancelButtonText: `{{ __('common_actions')['cancel'] }}`,
            cancelButtonColor: `#c82333`
        }).then((result) => {
            if (result.value) {
                $.ajax({
                    url: `/home/reservation/${reservation_id}/${no_show_type}/no-show`,
                    headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
                    type: 'DELETE',
                    success: function (data) {
                      // Success Message
                        Swal.fire({
                            toast: true, position: 'top-end',
                            showConfirmButton: false,
                            timer: 2500, timerProgressBar: true,
                            title: "{{ __('common_responses_and_messages')['updating_data'] }}",
                            icon: 'success',
                        });

                      // Visual Changes
                        $(`[data-reservation-card="${reservation_id}"]`).remove();
                    },

                    error: function(data){
                        showToast(
                            "{{ __('common_responses_and_messages')['data_not_updated'] }}",
                            "#C34808", "#78350F"
                        );
                        return;
                    },
                });
            }
        });

    }

    function showReservationBallot(encrypted_data) {
      //* Decrypt Received Data
        const data = decryptData(decodeURIComponent(encrypted_data));

      //* Control Data
        const $modal = $('#reservation_ballot');
        const has_control_hours = @json($has_control_hours);

      //* Fill Data
        // Save Meta Data
            $modal.data('reservation-id', data.id).data('reservation', data);

        // Actions
            $('#btn-edit-reservation').off('click')
                .on('click', () => showModalForm(data.id));

            $('#btn-print-ticket')
                .attr('href', `/reservation-tickets/full-stay/${data.id}`);

        // Texts
            // Titles
            $('#ballot-reservation-id').text(data.id);

            // Balances
            $('#ballot-lodging-balances-total').text( clean_currencies(data.total_price) );
            $('#ballot-lodging-balances-paid').text( clean_currencies(data.lodgingPayments) );
            $('#ballot-lodging-balances-outstanding').text( clean_currencies(data.lodgingPayment_left) );

            $('#ballot-consumption-balances-total').text( clean_currencies(data.consumptionCharges) );
            $('#ballot-consumption-balances-paid').text( clean_currencies(data.consumptionPayments) );
            $('#ballot-consumption-balances-outstanding').text( clean_currencies(data.consumptionPayment_left) );

            $('#ballot-extra-balances-total').text( clean_currencies(data.extraCharges) );
            $('#ballot-extra-balances-paid').text( clean_currencies(data.extraPayments) );
            $('#ballot-extra-balances-outstanding').text( clean_currencies(data.extraPayment_left) );

        // Inputs
          // Basic Reservation Data
            $('#ballot-reservation-date').val(data.reservation_date);
            $('#ballot-client-reference').val(data.client_reference);
            $('#ballot-client-segment')
                .text(data.client_segment_type).attr('style', data.client_segment_badge);


            $('#ballot-reservation-status').val(data.status);

            $('#ballot-guest-status').val(data.guest_status);
            $('#ballot-reservation-source').val(data.source);
            $('#ballot-agency').val(data.agency ? data.agency : "{{ __('neutral_words')['none'] }}");
            $('#ballot-lodging-contract').val(data.lodging_contract);

          // Advanced Reservation Data
            // Details
            const checkin_date = has_control_hours
                ? `${data.date_entry}  ${data.hour_entry}`
                : data.date_entry;

            const checkout_date = has_control_hours
                ? `${data.date_departure}  ${data.hour_departure}`
                : data.date_departure;

            $('#ballot-checkin-date').val(checkin_date);
            $('#ballot-checkout-date').val(checkout_date);

            $('#ballot-nights-block').toggle(!data.is_express);
            $('#ballot-number-nights').val(data.number_nights);
            $('#ballot-number-hours').val(data.number_hours);
            $('#ballot-number-adults').val(data.number_adults);
            $('#ballot-number-children').val(data.number_children);

            $('#ballot-room-type').val(data.room_type);
            $('#ballot-room-number').val(data.room_number);
            $('#ballot-regimen').val(data.regimen);

            // Rates
            $('#ballot-suggested-rate').val( clean_currencies(data.suggested_price) );
            $('#ballot-selected-rate').val( clean_currencies(data.final_price) );
            $('#ballot-total-price').val( clean_currencies(data.total_price) );

            //Balances
            const total_per_service = parseFloat(data.total_price) + parseFloat(data.consumptionCharges) + parseFloat(data.extraCharges);
            const total_service_outstanding = parseFloat(data.lodgingPayment_left) + parseFloat(data.consumptionPayment_left) + parseFloat(data.extraPayment_left);

            $('#ballot-total-per-service').val( clean_currencies(total_per_service) )
            $('#ballot-total-service-outstanding').val( clean_currencies(total_service_outstanding) )

            // Notes & Reminders
            $('#ballot-notes').val(data.notes);
            $('#ballot-requiere-invoice').prop('checked', Boolean(data.requiere_invoice));

      //* Show Modal
        $modal.modal('show');
    }

  //* Cycles
    // Debounce
    function debounce(func, delay) {
        let timeout;
        return function (...args) {
            const context = this;
            clearTimeout(timeout);
            timeout = setTimeout(() => func.apply(context, args), delay);
        };
    }

    // Build Reservation Cards
    window.reservesOnTimeDebounced = (window.reservesOnTimeDebounced || debounce(getReservesOnTime, 800));

    function getReservesOnTime() {
        let reservesEncrypted = localStorage.getItem("ReservationData");
        let reservesData = decryptData(reservesEncrypted);

        //window.config.data.features.has_control_hours

        $.get("{{ route('api.home.reservationCards') }}", {
            has_control_hours : window.config.data.features.has_control_hours
        }, function(data) {
            let currentData = JSON.stringify(data);

            if (JSON.stringify(reservesData) !== currentData) {
                renderReservations(data);

                const encrypted = encryptData(data);
                localStorage.setItem("ReservationData", encrypted);
            }
        });
    }

    // Check Overbookings
    function getOverBookings() {
        let overBookEncrypted = localStorage.getItem("isOverBooking");
        let overBook = decryptData(overBookEncrypted);

        $.get('/api/reservations/overbookings', { has_control_hours: @json($has_control_hours) },function(data) {
            let currentData = JSON.stringify(data);

            if (!overBook || JSON.stringify(overBook) !== currentData) {
                if (data.length > 0) {
                    Toastify({
                        text: translateAndReplace("home.overbooking_count_message", { count: data.length }),
                        duration: 7000, close: true,
                        destination: "/reservations",
                        newWindow: false,
                        gravity: "bottom", position: "center",
                        avatar: config.assets.toastInfoIcon,
                        style: {
                            background: "linear-gradient(to right, #dc3545 , #dc3545)",
                        }
                    }).showToast();
                }

                const encrypted = encryptData(data);
                localStorage.setItem("isOverBooking", encrypted);
            }
        });
    }

    // On api token generated
    window.apiTokenReady.then(token => {
        // Initial Call
        setTimeout(() => {
            getReservesOnTime();
            getOverBookings();
        }, 500);

        // Cycles
        setInterval(reservesOnTimeDebounced, 9200); //Cada 10 segundo (10 mil milisegundos)
        setInterval(getOverBookings, 300000); //Cada 5 minutos (300 mil milisegundos)
    });

  //* Builders
    // Builder Constants
    const drawEmptyList = (title, message) => `
        <div class="pt-3 pb-2 empty-list-card g-1 d-flex flex-column align-items-center">
            <img
                src="
                    @if (Auth::user()->profile_photo === null)
                        {{ asset('images/only_harsi.png') }}
                    @else
                        {{ Auth::user()->profile_photo }}
                    @endif
                "
                class="img-fluid d-block empty-list-img"
                alt="Harsi Icon"
            />
            <h6 class="text-center">
                <span class="empty-list-title">${title}</span><br>
                <span class="empty-list-message">${message}</span><br>
            </h6>
        </div>
    `;

    const buildReservationCardList = (reservations, type, modal_map) =>
        reservations.map(reservation => {
            const modal_data = modal_map[reservation.id] || reservation;
            return buildReservationCards(reservation, type, modal_data)
        }).join('');

    // Builder Functions
    function renderReservations(data) {
        let modals = data.modals || [];
        const modal_map = {};
            modals.forEach(m => modal_map[m.id] = m);

        let arrives = data.arrivals.length ? buildReservationCardList(data.arrivals, 'arrive', modal_map) : drawEmptyList( translateAndReplace('home.empty_list.all_clear_title') , translateAndReplace('home.empty_list.arrivals_message'));
        let occupancy = data.occupancy.length ? buildReservationCardList(data.occupancy, 'ocupancy', modal_map) : drawEmptyList( translateAndReplace('home.empty_list.no_guests_title') , translateAndReplace('home.empty_list.in_hotel_message'));
        let departures = data.departures.length ? buildReservationCardList(data.departures, 'departure', modal_map) : drawEmptyList( translateAndReplace('home.empty_list.all_clear_title') , translateAndReplace('home.empty_list.departures_message'));

        $('#reservation-arrives').html(arrives);
        $('#reservation-occupancy').html(occupancy);
        $('#reservation-departures').html(departures);
    }

    function buildReservationCards(data, control_status, modal_data) {
      //* Extract common Attributes
        let client_name = data.client_reference;

      //* Dynamic Resources
        // Conditionals
            const is_arrive = control_status === 'arrive';

        // No show Conditionals
            let no_show_condition_1 = ( is_arrive && data.no_show_type === 'Primary'); // Define "No Show" button visualization
            let no_show_condition_2 = ( is_arrive && ['Secondary', 'Tertiary'].includes(data.no_show_type) && ['0', 0].includes(data.show_in_calendar) ); // Remove "No Show" button and decolore cards

        // Messages &  titles
            const pax_title = `{{ __('home')['cards']['tenants'] }}: ${data.number_adults} {{ __('home')['cards']['adults'] }} {{ __('neutral_words')['and'] }} ${data.number_children} {{ __('home')['cards']['children'] }}`;
            const defer_message = `{{ __('home')['cards']['defer_confirmation_1'] }}${data.id} (${data.client_reference}) {{ __('home')['cards']['defer_confirmation_2'] }}`;

        // Encrypted Data
            const encrypted_modal_reservation = encodeURIComponent(encryptData(modal_data));

      //* Build Cards
        // Complements
        const payment_summary_section = !is_arrive
            ? `
                <div class="mb-1 g-2 d-flex align-items-center justify-content-start w-100">

                    {{-- Cantidad Pagada --}}
                    <div title="{{ __('home')['cards']['paid'] }}"
                        class="d-flex align-items-center justify-content-center">
                        <img class="img-icon" src="{{ asset('icons/payment_card.svg') }}">
                        <p class="mb-0 harsi-color reservation-card-data">${data.lodgingPayments}</p>
                    </div>

                    {{-- Cantidad Restante --}}
                    <div title="{{ __('home')['cards']['owed'] }}"
                        class="d-flex align-items-center justify-content-center">
                        <img class="img-icon" src="{{ asset('icons/missing_payment_blue.svg') }}">
                        <p class="mb-0 harsi-color reservation-card-data">${data.lodgingPayment_left < 0 ? 0 : data.lodgingPayment_left}</p>
                    </div>

                </div>
            `
            : '';


        // Final Cut
        return `
            <div data-reservation-card="${data.id}"
                class="reserve-card g-1 d-flex align-items-center pt-3 pb-2 ${ no_show_condition_2 ? 'disabled-reserve-card': '' }"
            >

                {{-- Status Bar --}}
                <div class="status-bar" style="background-color: ${data.payment_status}d6 !important;"></div>

                {{-- Reserve Data --}}
                <div class="pr-2 flex-grow-1 d-flex flex-column align-items-start">

                    {{-- Folio - Huésped --}}
                    <div class="pr-2 w-100 d-flex justify-content-between align-items-center">
                        <p title="{{ __('entity_fields')['reservation']['guest'] }}"
                            class="mb-2 guest-name"
                        >${truncateString(client_name.toLowerCase(), 17)}</p>

                        <span title="${translateAndReplace('entity_fields.common.type')}: ${data.client_segment_type}"
                            class="client-segment-card-badge reservation-card-data text-uppercase"
                            style="${data.client_segment_badge}"
                        >
                            #${data.id}
                        </span>

                    </div>

                    {{-- Noches - Horas - Periodo --}}
                    <div class="mb-1 d-flex align-items-center justify-content-start w-100 g-1">

                        ${!data.is_express
                            ? `
                                {{-- Noches --}}
                                <div title="{{ __('entity_fields')['reservation']['number_nights_large'] }}"
                                    class="d-flex align-items-center justify-content-center">
                                    <img class="img-icon" src="{{ asset('icons/moon.svg') }}">
                                    <p class="mb-0 harsi-color reservation-card-data">${data.number_nights}</p>
                                </div>
                            `
                            : `
                                {{-- Horas --}}
                                <div title="{{ __('entity_fields')['reservation']['number_hours_large'] }}"
                                    class="d-flex align-items-center justify-content-center">
                                    <img class="img-icon" src="{{ asset('icons/clock_blue.svg') }}">
                                    <p class="mb-0 harsi-color reservation-card-data">${data.number_hours}</p>
                                </div>
                            `
                        }

                        {{-- Desde --}}
                        <div title="{{ __('entity_fields')['reservation']['date_entry_large'] }}"
                            class="d-flex align-items-center justify-content-center">
                            <img class="img-icon" src="{{ asset('icons/checkIn_blue.svg') }}">
                            <p class="mb-0 harsi-color reservation-card-data">${data.date_entry}</p>
                        </div>

                        {{-- Hasta --}}
                        <div title="{{ __('entity_fields')['reservation']['date_departure_large'] }}"
                            class="d-flex align-items-center justify-content-center">
                            <img class="img-icon" src="{{ asset('icons/checkIn_inverso.svg') }}">
                            <p class="mb-0 harsi-color reservation-card-data">${data.date_departure}</p>
                        </div>

                    </div>

                    {{-- Stay Summary --}}
                    <div class="mb-1 g-1 d-flex align-items-center justify-content-start w-100">

                        {{-- Room Type --}}
                        <div title="{{ __('entity_fields')['common']['room_type'] }}"
                            class="d-flex align-items-center justify-content-center">
                            <img class="img-icon" src="{{ asset('icons/types.svg') }}">
                            <p class="mb-0 harsi-color reservation-card-data">${truncateString(data.room_type, 9)}</p>
                        </div>

                        {{-- Room Type --}}
                        <div title="{{ __('entity_fields')['reservation']['room'] }}"
                            class="d-flex align-items-center justify-content-center">
                            <img class="img-icon" src="{{ asset('icons/double_bed_blue.svg') }}">
                            <p class="mb-0 harsi-color reservation-card-data">${truncateString(data.room_number, 9)}</p>
                        </div>

                        {{-- PAX --}}
                        <div title="${pax_title}"
                            class="d-flex align-items-center justify-content-center">
                            <img class="img-icon" src="{{ asset('icons/traveling_blue.svg') }}">
                            <p class="mb-0 harsi-color reservation-card-data">${data.number_adults} - ${data.number_children}</p>
                        </div>

                    </div>

                    {{-- Payments Summary --}}
                    ${payment_summary_section}

                    {{-- Actions --}}
                    <div class="px-2 my-2 g-1 d-flex align-items-center justify-content-end w-100">

                        <button type="button" title="{{ __('home')['cards']['get_details'] }}"
                            class="btn reservation-card-button btn-harsi"
                            onclick="showReservationBallot('${encrypted_modal_reservation}')"
                        >
                            {{ __('entities')['hotel']['reservation'] }}
                        </button>

                        ${ is_arrive && !no_show_condition_2
                            ? `
                                <button type="submit" title="{{ __('home')['cards']['defer_reserve'] }}"
                                    class="reservation-card-button btn ${no_show_condition_1 ? 'btn-warning':'btn-danger'}"
                                    onclick="setAsNoShow('${defer_message}', ${data.id}, '${data.no_show_type}')"
                                >
                                    ${no_show_condition_1 ? 'No Show':'<span class="text-white">No Show</span>'}
                                </button>
                            ` : ""
                        }

                    </div>

                </div>

            </div>
        `;
    }

</script>

{{-- Support Functions --}}
<script>
  //? Crypts
    function encryptData(data) {
        try {
            return CryptoJS.AES.encrypt(
                JSON.stringify(data),
                window.decrypt_data
            ).toString();
        } catch (e) {
            return null;
        }
    }

    function decryptData(encrypted) {
        try {
            if (!encrypted) return null;

            const bytes = CryptoJS.AES.decrypt(encrypted, window.decrypt_data);
            const decrypted = bytes.toString(CryptoJS.enc.Utf8);

            return decrypted ? JSON.parse(decrypted) : null;
        } catch (e) {
            return null;
        }
    }

  //? Formatters
    const clean_currencies = (value) => formatCurrency( removeUnnecessaryDecimal(value) );

    function truncateString(txt, mins_length = 15) {
        // Avoid truncate small texts
        if (txt.length <= mins_length)
            return txt;

        // Truncate text and add '...' at the end
        return `${txt.substring(0, mins_length)}...`;
    }
</script>
