@extends('layouts.reports')

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

@section('content')

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

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

    {{-- 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_month') }}
                </h5>
            </div>

            {{-- Filter Form --}}
            <form id="filter_report" class="py-2 d-flex align-items-center">
                {{-- Year --}}
                <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']['filter_by_year'] }}
                        </span>
                    </div>

                    <select id="year" class="form-control">
                        @for ($year = 2024; $year < now()->addYears(7)->year; $year++)
                            <option value="{{ $year }}"
                                @if(now()->year == $year) selected @endif
                            >{{ $year }}</option>
                        @endfor
                    </select>
                </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_month') }}
            </h2>
        </section>

        {{-- Table --}}
        <section class="mx-auto my-1 table-responsive col-10">
            <table class="table text-center cardtable" id="incomes_table">

                {{-- Header --}}
                <thead>
                    <tr class="cardtabletr">
                        <th class="text-center" scope="col">{{ __('neutral_words')['month'] }}</th>
                        <th class="text-center" scope="col">Total ({{ __('reports')['hotel']['common']['lodging'] }})</th>
                        <th class="text-center" scope="col">Total ({{ __('reports')['hotel']['common']['consumption'] }})</th>
                        <th class="text-center" scope="col">Total ({{ __('reports')['hotel']['common']['extras'] }})</th>
                    </tr>
                </thead>

                {{-- Footer --}}
                <tfoot class="table-bordered">
                    <tr>
                        {{-- Title --}}
                        <th scope="row" class="text-center">
                            {{ __('reports')['hotel']['common']['totals'] }}
                        </th>

                        {{-- Lodging --}}
                        <td class="px-4 text-center">
                            <div id="lodging_breakdown_container">
                                <div class="fw-bold" id="lodging_incomes">
                                    0.00
                                </div>
                            </div>
                        </td>

                        {{-- Consumption --}}
                        <td class="px-4 text-center">
                            <div id="consumption_breakdown_container">
                                <div class="fw-bold" id="consumption_incomes">
                                    0.00
                                </div>
                            </div>
                        </td>

                        {{-- Extras --}}
                        <td class="px-4 text-center">
                            <div id="extras_breakdown_container">
                                <div class="fw-bold" id="extra_incomes">
                                    0.00
                                </div>
                            </div>
                        </td>

                    </tr>
                </tfoot>
            </table>
        </section>

    </div>

    <script>

        $(document).ready(function () {
          // Redraw Table for Filter
            $('#filter_report').on('submit', function (e) {
                e.preventDefault();
                reportTable.ajax.reload();
            });


          // Table Controller
            const reportTable =  $('#incomes_table').DataTable({
                language: getDataTableLanguageConfig(),
                "order": [],
                "pageLength": 12,

                paging: false,
                searching: false,
                serverSide: true,
                processing: false,

                ajax: {
                    url: "{{ route('hotel.reports.incomePerMonth') }}",
                    type: "GET",
                    data: function (d) {
                        d.year = $('#year').val();
                    },

                    dataSrc: function (result) {
                      // Control Data
                        const incomes = result.data;
                        const totals = {
                            lodging: 0.0,
                            consumption: 0.0,
                            extras: 0.0,
                            final: 0.0,
                        };

                      // Compute incomes per origin
                        console.log(incomes);

                        incomes.forEach(income => {
                            let lodging_payments = income.income_lodging;
                            let consumption_payments = income.income_consumption;
                            let extra_payments = income.income_extras;

                            totals.lodging += lodging_payments;
                            totals.consumption += consumption_payments;
                            totals.extras += extra_payments;
                            totals.final += (lodging_payments + consumption_payments + extra_payments);
                        });

                      // Update Breakdown Configuration
                        HOTEL_TAX_BREAKDOWN_ENGINE.totals = totals;

                      // Render Totals
                        $('#lodging_incomes').text( formatCurrency(totals.lodging) );
                        $('#consumption_incomes').text( formatCurrency(totals.consumption) );
                        $('#extra_incomes').text( formatCurrency(totals.extras) );

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

                        return incomes;
                    }
                },
                columns: [
                    { data: 'income_month', name: 'income_month', type: 'date' },
                    { data: 'income_lodging', name: 'income_lodging' },
                    { data: 'income_consumption', name: 'income_consumption' },
                    { data: 'income_extras', name: 'income_extras' },
                ]
            });
        });

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

        // Report Interactions
            function imprimir() {
                if (isIosDevice()) {
                    openPrintWindow();
                } else {
                    window.print();
                }
            }

            function print_csv() {
                // Extract Data
                let year = $("#year").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-month/',
                    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="year" value='${year}'>
                `);

                // 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 HOTEL_TAX_BREAKDOWN_ENGINE = {
                is_applied: false,
                is_notified: false,

                table_selector: '#incomes_table',
                sections: {
                    lodging: {
                        total_selector: '#lodging_incomes',
                        container_selector: '#lodging_breakdown_container'
                    },

                    consumption: {
                        total_selector: '#consumption_incomes',
                        container_selector: '#consumption_breakdown_container'
                    },

                    extras: {
                        total_selector: '#extra_incomes',
                        container_selector: '#extras_breakdown_container'
                    }
                },

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

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

            function renderHotelBreakdown(data) {
                renderSectionBreakdown({
                    section: 'lodging',
                    result: data.lodging
                });

                renderSectionBreakdown({
                    section: 'consumption',
                    result: data.consumption
                });

                renderSectionBreakdown({
                    section: 'extras',
                    result: data.extras
                });
            }

            function spreadResetActions() {
                Object.keys(HOTEL_TAX_BREAKDOWN_ENGINE.sections).forEach(function(key) {
                    const section = HOTEL_TAX_BREAKDOWN_ENGINE.sections[key];

                    const container = section.container_selector;
                    const idToSave = section.total_selector.replace('#', '');

                    $(container).contents().filter(function() {
                        return this.id !== idToSave;
                    }).remove();
                });
            }

        // Formats
            function convertCurrencyStringToNumber(currencyString) {
                return parseFloat(currencyString.replace(/\$/g, "").replace(/,/g, ""));
            }

    </script>

@endsection
