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

@extends('adminlte::page')

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

@section('content')
    {{-- Special Styles --}}
    <style>
        .btn-outline-light {
            border-color: #98b0ca;
        }
        .btn-outline-light  a {
            color: #0d6889 !important;
            font-weight: 500;
            font-size: 1.05rem;
        }

        .btn-outline-light:hover {
            background-color: #98b0ca;
        }

        .alert-danger{
            color: #721c24;
            background-color: #f8d7da;
            border-color: #f5c6cb;
        }
    </style>

    {{-- Body --}}
    <div class="col-xs-12">

        {{-- Title & Filter --}}
        <div class="px-3 py-2 mb-3 cardtitle d-flex align-items-center justify-content-between">

            {{-- Title --}}
            <h3 class="pl-3 mb-0">
                {{ __('modules')['dashboard']['settings']['audits'] }}
            </h3>

            {{-- Buttons --}}
            <div class="gap-2 d-flex align-items-center justify-content-end">

                {{-- Conclude & Audit Shift by Date --}}
                <button type="button" class="px-3 py-1 mx-3 btn btn-outline-secondary" onclick="concludeAndAuditShift()">
                    <i class="fas fa-hourglass-end"></i>
                    &nbsp;
                    {{ __('common_actions')['audit'] }}
                </button>

                {{-- Conclude Current Shift --}}
                @if ($last_audit_is_over && $has_current_shift && $not_same_shift_or_day)
                    <button type="button" class="px-3 py-1 mx-3 btn btn-outline-info" onclick="concludeShift()">
                        <i class="fas fa-hourglass-start"></i>
                        &nbsp;
                        {{ __('common_responses_and_messages')['conclude_shift'] }}
                    </button>
                @endif

                {{-- Filter --}}
                <ul class="mx-3 cursor-pointer navbar-nav">
                    <li class="py-0 text-center nav-item dropdown btn btn-outline-light">

                        {{-- Activate --}}
                        <a id="navbarDropdown" title="Filtrar Auditorias" class="px-3 py-1 nav-link" role="button" href="#"
                            data-toggle="dropdown" aria-haspopup="true" aria-expanded="true" v-pre>
                            <img src="{{ asset('icons/reservation_filter.svg') }}" style="width: 1.5rem;" alt="Filter">
                            &nbsp;<span>{{ __('common_actions')['filter'] }}</span>
                        </a>

                        {{-- Structure --}}
                        <div class="dropdown-menu dropdown-menu-right drop-filter" style="width: 30rem; border-radius: 10px; " aria-labelledby="navbarDropdown">
                            <div class="container mb-3">

                                {{-- Buttons --}}
                                <div class="px-2 mb-3 row" style="border-bottom: 1px solid #dddddd">
                                    {{-- Icon --}}
                                    <div class="pt-2 col-1">
                                        <img src="{{ asset('icons/reservation_filter.svg') }}" alt=""
                                            class="pt-1" style="width: auto; height: 1.4rem;">
                                    </div>

                                    {{-- Title --}}
                                    <div class="py-2 col-9">
                                        <span class="text-start" style="font-weight: bolder; text-transform: uppercase; color: #0d6889; font-size: 1.1rem">
                                            {{ __('entity_forms')['reservation']['page']['filter_title'] }}
                                        </span>
                                    </div>

                                    {{-- Filter Button --}}
                                    <div class="py-2 col-2 text-end">
                                        <button  type="button" id="filter_table"
                                            class="btn btn-success" style="font-size: 1rem">
                                            {{ __('common_actions')['filter'] }}
                                        </button>
                                    </div>
                                </div>

                                {{-- Fecha --}}
                                <div class="p-0 row justify-content-center align-items-center">

                                    {{-- Title --}}
                                    <div class="p-0 pr-1 col-2">
                                        <p class="py-1 text-center indicadores ">
                                            {{ __('entity_fields')['common']['date'] }}
                                        </p>
                                    </div>

                                    {{-- From --}}
                                    <div class="p-0 pr-1 col-4">
                                        <input type="date" id="from"
                                            class="form-control" value="<?php echo date("Y-m-01");?>">
                                    </div>

                                    {{-- Separator --}}
                                    <div class="p-0 pr-1 col-1">
                                        <p class="py-1 text-center indicadores ">
                                            -
                                        </p>
                                    </div>

                                    {{-- To --}}
                                    <div class="p-0 pr-1 col-4">
                                        <input type="date" id="to"
                                        class="form-control" value="<?php echo date("Y-m-t");?>">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </li>
                </ul>
            </div>

        </div>

        {{-- Table Structure --}}
        <div class="mb-5 table-responsive">
            <table class="table text-center cardtable" id="audit_table">
                <thead>
                    <tr class="cardtabletr">
                        <th scope="col">Folio</th>
                        <th scope="col">{{ __('entity_fields')['common']['date'] }}</th>
                        <th scope="col">{{ __('entity_fields')['common']['receptionist'] }}</th>
                        <th scope="col">Auditor</th>
                        <th scope="col">{{ __('entity_fields')['common']['shift'] }}</th>
                        <th scope="col">{{ __('entity_fields')['common']['status'] }}</th>
                        <th scope="col">{{ __('entity_fields')['common']['actions'] }}</th>
                    </tr>
                </thead>
            </table>
        </div>

    </div>

    {{-- 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>

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

      //* Table Constructor
        $(document).ready(function(){

            // Redraw Table for Filter
            $("#filter_table").click(function () {
                event.preventDefault();
                $('#audit_table').DataTable().draw();
            });

            // Table Controller
            $('#audit_table').DataTable({
                order: [1, 'desc'],
                lengthMenu: [
                    [5, 10, 25, 50,  100, -1],
                    [5, 10, 25, 50,  100, 'All']
                ],

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

                ajax: {
                    url: "{{ route('audits.index') }}",
                    data: function (d) {
                        d.from = $('#from').val();
                        d.to = $('#to').val();
                    }
                },
                columns:[
                    {
                        data: 'id',
                        name: 'id',
                        searchable: true
                    },
                    {
                        data: 'audit_date',
                        name: 'audit_date',
                        type: 'date',
                    },
                    {
                        data: 'receptionist',
                        name: 'receptionist',
                        searchable: true
                    },
                    {
                        data: 'auditor',
                        name: 'auditor',
                        searchable: true
                    },
                    {
                        data: 'shift',
                        name: 'shift',
                        searchable: true
                    },
                    {
                        data: 'status',
                        name: 'status',
                        searchable: false
                    },
                    {
                        data: 'action',
                        name: 'action',
                        orderable: false
                    }
                ]
            });

        });

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

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

      //* Special Interactions
        function auditShift(id) {
            Swal.fire({
                type: 'warning',
                title: "{{ __('common_responses_and_messages')['confirm_audit'] }}",
                confirmButtonText: "{{ __('common_actions')['approve'] }} {{ __('common_actions')['audit'] }}",
                confirmButtonColor: `#0d6889`,
                showCancelButton: true,
                cancelButtonText: `{{ __('common_actions')['cancel'] }}`,
                cancelButtonColor: `#c82333`
            }).then((result) => {
                /* Read more about isConfirmed, isDenied below */
                if (result.value) {
                    window.location.href = window.location.origin + `/audits/${id}/audit-shift`
                }
            });
        }

        function concludeShift() {
            Swal.fire({
                type: 'warning',
                html: `
                    <h5 class="mb-3">{{ __('common_responses_and_messages')['audit_current_shift'] }}</h5>

                    <div class="alert alert-danger" role="alert">
                        {{ __('common_responses_and_messages')['spontaneous_audit_alert'] }}
                    </div>
                `,
                confirmButtonText: "{{ __('common_actions')['approve'] }} {{ __('common_actions')['audit'] }}",
                confirmButtonColor: `#0d6889`,
                showCancelButton: true,
                cancelButtonText: `{{ __('common_actions')['cancel'] }}`,
                cancelButtonColor: `#c82333`
            }).then((result) => {
                /* Read more about isConfirmed, isDenied below */
                if (result.value) {
                    window.location.href = `{{ route('audits.concludeShift') }}`
                }
            });
        }

        function concludeAndAuditShift(){
            @php
                $default_date = $max_date = $has_finished_shifts_today
                    ? now()->toDateString() // Today
                    : now()->subDay()->toDateString(); // Yesterday
            @endphp

            Swal.fire({
                type: "info",
                html: `
                    <h4 class="mb-4">{!! __('entity_forms')['audit_shift']['conclude_and_audit']['title'] !!}</h4>

                    <div class="container px-5">

                        {{-- Date --}}
                        <div class="mb-4 input-group">
                            <div class="input-group-prepend">
                                <label class="input-group-text" style="background-color:#fff">
                                    {{ __('entity_fields')['common']['date'] }}
                                </label>
                            </div>

                            <input type="date" id="swal-date" required
                                min="2023-01-01" max="{{ $max_date }}"
                                value="{{ $default_date }}" step="1"
                                class="form-control">
                        </div>

                        {{-- Shift --}}
                        <div class="mb-4 input-group">
                            <div class="input-group-prepend">
                                <label class="input-group-text" style="background-color:#fff">
                                    {{ __('entity_fields')['common']['shift'] }}
                                </label>
                            </div>

                            <select id="swal-shift" class="form-control" required>
                                <option value="" selected disabled>-- -- --</option>
                                    @foreach ($shifts as $shift)
                                        <option value="{{ $shift->id }}"
                                            data-finished-today="{{ $finished_shifts_today->contains('id', $shift->id) ? 1 : 0 }}"
                                        >
                                            {{ $shift->name }}
                                        </option>
                                    @endforeach
                            </select>
                        </select>
                        </div>

                    </div>
                `,

                showCancelButton: true,
                confirmButtonColor: '#0d6889',
                cancelButtonColor: '#d33',
                cancelButtonText: "{{ __('common_actions')['cancel'] }}",
                confirmButtonText: "{{ __('common_actions')['accept'] }}",
                focusConfirm: false,

                preConfirm: () => {
                    const date = Swal.getPopup().querySelector('#swal-date').value

                    const shift = Swal.getPopup().querySelector('#swal-shift').value
                        if (!shift)
                            Swal.showValidationMessage("{{ __('entity_forms')['audit_shift']['conclude_and_audit']['missing_shift'] }}")

                    return {
                        date: date,
                        shift: shift
                    }
                },

                onOpen: () => {
                  // Controls Variables
                    const $popup = $(Swal.getPopup());
                    const $date_input = $popup.find('#swal-date');
                    const $shift_selector = $popup.find('#swal-shift');

                    const original_shifts = $shift_selector.find('option').clone(); // Save original options

                  // Helper
                    function filterShifts() {
                      // Control Data
                        const selectedDate = $date_input.val();
                        const today = "{{ now()->toDateString() }}";

                      // Reset select options
                        // Clear select
                        $shift_selector.empty();

                        // Placeholder
                        $shift_selector.append(`
                            <option value="" disabled selected>
                                {{ __('common_actions')['select'] }}
                            </option>
                        `);

                      // Define avalle options
                        original_shifts.each(function () {
                            const $option = $(this);

                            // Ignore placeholder
                            if (!$option.val()) return;

                            // If the selected date is a past date
                            if (selectedDate < today) {
                                $shift_selector.append($option.clone()); // Use all shifts
                                return;
                            }

                            // Only use concluded shifts
                            if ($option.data('finishedToday') == 1)
                                $shift_selector.append($option.clone());
                        });
                    }

                  // Triggers
                    $date_input.on('change', filterShifts); // Update select options
                    filterShifts();
                },

            }).then((result) => {
                date = result.value.date;
                shift = result.value.shift;

                if(date > "{{ date('Y-m-d') }}"){
                    Swal.fire({
                        title: "{{ __('entity_forms')['audit_shift']['conclude_and_audit']['date_error_title'] }}",
                        html: `
                            <p>
                                {!! __('entity_forms')['audit_shift']['conclude_and_audit']['date_error_description'] !!}
                            </p>
                        `,
                        type: 'error'
                    });
                    return;
                }

                var settings = {
                    "url": `audits/validate-timeless-request?shift_to_audit=${shift}&date_to_audit=${date}`,
                    "method": "GET",
                };

                $.ajax(settings)
                    .done(() => {
                        window.location.href = `audits/conclude-and-audit-shift?shift_to_audit=${shift}&date_to_audit=${date}`;
                    }).fail(() => {
                        Swal.fire({
                            title: "{{ __('common_responses_and_messages')['rejected_action'] }}",
                            html: `
                                <div class="container px-5 pb-0 mb-0 text-left">
                                    <p>{{ __('entity_forms')['audit_shift']['conclude_and_audit']['error_description'] }}</p>
                                    <ul class="text-left warning-confirmation">
                                        <li class="mb-3">
                                            {{ __('entity_forms')['audit_shift']['conclude_and_audit']['error_pending_reason'] }}
                                        </li>
                                        <li>
                                            {{ __('entity_forms')['audit_shift']['conclude_and_audit']['error_existing_reason'] }}
                                        </li>
                                    </ul>
                                </div>
                            `,
                            type: 'error'
                        });
                        return;
                    });
            });
        }

    </script>

@endsection

