@extends('layouts.reports')

@section('title')
Hotel | {{ __('reports.hotel.statisticalReports.ingresos.revenues_per_period') }}
@endsection

@section('content')

    {{-- Control Environment --}}
    @php
        use App\Helpers\Environment\SystemFeaturesHelper;

        $has_itemized_taxes_reports = SystemFeaturesHelper::getFeatureStatus('itemized_taxes_reports');
    @endphp

    {{-- Special Styles --}}
    <style>
        td {
            font-size: 0.9rem;
        }

        .td-minus {
            font-size: 0.84rem;
        }

        table th, table td {
            vertical-align: middle !important;
        }

        .dataTables_info{
            color: white;
        }
    </style>

    {{-- Content --}}
    <div class="mt-4 container-fluid">

        {{-- Header --}}
        <section class="flex-wrap px-3 py-1 d-flex justify-content-between align-items-center cardtitle oculto-impresion">

            {{-- Action & Titles --}}
            <div class="flex-wrap py-2 justify-content-between align-items-center d-flex">
                {{-- Buttons --}}
                <div class="mr-2 d-flex">
                    {{-- Go Back --}}
                    <a type="button" href="{{ route('hotel.reports') }}"
                        class="mx-1 fixed-width oculto-impresion btn return-button"
                    >
                        <img src="{{ asset('icons/arrow_inverse.svg') }}">
                    </a>

                    {{-- Print --}}
                    <button onclick="imprimir()"
                        class="px-0 mx-1 fixed-width oculto-impresion btn harsi-button"
                    >
                        <img src="{{ asset('icons/print.svg') }}">
                    </button>

                    {{-- Download as CSV --}}
                    <button onclick="print_csv()"
                        class="px-0 mx-1 btn btn-success fixed-width oculto-impresion download-csv-button"
                        title="{{ __('reports')['hotel']['common']['download'] }}"
                    >
                        <img src="{{ asset('icons/csv_white.svg') }}">
                    </button>

                    {{-- Tax Breakdown --}}
                    @if ($has_itemized_taxes_reports)
                        @include('shared.utils.report-complements.hotel-grouped-tax-breakdown-dropdown')
                    @endif
                </div>

                {{-- Title --}}
                <h5 class="mb-0 oculto-impresion">
                    {{ __('reports.hotel.statisticalReports.ingresos.revenues_per_period') }}
                </h5>
            </div>

            {{-- Filter Form --}}
            <form id="incomes_period" class="py-2 d-flex align-items-center">
                {{-- From --}}
                <div class="mx-1 input-group">
                    <div class="input-group-prepend">
                        <span class="px-3 input-group-text harsi-color fw-bold">
                            {{ __('reports')['hotel']['common']['from'] }}
                        </span>
                    </div>

                    <input type="date" id="from" class="form-control"
                        value="{{ now()->format('Y-m-01') }}">
                </div>

                {{-- To --}}
                <div class="mx-1 input-group">
                    <div class="input-group-prepend">
                        <span class="px-3 input-group-text harsi-color fw-bold">
                            {{ __('reports')['hotel']['common']['to'] }}
                        </span>
                    </div>

                    <input type="date" id="to" class="form-control"
                        value="{{ now()->format('Y-m-t') }}">
                </div>

                {{-- Submit --}}
                <button type="submit" class="mx-2 btn harsi-button">
                    {{ __('common_actions')['filter'] }}
                </button>
            </form>

        </section>

        {{-- Title for Print --}}
        <section class="mb-4">
            <h2 class="text-center col-lg-12" id="uno">
                {{ __('reports.hotel.statisticalReports.ingresos.revenues_per_period') }}
            </h2>
            <h3 class="mt-1 text-center col-lg-12 fw-bold" id="uno"><span id="period_of_incomes"></span></h3>
        </section>

        {{-- Summary Table --}}
        @include('hotel.reports.shared.tax-summary-card', [
            'card_width' => 60,
            'show_general_total' => false,
            'title_card' => __('reports')['hotel']['statisticalReports']['incomes']['title'],
        ])

        {{-- Table --}}
        <section class="my-1 table-responsive col-12">
            <table class="table text-center cardtable table-sm" id="incomes_table">
                <thead>
                    <tr class="cardtabletr">
                        <th class="text-center" colspan="4">{{ __('entities')['hotel']['reservation'] }}</th>
                        <th class="text-center" colspan="3">{{ __('reports')['hotel']['common']['payments'] }}</th>
                        <th class="text-center" rowspan="2" colspan="1">Total</th>
                    </tr>
                    <tr class="cardtabletr">
                        <th class="text-center th_minus" scope="col">{{ __('entity_fields')['common']['date'] }}</th>
                        <th class="text-center th_minus" scope="col">Folio</th>
                        <th class="text-center th_minus" scope="col">{{ __('entity_fields')['reservation']['client'] }}</th>
                        <th class="text-center th_minus" scope="col">{{ __('entity_fields')['reservation']['room'] }}</th>
                        <th class="text-center th_minus" scope="col">{{ __('reports')['hotel']['common']['income_type'] }}</th>
                        <th class="text-center th_minus" scope="col">{{ __('reports')['hotel']['common']['income'] }}</th>
                        <th class="text-center th_minus" scope="col">{{ __('entity_fields')['common']['payment_method'] }}</th>
                    </tr>
                </thead>
                <tfoot>
                    <tr id="main_total_row">
                        <th scope="row" colspan="7" class="text-right">
                            {{ __('reports')['hotel']['common']['total'] }}
                            <div id="tax_breakdown_disclaimer"></div>
                        </th>
                        <td class="text-center td-minus"><b id="total_incomes"></b></td>
                    </tr>
                </tfoot>
            </table>
        </section>
    </div>

    <script>
        // Global Controls
        $(document).ready(function () {
          // Hide TaxBreakdown
            $('#tax-summary-card').toggle();

          // Filter
            $('#incomes_period').on('submit', function (e) {
                e.preventDefault();
                incomesTable.ajax.reload();
            });

          // Table Controller
            const incomesTable = $('#incomes_table').DataTable({
                language: getDataTableLanguageConfig(),
                order: [[1, 'asc']],

                lengthMenu: [
                    [-1, 5, 10, 25, 50, 100],
                    ['All', 5, 10, 25, 50, 100]
                ],

                processing: true,
                serverSide: true,

                ajax: {
                    url: "{{ route('hotel.reports.incomePerPeriod') }}",
                    type: "GET",

                    data: function (d) {
                        d.start_date = $('#from').val();
                        d.end_date = $('#to').val();
                    }
                },

                columns: [
                    { data: 'date_entry', type: 'date' },
                    { data: 'id', name: 'id' },
                    { data: 'client_reference', name: 'client_reference' },
                    { data: 'room_name' },
                    { data: 'payment_types', orderable: false, searchable: false },
                    { data: 'payment_incomes', orderable: false, searchable: false },
                    { data: 'payment_methods', orderable: false, searchable: false },
                    { data: 'total_income' }
                ],

                drawCallback: function (settings) {
                  //* Control Data
                    const json = settings.json || {};
                    const incomes = json.data;
                    const total_incomes = json.totals;

                    let final_total = 0;

                  //* Compute Total
                    incomes.forEach(income => {
                        final_total += income.total_income_simple;
                    });

                    // Update Breakdown Configuration
                    HOTEL_TAX_BREAKDOWN_ENGINE.totals = total_incomes;

                    // Render Totals
                    $('#lodging_total').text( formatCurrency(total_incomes.lodging) );
                    $('#consumption_total').text( formatCurrency(total_incomes.consumption) );
                    $('#extras_total').text( formatCurrency(total_incomes.extras) );
                    $('#total_incomes').text( formatCurrency(final_total || 0) );

                    // Apply Taxes (Only if form has been submitted before)
                    if (HOTEL_TAX_BREAKDOWN_ENGINE.is_applied) applyHotelTaxes();
                }
            });
        });

        // Table Data cycle
        const cargarTabla = () => $('#incomes_table').DataTable().ajax.reload(null, false);
        $(document).ready(() => setInterval(cargarTabla, 30000) );  //Cada 30 segundos (30 mil milisegundos)

        // Print Report
            function imprimir() {
                const beforePrint = function () {
                    const from = $('#from').val();
                    const to = $('#to').val();

                    $('#period_of_incomes').text(`${formatDate(from)} - ${formatDate(to)}`);
                };

                if (isIosDevice()) {
                    openPrintWindow(beforePrint);
                } else {
                    beforePrint();
                    window.print();
                }
            }

            function print_csv() {
              // Control Data
                let start = $("#from").val();
                let end = $("#to").val();

              // Remove last illusionary form
                $('#csv_export_form').remove();

              // Build illusionary Form
                const form = $('<form>', {
                    id: 'csv_export_form',
                    method: 'POST',
                    action: '/hotel/csv/income-per-period',
                    style: 'display:none;',
                });

                // Append CSRF Token
                form.append(`
                    <input type="hidden" name="_token" value="{{ csrf_token() }}">
                `);

                // Append Request Data
                form.append(`
                    <input type="hidden" name="start" value='${start}'>
                    <input type="hidden" name="end" value='${end}'>
                `);

                // Append Tax Breakdown
                form.append(`
                    <input type="hidden" name="tax_breakdown"
                        value='${JSON.stringify(HOTEL_TAX_BREAKDOWN_ENGINE)}'
                    >
                `);

                // Submit Illusionary form
                $('body').append(form);
                form.trigger('submit');

                // Automatic Form Removal
                setTimeout(() => { form.remove() }, 1000);
            }

        // Tax Breakdown Configuration
        const sections = ['lodging', 'consumption', 'extra'];

        const HOTEL_TAX_BREAKDOWN_ENGINE = {
            is_applied: false,
            is_notified: false,

            table_selector: '#example',
            sections: {},

            totals: {
                lodging: 0,
                consumption: 0,
                extras: 0,
                final: 0
            },

            taxes: {
                lodging: [],
                consumption: [],
                extras: []
            }
        };

        function renderHotelBreakdown(data) {
            $('#main_total_row, #tax-summary-card').show();

            sections.forEach(section => {
                renderSection(section, data[section === 'extra' ? 'extras' : section]);
            });
        }

        function spreadResetActions() {
          // Hide breakdown section
            $('#main_total_row, #tax-summary-card').hide();
        }

    </script>

@endsection
