<link href="{{ asset('css/components/tables/entity-tables.css') }}" rel="stylesheet">
<link href="{{ asset('css/pages/shared/otasPages.css') }}" rel="stylesheet">
<link href="{{ asset('css/components/custom/specialElements.css') }}" rel="stylesheet">

@extends('adminlte::page')

@section('title', __('modules')['dashboard']['settings']['otas_connection'])

@section('content')

    {{-- Body --}}
    <section class="col-12">

        {{-- Title & Filter --}}
        <div class="px-3 py-2 mb-4 cardtitle d-flex align-items-center justify-content-between">
            {{-- Title --}}
            <h3 class="pl-3 mb-0">
                {{ __('modules')['dashboard']['settings']['otas_connection'] }}
            </h3>
        </div>

        {{-- Table Structure --}}
        <div class="mb-5 table-responsive">
            <table class="table text-center cardtable" id="otas_connection_table">
                <thead>
                    <tr class="cardtabletr">
                        <th scope="col">{{ __('entity_fields')['common']['logo'] }}</th>
                        <th scope="col">{{ __('entities')['hotel']['agency'] }}</th>
                        <th scope="col">{{ __('entities')['settings']['ota_connection'] }}</th>
                        <th scope="col">{{ __('entity_fields')['ota_connection']['mapping'] }}</th>
                        <th scope="col">{{ __('entity_fields')['ota_connection']['rooms_configuration'] }}</th>
                        <th scope="col">{{ __('entity_fields')['common']['actions'] }}</th>
                    </tr>
                </thead>
            </table>
        </div>

        {{-- Connection Form Modal --}}
        <div id="connectionModal" class="mt-5 modal fade" role="dialog">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="p-4 modal-body special-modal-body">

                        {{-- Form --}}
                        <form method="POST" enctype="multipart/form-data" id="connection_form"
                            class="form-horizontal" autocomplete="off"
                        >@csrf

                            {{-- Header --}}
                            <section class="pt-3 pb-5 row justify-content-center align-items-baseline">

                                {{-- Title & Toggle --}}
                                <div class="pl-3 d-flex align-items-start text-start col-11" style="flex-wrap: wrap; gap: 1rem;">
                                    {{-- Title --}}
                                    <div class="d-flex align-items-center" style="font-weight: 800; color: #0d6889;">
                                        <h1 class="m-0 modal_title" style="font-weight: 800; color: #0d6889"></h1>
                                        <input type="hidden" id="ota_name" name="ota_name">
                                    </div>

                                    {{-- Toggle --}}
                                    <div class="m-0 ml-3 d-flex align-items-center mt-md-2" id="connection_status_box">
                                        <div class="px-2 py-1 switch_card d-flex align-items-center justify-content-between">
                                            <div class="pr-3 d-flex align-items-center justify-content-start" style="flex: 1;">
                                                <p  style="font-weight: 600; color:#0d6889; margin: 0;">
                                                    {{ __('neutral_words')['disabled'] }}
                                                </p>
                                            </div>

                                            <div class="d-flex align-items-center justify-content-center" style="flex: 1;">
                                                <label class="m-0 switch switch_label">
                                                    <input type="checkbox"
                                                        id="is_ota_active"
                                                        name="is_ota_active"
                                                        onchange="ensureToggleAction()"
                                                    >
                                                    <span class="specific_slider slider round"></span>
                                                </label>
                                            </div>

                                            <div class="pl-3 d-flex align-items-center justify-content-end" style="flex: 1;">
                                                <p  style="font-weight: 600; color:#0d6889; margin: 0;">
                                                    {{ __('neutral_words')['enabled'] }}
                                                </p>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                {{-- Close Button --}}
                                <div class="text-center col-1">
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close" style="float: none; font-size: 3.5rem; color: #FF5050">
                                        <span>
                                            <img src="{{ asset('icons/close_modal.svg') }}" aria-hidden="true"
                                                style="margin-top: -0.85rem; width: 2.45rem;">
                                        </span>
                                    </button>
                                </div>

                            </section>

                            <section class="px-4 mb-4 d-flex align-items-baseline justify-content-between">

                                {{-- OTA Connection Instructions --}}
                                <div class="col-5 ota-indications" style="color:#0D6889">
                                    <p id="connection_manual_introduction" style="font-size: 1.1rem;"></p>
                                    <div id="connection_manual_instructions"></div>
                                </div>

                                {{-- Connection Manager --}}
                                <div class="col-6">

                                    {{-- Header --}}
                                    <p class="harsi-color ota-indications">
                                        {{ __('entity_forms')['otas_connection']['common']['connection_manual_step_1'] }}
                                    </p>

                                    {{-- Hotel OTA ID --}}
                                    <div class="mb-4 shadow-sm input-group">
                                        <div class="input-group-prepend">
                                            <div class="input-group-text clean-label">Hotel ID (<span id="ota_id_reference"></span>)</div>
                                        </div>
                                        <input type="text" name="id_connection" id="id_connection" required
                                            oninput="this.value = this.value.replace(/[^a-zA-Z0-9 _-]/g, '');"
                                            class="form-control" placeholder="HARSI - 12345678">
                                    </div>

                                    {{-- Status Connection --}}
                                    <div class="mb-3 shadow-sm input-group">
                                        <div class="input-group-prepend">
                                            <div class="input-group-text clean-label">{{ __('entity_fields')['ota_connection']['connected'] }}</div>
                                        </div>
                                        <select id="connection_status"
                                            class="form-control disabled-select" disabled>
                                            <option value="0" selected>{{ __('neutral_words')['No'] }}</option>
                                            <option value="1">{{ __('neutral_words')['Si'] }}</option>
                                        </select>
                                    </div>

                                    {{-- Map Sync --}}
                                    <div class="mb-4 shadow-sm input-group">
                                        <div class="input-group-prepend">
                                            <div class="input-group-text clean-label">{{ __('entity_fields')['ota_connection']['mapping'] }}</div>
                                        </div>
                                        <select id="synchronization_status"
                                            class="form-control disabled-select" disabled>
                                            <option value="0" selected>{{ __('neutral_words')['not_synchronized'] }}</option>
                                            <option value="1">{{ __('neutral_words')['synchronized'] }}</option>
                                        </select>
                                    </div>

                                    <div class="mb-4 text-center" id="configure_rooms">
                                        <a href="{{ route('room-types.index') }}" class="px-3 py-1 btn btn-harsi text-uppercase">
                                            {{ __('entity_forms')['otas_connection']['common']['configure_rooms'] }}
                                        </a>
                                    </div>

                                    {{-- Header --}}
                                    <p class="harsi-color ota-indications">
                                        {{ __('entity_forms')['otas_connection']['common']['connection_manual_step_2'] }}
                                    </p>

                                    {{-- Assigned Local Agency --}}
                                    <div class="shadow-sm input-group">
                                        <div class="input-group-prepend">
                                            <div class="input-group-text clean-label">Agencia Local</div>
                                        </div>
                                        <select id="assigned_agency" name="assigned_agency"
                                            class="form-control">
                                            <option value="none" selected>{{ __('neutral_words')['none'] }}</option>

                                            @foreach ($agencies as $agency)
                                                <option value="{{ $agency->id }}">{{ $agency->agency_name }}</option>
                                            @endforeach
                                        </select>
                                    </div>

                                </div>

                            </section>

                            {{-- Buttons --}}
                            <div class="pb-3 pt-4_5 col-12" align="center">
                                <input type="hidden" name="hidden_id" id="hidden_id" />
                                <input type="submit" id="update_connection" class="btn btn-lg boton-lg text-uppercase"/>
                            </div>
                        </form>

                    </div>
                </div>
            </div>
        </div>

    </section>

    {{-- JS Control --}}
    <script type="text/javascript">
        "use strict";
    </script>

    {{-- Import DataTables Modded --}}
    <script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.18/js/dataTables.bootstrap4.min.js"></script>

    {{-- CRUD Controls --}}
    <script>
        // Table Constructor
        $(document).ready(function(){

            // Table Controller
            $('#otas_connection_table').DataTable({
                order: [2, 'asc'],
                lengthMenu: [
                    [4, 10, 25, 50,  100, -1],
                    [4, 10, 25, 50,  100, 'All']
                ],

                language: getDataTableLanguageConfig(),
                processing: false,
                serverSide: true,

                ajax:{
                    url: "{{ route('otas.index') }}",
                },
                columns:[
                    {
                        data: 'image',
                        name: 'image',
                        searchable: false,
                    },
                    {
                        data: 'name',
                        name: 'name',
                        searchable: true,
                    },
                    {
                        data: 'connection',
                        name: 'connection',
                        searchable: false,
                    },
                    {
                        data: 'mapping',
                        name: 'mapping',
                        searchable: false,
                    },
                    {
                        data: 'rooms_configuration',
                        name: 'rooms_configuration',
                        searchable: false,
                    },
                    {
                        data: 'action',
                        name: 'action',
                        orderable: false
                    }
                ]
            });

            // Open For Edit
            $(document).on('click', '.connect, .connect-disabled', function(){
                let id = $(this).attr('id');

                $.ajax({
                    url: `/otas/${id}/edit`,
                    dataType: "json",
                    success: function (html) {
                        const data = html.data;

                        // Visual Elements
                        $('.modal_title, #ota_id_reference').text(data.name);
                        $('#update_connection').val( translateAndReplace(`entity_forms.otas_connection.common.connect_channel`) );

                        $('#connection_manual_introduction').html( translateAndReplace(`entity_forms.otas_connection.common.connection_manual_introduction`, {ota_name: data.sample_name}) );
                        $('#connection_manual_instructions').html( translateAndReplace(`entity_forms.otas_connection.connections.${data.sample_name}.description`) );

                        const has_been_connected = ![null, ""].includes(data.ota_hotel_id);
                        if (has_been_connected) {
                            $('#connection_status_box').show(has_been_connected).addClass('d-flex');
                        }else {
                            $('#connection_status_box').hide(has_been_connected).removeClass('d-flex');
                        }

                        $('#configure_rooms').toggle(Boolean(data.is_active));

                        // Form Values
                        $('#connection_form')[0].reset();
                        $('#hidden_id').val(id);
                        $('#ota_name').val(data.name);
                        $('#is_ota_active').prop('checked', Boolean(data.is_active));
                        $('#id_connection').val(data.ota_hotel_id);
                        $('#connection_status').val(data.is_connected);
                        $('#synchronization_status').val(data.is_synchronized);
                        $('#assigned_agency').val(data.local_agency_id ?? "none");

                        // Display Modal
                        $('#connectionModal').modal('show');
                    }
                })
            });

            // Submit Form
            $('#connection_form').on('submit', function(event){
                event.preventDefault();
                const otas_was_linked = $('#assigned_agency').val() != "none";

                if (!otas_was_linked) {
                    Swal.fire({
                        type: 'warning',
                        title: "{{ __('common_responses_and_messages')['default_confirmation'] }}",
                        html: translateAndReplace(
                            `entity_forms.otas_connection.connections.warnings.no_linked_agency`
                        ),
                        showCancelButton: true,
                        confirmButtonText: "{{ __('common_actions')['approve'] }} {{ __('common_actions')['accept'] }}",
                        cancelButtonText: "{{ __('common_actions')['cancel'] }}",
                    }).then((response) => {
                        if (response.value) updateConnection(this);
                    });
                } else {
                    updateConnection(this);
                }

            });

            function updateConnection(form_data) {
                $.ajax({
                    url:"{{ route('otas.update') }}",
                    method:"POST",
                    data:new FormData(form_data),
                    contentType: false,
                    cache: false,
                    processData: false,
                    dataType:"json",
                    success: function(data) {
                        launchSwalToast(
                            'success',
                            `{{ __('common_responses_and_messages')['connected_successfully'] }}`
                        );

                        $('#connection_form')[0].reset();
                        $('#connectionModal').modal('hide');
                        $('#otas_connection_table').DataTable().ajax.reload(null, false);
                    },

                    error: function(err) {
                        launchSwalToast(
                            'error',
                            err.responseJSON.error,
                        );
                    }
                });
            }

            // On Close Modal
            $('#connectionModal').on('hide.bs.modal', function () {
                document.activeElement.blur();
            });
        });

        // Table Data Cycle
            function cargarTabla(){
                $('#otas_connection_table').DataTable().ajax.reload(null, false);
            }

            $( document ).ready(function() {
                setInterval(cargarTabla, 120000); //Cada 120 segundos (120 mil milisegundos)
            });

        // Avoid unexpected Dropdown Close
            $(document).ready(function () {
                $('.drop-filter').on('click', function (e) {
                    e.stopPropagation(); // Evita que el dropdown se cierre al hacer clic dentro
                });
            });
    </script>

    {{-- Behavior Functions --}}
    <script>
      // Toogle Interactions
        function ensureToggleAction() {
            // Switch Values
            const switch_id = `is_ota_active`;
            const checked = $(`#${switch_id}`).prop('checked');

            // Avoid Connection on empty CLABES
            if ($('#id_connection').val().trim() === "") {
                // Show restriction message
                Swal.fire(
                    "{{ __('entity_forms')['otas_connection']['connections']['errors']['connection_not_allowed_title'] }}",
                    "{{ __('entity_forms')['otas_connection']['connections']['errors']['connection_not_allowed_message'] }}",
                    'error'
                );

                // Restore toggle value
                restoreToggleValue(switch_id);
                return;
            }

            Swal.fire({
                type: 'warning',
                title: "{{ __('common_responses_and_messages')['default_confirmation'] }}",
                html: translateAndReplace(
                    `entity_forms.otas_connection.connections.warnings.${checked ? 'disable_connection' : 'enable_connection'}`,
                    { ota: $('#ota_name').val() }
                ),
                showCancelButton: true,
                confirmButtonText: "{{ __('common_actions')['approve'] }} {{ __('common_actions')['accept'] }}",
                cancelButtonText: "{{ __('common_actions')['cancel'] }}",
            }).then((response) => {
                if (response.dismiss) { // If dismiss, restore toggle value
                    restoreToggleValue(switch_id);
                    return;
                }

                $.ajax({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    url:"{{ route('otas.update') }}",
                    method:"POST",
                    data: {
                        hidden_id: $('#hidden_id').val(),
                        toggle_control: checked,
                        id_connection: $('#id_connection').val(),
                        assigned_agency: $('#assigned_agency').val(),
                    },
                    success: function(data) {
                        launchSwalToast(
                            'success',
                            `{{ __('common_responses_and_messages')['update'] }}&nbsp;<b style="color:#12a15e">{{ __('common_responses_and_messages')['completed'] }}</b>`
                        );
                        $('#otas_connection_table').DataTable().ajax.reload(null, false);

                        $('#connection_status, #synchronization_status').val(+checked);
                        $('#configure_rooms').toggle(checked);
                    },

                    error: function(err) {
                        // Launch Error
                        launchSwalToast(
                            "error",
                            "{{ __('entity_forms')['otas_connection']['connections']['errors']['connection_not_updated'] }}"
                        );

                        // Restore toggle value
                        restoreToggleValue(switch_id);
                    }
                });

            });
        }

      // Support Functions
        function restoreToggleValue(switch_id) {
            const $switch = $(`#${switch_id}`);
            $switch.prop('checked', !$switch.prop('checked'));
        }

        function launchSwalToast(type, title) {
            Swal.fire({
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 5000,
                title,
                type,
            });
        }
    </script>
@endsection
