@extends('layouts.reports')

@section('title')
{{ __('modules')['dashboard']['restaurant']['title'] }} | {{ __('reports.restaurant.statisticalReports.ingresos.day_balance') }}
@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;
        }
        small {
            font-size: 90%;
        }
    </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('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.day_balance') }}
                </h5>
            </div>

        </section>

        {{-- Title for Print --}}
        <section class="mb-4">
            <h3 class="text-center col-lg-12" id="uno">
                {{ __('reports.restaurant.statisticalReports.ingresos.day_balance') }}
            </h3>
            <h2 class="mt-1 text-center col-lg-12 fw-bold" id="uno">
                {{ date("Y-m-d") }}
            </h2>
        </section>

        {{-- Table --}}
        <section class="my-1 table-responsive col-12">
            <table class="table text-center cardtable"id="example">
                <thead>
                    <tr class="cardtabletr">
                        <th class="text-center" scope="col" width="6%">Folio</th>
                        <th class="text-center" scope="col" width="7%">{{ __('entity_fields')['order']['time'] }}</th>
                        <th class="text-center" scope="col" width="12%">{{ __('entity_fields')['order']['table'] }}</th>
                        <th class="text-center" scope="col" width="15%">{{ __('entity_fields')['order']['cashier'] }}</th>
                        <th class="text-center" scope="col" width="33.5%">{{ __('entity_fields')['order']['items'] }}</th>
                        <th class="text-center" scope="col">{{ __('entity_fields')['common']['payment_method'] }}</th>
                        <th class="text-center" scope="col">{{ __('entity_fields')['order']['total'] }}</th>
                    </tr>
                </thead>
                <tfoot>
                    <tr id="main_total_row">
                        <th scope="row" colspan="6" 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>
        // Formats
            function convertCurrencyStringToNumber(currencyString) {
                return parseFloat(currencyString.replace(/\$/g, "").replace(/,/g, ""));
            }

        // Table Core
            // Global Controls
            $(document).ready(function () {
                const reportTable = $('#example').DataTable({
                    order: [0, 'asc'],

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

                    language: getDataTableLanguageConfig(),
                    ajax: {
                        url: "{{ route('restaurant.reports.dailyRestaurantIncome') }}",

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

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

                            //  Update Breakdown Configuration
                            TAX_BREAKDOWN_ENGINE.total = final_total;

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

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

                            return incomes;
                        }
                    },
                    columns: [
                        {
                            data: 'id', name: 'id',
                            searchable: true
                        },
                        {
                            data: 'time', name: 'time',
                            searchable: true
                        },
                        {
                            data: 'order_table', name: 'order_table',
                            searchable: true
                        },
                        {
                            data: 'order_cashier', name: 'order_cashier',
                            searchable: false
                        },
                        {
                            data: 'products', name: 'products',
                            searchable: false
                        },
                        {
                            data: 'order_payment_method', name: 'order_payment_method',
                            searchable: false
                        },
                        {
                            data: 'order_total', name: 'order_total',
                            searchable: false
                        },
                    ]
                });
            });

            // 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() {
                if (isIosDevice()) {
                    openPrintWindow();
                } else {
                    window.print();
                }
            }

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

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

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

                // 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: 6,
            };
    </script>

@endsection
