@extends('layouts.reports')

@section('title')
Hotel | {{ __('reports.hotel.statisticalReports.ingresos.balances_per_period') }}
@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.balances_per_period') }}
                </h5>
            </div>

            {{-- Filter Form --}}
            <form id="filter_report" 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.balances_per_period') }}
            </h2>
            <h3 class="mt-1 text-center col-lg-12 fw-bold" id="uno"><span id="period_of_balances"></span></h3>
        </section>

        {{-- Table --}}
        <section class="my-1 table-responsive col-12">
            <table class="table text-center table-sm cardtable" id="example">

                {{-- Header --}}
                <thead>
                    <tr class="cardtabletr">
                        <th class="text-center th_minus" colspan="4">{{ __('entities')['hotel']['reservation'] }}</th>
                        <th class="text-center th_minus" colspan="3">{{ __('reports')['hotel']['common']['lodging'] }}</th>
                        <th class="text-center th_minus" colspan="3">{{ __('reports')['hotel']['common']['consumption'] }}</th>
                        <th class="text-center th_minus" colspan="3">{{ __('reports')['hotel']['common']['extras'] }}</th>
                    </tr>
                    <tr class="cardtabletr">
                        <th class="text-center th_minus" scope="col">ID</th>
                        <th class="text-center th_minus" scope="col">{{ __('entity_fields')['reservation']['client'] }}</th>
                        <th class="text-center th_minus" scope="col">Checkout</th>
                        <th class="text-center th_minus" scope="col">{{ __('reports')['hotel']['common']['attended_by'] }}</th>
                        <th class="text-center th_minus" scope="col">{{ __('entity_fields')['reservation']['contract'] }}</th>
                        <th class="text-center th_minus" scope="col">{{ __('reports')['hotel']['common']['balance'] }}</th>
                        <th class="text-center th_minus" scope="col">{{ __('reports')['hotel']['common']['paid'] }} </th>
                        <th class="text-center th_minus" scope="col">{{ __('entity_fields')['reservation']['contract'] }}</th>
                        <th class="text-center th_minus" scope="col">{{ __('reports')['hotel']['common']['balance'] }}</th>
                        <th class="text-center th_minus" scope="col">{{ __('reports')['hotel']['common']['paid'] }} </th>
                        <th class="text-center th_minus" scope="col">{{ __('entity_fields')['reservation']['contract'] }}</th>
                        <th class="text-center th_minus" scope="col">{{ __('reports')['hotel']['common']['balance'] }}</th>
                        <th class="text-center th_minus" scope="col">{{ __('reports')['hotel']['common']['paid'] }} </th>
                    </tr>
                </thead>

                {{-- Footer --}}
                <tfoot class="table-bordered">
                    <tr>
                        {{-- Title --}}
                        <th scope="row" colspan="4" class="pr-3 text-left broken-cell-alignment">
                            {{ __('reports')['hotel']['common']['totals'] }}
                            <div id="tax_breakdown_disclaimer"></div>
                        </th>

                        {{-- Lodging --}}
                        <td colspan="3" class="text-right broken-cell-alignment">
                            <div id="lodging_breakdown_container">
                                <div class="fw-bold" id="lodging_incomes">
                                    0.00
                                </div>
                            </div>
                        </td>

                        {{-- Consumption --}}
                        <td colspan="3" class="text-right broken-cell-alignment">
                            <div id="consumption_breakdown_container">
                                <div class="fw-bold" id="consumption_incomes">
                                    0.00
                                </div>
                            </div>
                        </td>

                        {{-- Extras --}}
                        <td colspan="3" class="text-right broken-cell-alignment">
                            <div id="extras_breakdown_container">
                                <div class="fw-bold" id="extra_incomes">
                                    0.00
                                </div>
                            </div>
                        </td>

                    </tr>
                </tfoot>

            </table>
        </section>

    </div>

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

            // Table Controller
            const reportTable = $('#example').DataTable({
                language: getDataTableLanguageConfig(),
                lengthMenu: [[-1, 5, 10, 25, 50, 100], ['All', 5, 10, 25, 50, 100]],
                "order": [0, 'asc'],
                processing: false,
                serverSide: true,

                ajax: {
                    url: "{{ route('hotel.reports.checkoutBalances') }}",
                    type: "GET",
                    data: function (d) {
                        d.from = $('#from').val();
                        d.to = $('#to').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
                        incomes.forEach(income => {
                            let lodging_payments = convertCurrencyStringToNumber(income.lodging_payments);
                            let consumption_payments = convertCurrencyStringToNumber(income.consumption_payments);
                            let extra_payments = convertCurrencyStringToNumber(income.extra_payments);

                            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: 'id', name: 'id' },
                    { data: 'client_reference', name: 'client_reference' },
                    { data: 'date_departure', name: 'date_departure', type: 'date' },
                    { data: 'recepcionist' },
                    { data: 'lodging_contract', name: 'lodging_contract' },
                    { data: 'total_price', name: 'total_price' },
                    { data: 'lodging_payments' },
                    { data: 'consumption_contract', name: 'consumption_contract' },
                    { data: 'consumption_charges' },
                    { data: 'consumption_payments' },
                    { data: 'extras_contract', name: 'extras_contract' },
                    { data: 'extra_charges' },
                    { data: 'extra_payments' },
                ]
            });
        });

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

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

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

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

            function print_csv() {
                // Extract Data
                var start = $("#from").val();
                var 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/checkout-balances',
                    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 HOTEL_TAX_BREAKDOWN_ENGINE = {
                is_applied: false,
                is_notified: false,

                table_selector: '#example',
                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
