{{-- Imports --}}
@php
    use App\Enums\Hotel\CycleType;
@endphp

{{-- Constants --}}
<script>
  // Week days
    window.week_days = [
        { value: 0, label: moment().day(0).format('dddd') },
        { value: 1, label: moment().day(1).format('dddd') },
        { value: 2, label: moment().day(2).format('dddd') },
        { value: 3, label: moment().day(3).format('dddd') },
        { value: 4, label: moment().day(4).format('dddd') },
        { value: 5, label: moment().day(5).format('dddd') },
        { value: 6, label: moment().day(6).format('dddd') },
    ];
</script>

{{-- CRUD Interactions --}}
<script>
    $(document).ready(function () {
      // For Create
        $('#create_record').click(function () {
          // Adjust Titles
            $('.modal_title').text("{{ __('entity_forms')['common']['modal_title'] }}");
            $('.modal_subtitle').text("{{ __('entities')['hotel']['global_season'] }}");

          // Adjust Buttons
            $('#action_button').val("{{ __('common_actions')['add'] }}");
            $('#action').val("Agregar");

          // Reset Form
            $('#formModal').modal('show');
            $('#season_form')[0].reset();
            $('#cycle_type_block').hide();
            $('#periods').empty();
        });

      // For Edit
        $(document).on('click', '.edit', function () {
            const id = $(this).attr('id');

            $.ajax({
                url: `/seasons/${id}/edit`,
                dataType: "json",
                success: function (html) {
                  // Control Data
                    data = html.data;
                    periods = data.s_periods.periods;

                  // Seed Form
                    $('#periods').empty();
                    $('#s_name').val(data.s_name);
                    $('#is_cyclic').prop('checked', data.is_cyclic);
                    $('#cycle_type').val(data.cycle_type);
                    $('#hidden_id').val(data.id);

                  // Spread Periods Data
                    setAsCyclic();
                    periods.forEach(period => addPeriodRow(period, {is_cyclic: data.is_cyclic, cycle_type: data.cycle_type}));

                  // Modify Modal
                    // Total
                    $('.modal_title').text("{{ __('entity_forms')['common']['modal_title_2'] }}");
                    $('.modal_subtitle').text(`${data.s_name}`);

                    // Update Render
                    $('#action_button').val("{{ __('common_actions')['update'] }}");
                    $('#action').val("Actualizar");
                    $('#formModal').modal('show');
                }
            })
        });

      // For Delete
        $(document).on('click', '.delete', function () {
            var id = $(this).attr('id');
            Swal.fire({
                type: 'warning',
                title: "{{ __('common_responses_and_messages')['confirm_deletion'] }}",
                confirmButtonText: "{{ __('common_actions')['approve'] }} {{ __('common_actions')['confirm_deletion'] }}",
                confirmButtonColor: `#0d6889`,
                showCancelButton: true,
                cancelButtonText: `{{ __('common_actions')['cancel'] }}`,
                cancelButtonColor: `#c82333`
            }).then((result) => {
                if (result.value) {
                    $.ajax({
                        url: `/seasons/${id}/destroy`,
                        success: function (data) {
                            Swal.fire(
                                "{{ __('common_responses_and_messages')['deleted'] }}",
                                "{{ __('common_responses_and_messages')['deleted_successfully'] }}",
                                'success'
                            );

                            $('#season_table').DataTable().ajax.reload(null, false);
                        }
                    });
                }
            });
        });

      // On Submit
        $('#season_form').on('submit', function (event) {
            event.preventDefault();

            // Create
            if ($('#action').val() == 'Agregar') {
                $.ajax({
                    url: "{{ route('seasons.store') }}",
                    method: "POST",
                    data: new FormData(this),
                    contentType: false,
                    cache: false,
                    processData: false,
                    dataType: "json",
                    success: function (data) {
                      // Messages
                        Swal.fire(
                            "{{ __('common_responses_and_messages')['success'] }}",
                            "{{ __('common_responses_and_messages')['created_successfully'] }}",
                            'success'
                        );

                      // Reset Form
                        $('#season_form')[0].reset();
                        $('#season_table').DataTable().ajax.reload(null, false);
                        $('#formModal').modal('hide');
                        $('#periods').empty();
                    },

                    error: function(data){
                      // Control Data
                        const response = data.responseJSON;
                        const error = response.error;

                      // Display as Validation Error
                        if (error) showToast(error, "#C34808", "#78350F");

                        return;
                    },
                })
            }

            // Edit
            if ($('#action').val() == "Actualizar") {
                $.ajax({
                    url: "{{ route('seasons.update') }}",
                    method: "POST",
                    data: new FormData(this),
                    contentType: false,
                    cache: false,
                    processData: false,
                    dataType: "json",
                    success: function (data) {
                      // Messages
                        Swal.fire(
                            "{{ __('common_responses_and_messages')['success'] }}",
                            "{{ __('common_responses_and_messages')['updated_successfully'] }}",
                            'success'
                        );

                      // Reset Form
                        $('#season_form')[0].reset();
                        $('#season_table').DataTable().ajax.reload(null, false);
                        $('#formModal').modal('hide');
                        $('#periods').empty();
                    },

                    error: function(data){
                      // Control Data
                        const response = data.responseJSON;
                        const error = response.error;

                      // Display as Validation Error
                        if (error) showToast(error, "#C34808", "#78350F");

                        return;
                    },
                });
            }
        });
    });
</script>

