@extends('layouts.reports')

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

            {{-- Filter Form --}}
            <form id="incomes_period" class="flex-wrap py-2 d-flex align-items-center">
                {{-- From --}}
                <div class="mx-1 input-group" style="width: 210px;">
                    <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" style="width: 210px;">
                    <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>

                <div class="mx-1 input-group" style="width: 170px;">
                    <select id="payment_method" class="form-control" required>
                        <option value="" disabled selected>-- {{ __('common_actions')['select'] }} --</option>
                        @foreach ($paymentMethods as $method)
                            <option value="{{ $method->method_name }}">{{ $method->method_name }}</option>
                        @endforeach
                    </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">
            <h1 class="text-center pdf_title col-lg-12" id="uno">
                {{ __('reports.hotel.statisticalReports.ingresos.revenues_per_period_and_payment_method') }}
            </h1>
            <h3 class="mt-3 text-center col-lg-12" id="uno">
                <span id="period_of_incomes"></span>
                &nbsp;&nbsp;|&nbsp;&nbsp;
                <span id="pm_of_incomes">{{ __('neutral_words')['all'] }}</span>
            </h3>
        </section>

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

                {{-- Header --}}
                <thead>
                    <tr class="cardtabletr">
                        <th class="text-center" scope="col">{{ __('entity_fields')['common']['date'] }}</th>
                        <th class="text-center" scope="col">Folio</th>
                        <th class="text-center" scope="col">{{ __('entity_fields')['reservation']['client'] }}</th>
                        <th class="text-center" scope="col">{{ __('entity_fields')['reservation']['room'] }}</th>

                        <th class="text-center" scope="col" @if($has_itemized_taxes_reports) width="17%" @endif>
                            {{ __('reports')['hotel']['common']['lodging'] }}
                        </th>
                        <th class="text-center" scope="col" @if($has_itemized_taxes_reports) width="17%" @endif>
                            {{ __('reports')['hotel']['common']['consumption'] }}
                        </th>
                        <th class="text-center" scope="col" @if($has_itemized_taxes_reports) width="17%" @endif>
                            {{ __('reports')['hotel']['common']['extras'] }}
                        </th>

                        <th class="text-center" scope="col">Total</th>
                    </tr>
                </thead>

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

                        {{-- Lodging --}}
                        <td class="text-center broken-cell-alignment">
                            <div id="lodging_breakdown_container">
                                <div class="fw-bold" id="lodging_payments">
                                    0.00
                                </div>
                            </div>
                        </td>

                        {{-- Consumption --}}
                        <td class="text-center broken-cell-alignment">
                            <div id="consumption_breakdown_container">
                                <div class="fw-bold" id="consumption_payments">
                                    0.00
                                </div>
                            </div>
                        </td>

                        {{-- Extras --}}
                        <td class="text-center broken-cell-alignment">
                            <div id="extras_breakdown_container">
                                <div class="fw-bold" id="extra_payments">
                                    0.00
                                </div>
                            </div>
                        </td>

                        <td class="text-center"><b id="total_incomes"></b></td>
                    </tr>
                </tfoot>
            </table>
        </section>

    </div>

    <script>
        // Global Controls
        $(document).ready(function () {

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

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

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

                processing: false,
                serverSide: true,

                ajax: {
                    url: "{{ route('hotel.reports.incomePerPeriodAndPaymentMethod') }}",
                    type: "GET",
                    data: function (d) {
                        d.start_date = $('#from').val();
                        d.end_date = $('#to').val();
                        d.payment_method = $('#payment_method').val();
                    }
                },

                columns: [
                    { data: 'date_entry', name: 'date_entry', type: 'date' },
                    { data: 'id', name: 'id' },
                    { data: 'client_reference', name: 'client_reference' },
                    { data: 'room_name' },
                    { data: 'lodgingPayments' },
                    { data: 'consumptionPayments' },
                    { data: 'extraPayments' },
                    { data: 'totalIncome' },
                ],

                drawCallback: function (settings) {

                    //* Control Data
                    const json = settings.json || {};

                    //* Compute Totals
                    const totals = json.data.reduce((acc, item) => {
                        acc.lodging += item.lodgingPaymentsSimple || 0;
                        acc.consumption += item.consumptionPaymentsSimple || 0;
                        acc.extras += item.extraPaymentsSimple || 0;
                        acc.final += item.totalIncomeSimple || 0;
                            return acc;
                    }, {
                        lodging: 0,
                        consumption: 0,
                        extras: 0,
                        final: 0
                    });

                    //* Update Breakdown Configuration
                    HOTEL_TAX_BREAKDOWN_ENGINE.totals = totals;

                    //* Totals
                    $('#lodging_payments').html(
                        formatCurrency(totals.lodging || 0.00)
                    );

                    $('#consumption_payments').html(
                        formatCurrency(totals.consumption || 0.00)
                    );

                    $('#extra_payments').html(
                        formatCurrency(totals.extras || 0.00)
                    );

                    $('#total_incomes').html(
                        formatCurrency(totals.final || 0.00)
                    );

                    // 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));

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

                    const payment_method = $('#payment_method').val()
                        ? $('#payment_method').val() : "{{ __('neutral_words')['all'] }}";

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

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

            function print_csv() {
                // Extract Data
                var start = $("#from").val();
                var end = $("#to").val();
                const payment_method = $('#payment_method').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-and-payment-method',
                    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}'>
                    <input type="hidden" name="payment_method" value='${payment_method}'>
                `);

                // 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_payments',
                        container_selector: '#lodging_breakdown_container'
                    },

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

                    extras: {
                        total_selector: '#extra_payments',
                        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();
                });
            }

    </script>

@endsection
