@extends('layouts.reports')

@section('title')
{{ __('modules')['dashboard']['restaurant']['title'] }} | {{ __('reports.restaurant.statisticalReports.ingresos.balances_per_period_and_amenities') }}
@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('restaurant.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.common-tax-calculator-dropdown')
                    @endif
                </div>

                {{-- Title --}}
                <h5 class="mb-0 oculto-impresion">
                    {{ __('reports.restaurant.statisticalReports.ingresos.balances_per_period_and_amenities') }}
                </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.restaurant.statisticalReports.ingresos.balances_per_period_and_amenities') }}
            </h2>
            <h3 class="mt-1 text-center col-lg-12 fw-bold" id="uno"><span id="period_of_incomes"></span></h3>
        </section>

        {{-- Table --}}
        <section class="my-1 table-responsive col-12">
            <table class="table text-center cardtable table-sm" id="example">
                <thead>
                    <tr class="cardtabletr">
                        <th class="text-center" scope="col" width="15%">{{ __('entity_fields')['common']['date'] }}</th>
                        <th class="text-center" scope="col" width="10%">{{ __('entities')['restaurant']['order'] }}</th>
                        <th class="text-center" scope="col" width="25%">{{ __('entity_fields')['order']['item'] }}</th>
                        <th class="text-center" scope="col">{{ __('entity_fields')['order']['quantity'] }}</th>
                        <th class="text-center" scope="col">{{ __('entity_fields')['common']['price'] }}</th>
                        <th class="text-center" scope="col">{{ __('entity_fields')['order']['subtotal'] }}</th>
                    </tr>
                </thead>
                <tfoot>
                    <tr id="main_total_row">
                        <th scope="row" colspan="5" class="text-right">
                            {{ __('reports')['restaurant']['common']['total_incomes'] }}
                            <div id="tax_breakdown_disclaimer"></div>
                        </th>
                        <td class="text-center"><b id="total_incomes"></b></td>
                    </tr>
                </tfoot>
            </table>
        </section>

    </div>

    <script>

        // Data Table
        $(document).ready(function () {
          // Filter
            $('#incomes_period').submit(function(event) {
                event.preventDefault();
                incomesTable.ajax.reload();
            });

          // Table Controller
            const incomesTable = $('#example').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('restaurant.reports.incomePerPeriodAndAmenities') }}",

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

                    dataSrc: function (result) {
                        const incomes = result.data;
                        let final_total = 0;

                        incomes.forEach(income => {
                            final_total += convertCurrencyStringToNumber(income.subtotal);
                        });

                        //  Update Breakdown Configuration
                        TAX_BREAKDOWN_ENGINE.total = final_total;

                        // Render Total
                        $('#total_incomes').text( formatCurrency(final_total.toFixed(2)) );

                        // Apply Taxes (Only if form has been submitted before)
                        if (TAX_BREAKDOWN_ENGINE.is_applied) applyTaxes();


                        return incomes;
                    }
                },

                columns: [
                    { data: 'order_date', name: 'order_date', searchable: true },
                    { data: 'order_id', name: 'order_id', searchable: true },
                    { data: 'item', name: 'item', searchable: true },
                    { data: 'item_quantity', name: 'item_quantity', searchable: false },
                    { data: 'item_price', name: 'item_price', searchable: false },
                    { data: 'subtotal', name: 'subtotal', searchable: false },
                ],
            });

            // Recarga periódica
            setInterval(function () {
                cargarTabla();
            }, 30000);
        });


        // Table Data cycle
        const cargarTabla = () => $('#example').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: '/restaurant/csv/income-per-period-and-amenities',
                    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(TAX_BREAKDOWN_ENGINE)}'
                    >
                `);

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

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

          // Tax Breakdown Configuration
            const TAX_BREAKDOWN_ENGINE = {
                table_selector: '#example',
                total_selector: '#total_incomes',
                total: 0,

                taxes: [],
                is_applied: false,
                is_notified: false,
                colspan_footer: 5,
            };

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

@endsection