{{-- Support Functions --}}
<script>
  // Messages
    function showToast(text, gradient_from, gradient_to) {
        Toastify({
            text,
            duration: 4000,
            close: false,
            gravity: "bottom",
            position: "center",
            avatar: "{{ asset('images/toast-info-icon.png') }}",

            selector: document.body,
            offset: { x: 0, y: 24 },
            style: {
                background: `linear-gradient(to right, ${gradient_from}, ${gradient_to})`,
            },
        }).showToast();
    }

  // Periods
    function setAsCyclic({mutate_periods = false} = {}) {
      // Get Status
        const set_cyclic_season = $('#is_cyclic').prop('checked');

      // Toggle Sections
        $('#cycle_type_block').toggle(set_cyclic_season);

      // Spread Actions
        if (mutate_periods)
            $('#cycle_type').val("{{ CycleType::CUSTOM->value }}").trigger("change");
    }

    function resetPeriods() {
      // Control Data
        let is_cyclic = $('#is_cyclic').prop('checked');
        let cycle_type = $('#cycle_type').val();

      // Clear Section
        $('#periods').empty();

      // Seed with Basic Period
        addPeriodRow();
    }

    function addPeriodRow(data, {is_cyclic = null, cycle_type= null}  = {}) {
      // Control Data
        if (!is_cyclic) is_cyclic = $('#is_cyclic').prop('checked');
        if (!cycle_type) cycle_type = $('#cycle_type').val();

      // Build Structure
        let form_structure = "";

        // Shared Structures
        const delete_button = `
            <button onclick="$(this).parent().remove();"
                type="button" class="py-0 rounded-circle btn btn-outline-danger">
                <i class="fa fa-times"></i>
            </button>
        `;

        // Define Model
        if (is_cyclic) { // Structures for Cyclic Seasons
            switch (cycle_type) {
                case "{{ CycleType::WEEKLY->value }}": // Weekly
                  // Selected day from DB
                    const selected_day = data;

                  // Control Data
                    let used_days = $('select[name="period_days[]"]').map((_, el) => parseInt($(el).val())).get();
                    let available_days = window.week_days.filter(day =>
                        !used_days.includes(day.value) || day.value === selected_day
                    );

                  // Options
                    let options = available_days.map(day => `
                        <option value="${day.value}" ${selected_day == day.value ? 'selected' : ''}>
                            ${day.label.toUpperCase()}
                        </option>
                    `).join('');

                    if (available_days.length === 0) break;

                  // Weekly Structure
                    form_structure = `
                        <div class="mb-3 d-flex align-items-center">
                            {{-- Button --}}
                            ${delete_button}

                            {{-- Day --}}
                            <div class="ml-3 input-group w-100">
                                <label class="px-4 text-center input-group-text control-label">
                                    {{ __('neutral_words')['day'] }}
                                </label>

                                <select name="period_days[]" required class="form-control">
                                    ${options}
                                </select>
                            </div>

                        </div>
                    `;

                    break;

                default: // Custom
                  // Shared Data
                    const dual_input = (type, label, day, month) =>`
                        <label class="px-2 input-group-text">${label}</label>

                        <select name="period_${type}_day[]" class="form-control" required>
                            ${buildDayOptions(day)}
                        </select>

                        <select name="period_${type}_month[]" class="form-control w-25" required>
                            ${buildMonthOptions(month)}
                        </select>
                    `;

                  // Default Data
                    const current_month = moment().month() + 1;
                    const last_day = moment().daysInMonth();

                  // Incoming data
                    const from_day = data?.from?.day ?? 1;
                    const from_month = data?.from?.month ?? current_month;

                    const to_day = data?.to?.day ?? last_day;
                    const to_month = data?.to?.month ?? current_month;

                  // Custom Structure
                    form_structure = `
                        <div class="mb-3 d-flex align-items-center">
                            {{-- Button --}}
                            ${delete_button}

                            {{-- From --}}
                            <div class="mx-2 input-group w-100">
                                ${dual_input("from", "{{ __('entity_forms')['season']['from'] }}", from_day, from_month)}
                            </div>

                            {{-- To --}}
                            <div class="input-group w-100">
                                ${dual_input("to", "{{ __('entity_forms')['season']['to'] }}", to_day, to_month)}
                            </div>

                        </div>
                    `;
                    break;
            }

        } else { // For Static Seasons
          // Control Data
            const from = data ? data.from : "{{ now()->toDateString() }}";
            const to = data ? data.to : "{{ now()->addDay()->toDateString() }}";

          // Structure
            form_structure = `
                <div class="mb-3 d-flex align-items-center">
                    {{-- Button --}}
                    ${delete_button}

                    {{-- From --}}
                    <div class="ml-1 mr-2 input-group w-100">
                        <label class="px-2 text-center input-group-text control-label">
                            {{ __('entity_forms')['season']['from'] }}
                        </label>
                        <input type="date" name="period_from[]" required
                            value="${from}" max="2100-12-31"
                            class="form-control">
                    </div>

                    {{-- To --}}
                    <div class="input-group w-100">
                        <label class="px-2 text-center input-group-text control-label">
                            {{ __('entity_forms')['season']['to'] }}
                        </label>
                        <input type="date" name="period_to[]" required
                            value="${to}" max="2100-12-31"
                            class="form-control">
                    </div>

                </div>
            `;
        }

      // Append Row
        $('#periods').append(form_structure)
    }

  // Dates & Times
    function buildDayOptions(selected = null) {
        return Array.from({ length: 31 }, (_, i) => `
            <option value="${i+1}" ${selected == (i+1) ? 'selected' : ''}>
                ${i + 1}
            </option>
        `).join('');
    }

    function buildMonthOptions(selected = null) {
        return moment.months().map((month, index) => `
            <option value="${index + 1}" ${selected == (index + 1) ? 'selected' : ''}>
                ${month.toUpperCase()}
            </option>
        `).join('');
    }

</script>
