{{-- Styles --}}
    <link href="{{ asset('css/pages/particular/comanda.css') }}" rel="stylesheet">
    <link href="{{ asset('css/components/custom/specialElements.css') }}" rel="stylesheet">

{{-- Headers & Configurations --}}
@extends('layouts.app')
@section('title')
    {{ __('modules')['home']['commands'] }}
@endsection

{{-- Control Variables --}}
    @php
        $has_discounts = \App\Helpers\Environment\SystemFeaturesHelper::getFeatureStatus("discounts");
        $has_product_barcodes = \App\Helpers\Environment\SystemFeaturesHelper::getFeatureStatus("product_barcodes");
    @endphp

{{-- Content --}}
@section('content')
    {{-- Estilos --}}
    <style>
        /* Tags */
        body{
            overflow-x: hidden;
        }

        label{
            font-weight: bold;
            padding-left: .4rem
        }

        /* Forms */
        .disabled-fields {
            background-color:#D7D6C2 !important;
            cursor: no-drop !important;
        }

        .search-container {
            position: relative;
        }

        .search-input {
            padding-left: 2.5rem;
        }

        .search-icon {
            position: absolute;
            top: 50%;
            left: 15px;
            transform: translateY(-50%);
            color: #888888c2;
        }

        /* Boxes */
        .bottom-divisor {
            border-bottom: 1.5px solid #576469;
            padding-bottom: .7rem !important;
        }

        /* Text */
        .section-title {
            font-size: 1.15rem;
            font-weight: bold;
            text-transform: uppercase;

            color: #306377 !important;
        }

        /* Medias */
        @media print {
            .oculto-impresion {
                display: none !important;
            }
        }
    </style>

    {{-- Content --}}
    <form method="POST" id="restaurant_form"
        class="pl-3 pr-3 form-horizontal oculto-impresion" enctype="multipart/form-data"
    > @csrf

        {{-- Encabezado --}}
        @include('restaurant.commands.components.form.header')

        {{-- Cuerpo --}}
        @include('restaurant.commands.components.form.body')

    </form>

    @include('restaurant.commands.components.ticket')
@endsection

{{-- Footer --}}
@section('footer')
    @include('shared.components.footer.basic-footer')
@endsection

{{-- Scripts --}}
@section('scripts')

    {{-- Screen Behavior --}}
    <script>
        $(document).ready(function(){
          //* Visual Behavior
            // Toggle Sections
            $("#refuse_payment").hide();
            $("#save_order_section, #discount_section, #discount_product_section").hide();
            displayBarcodeReader();

            // Assign Ticket Values
            $("#mesa").on("change", () => $("#ticket_table").text($("#mesa").val()));
            $("#forma_pago").on("change", () => $("#ticket_method").text($("#forma_pago").val()));

          //* Render Interactions
            // Calcular Cambio
            $("#pago_recibido").keyup(function() {
                if ($(this).val() !== "") getPayBack();
            });

          //* Define interactions
            // Save Commands
            $("#save_selected_product").on("click", saveSelectedProduct);
            $("#save_extra_product").on("click", saveExtraProduct);

            // Search bar
            const searchDebounced = debounce(onSelectChange, 500); // 500ms
            $('#search_bar').on('input', searchDebounced);
            $('#select_product').on('change',onSelectProduct);

            // Avoid Manual Print
            $(document).on('keydown', function(e) {
                if((e.ctrlKey || e.metaKey) && (e.key == "p" || e.charCode == 16 || e.charCode == 112 || e.keyCode == 80) ){
                    e.cancelBubble = true;
                    e.preventDefault();

                    e.stopImmediatePropagation();
                }
            });
        });
    </script>

    {{-- Support Functions --}}
    <script>
      //* Interactions
        // Round Decimals
        function redondearDecimales(inputId) {
            let result = 0;
            let value = parseFloat( $(`#${inputId}`).val() );

            let numeroRegexp = new RegExp('\\d\\.(\\d){' + 2 + ',}');   // Expresion regular para numeros con un cierto numero de decimales o mas

            if (numeroRegexp.test(value)) { // Ya que el numero tiene el numero de decimales requeridos o mas, se realiza el redondeo
                result = Number(value.toFixed(2));
                $("#"+inputId).val(result);
            } else {
                result = Number(value.toFixed(2)) === 0 ? 0 : value;  // En valores muy bajos, se comprueba si el numero es 0 (con el redondeo deseado), si no lo es se devuelve el numero otra vez.
                $("#"+inputId).val(result);
            }
        }

      //* Alerts
        function showErrorSwal(message) {
            Swal.fire({
                title: `{{ __('common_responses_and_messages')['whoops'] }}`,
                text: message,
                icon: "error"
            });
        }

        function launchSwalToast(icon, title) {
            Swal.fire({
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 5000,
                // timerProgressBar: true,
                title,
                icon,
            });
        }

      //* Math Support
        // Calcular Cambio
        function getPayBack() {
            const totalPedido = parseFloat($('#total_orden_illusory').val()) || 0;
            const pagoRecibido = parseFloat($('#pago_recibido').val()) || 0;
            const payback = (pagoRecibido - totalPedido).toFixed(2);

            $('#payback').val(payback);

            const isNegative = parseFloat(payback) < 0;

            $('#save_order_section').toggle(!isNegative);
            $('#refuse_payment').toggle(isNegative);
            $('#save_order').prop('disabled', isNegative);

            if (!isNegative) {
                $('#ticket_payment').text(formatCurrency(pagoRecibido.toFixed(2)));
                $('#ticket_change').text(formatCurrency(payback));
            }
        }

        // Calcular Descuento General
        function calculateDiscount() {
            if (getFeatureStatus("discounts")){
                const total = $("#total_orden").val();
                const discount_percentage = $("#discount_percentage").val();

                const discount = (total * discount_percentage) / 100;
                const discounted_amount = (total - discount).toFixed(2);

                $("#discount").val(discount.toFixed(2));
                $("#total_orden_illusory").val(discounted_amount);

                $("#ticket_total").text(formatCurrency(discounted_amount, false, true));
                $("#ticket_discount").text(`${parseFloat(discount_percentage).toFixed(2) ?? 0.0} %`);
            }

            return;
        }

        // Calcular Descuento de Producto
        function calculateProductDiscount() {
            const total = $("#selected_product_original_price").val();
            const discount_percentage = $("#selected_product_discount").val();

            const discount = (total * discount_percentage) / 100;
            const discounted_amount = (total - discount).toFixed(2);

            $("#selected_product_price").val(discounted_amount);
        }

      //* Render Support
        function buildRowKey(item, category, price) {
            const normItem = (item ?? "").toString().trim().toLowerCase();
            const normCategory = (category ?? "").toString().trim();
            const normPrice = Number(price).toFixed(2);

            return `${normItem}|${normCategory}|${normPrice}`; // Return Command Tracker with normalized data
        }
    </script>

    {{-- Commands Manager --}}
    <script>
      //* General Data
        let cont = 0; // Item Count
        let total = 0; // Order Total

        const subtotal = []; // Items Subtotal
        const rowKeyToIndex = {}; // Mapped Commands { "Command Tracker" : "Command ID" }

      //* Store Commands
        function saveSelectedProduct() {
            const item = $("#selected_product_name").val();
            const category_id = $("#selected_product_category").val();
            const quantity = parseFloat($("#selected_product_quantity").val());
            const item_price = parseFloat($("#selected_product_price").val());

            if (item && quantity > 0 && !isNaN(item_price)) {
                stackOrAddCommand(item, category_id, quantity, item_price);

                launchSwalToast(
                    'success',
                    "{{ __('common_responses_and_messages')['applying_changes'] }}"
                );

                clearProductFields();
                clearBarcodeFields();
                allowSubmit();
            } else {
                showErrorSwal(`{{ __('entity_forms')['orders']['item_error'] }}`);
            }
        }

        function saveExtraProduct() {
            const extra_item = $("#extra_product_name").val();
            const extra_item_price = parseFloat($("#extra_product_price").val());
            const extra_item_quantity = parseFloat($("#extra_product_quantity").val());

            if (extra_item && extra_item_quantity > 0 && !isNaN(extra_item_price)) {
                stackOrAddCommand(extra_item, "", extra_item_quantity, extra_item_price);

                launchSwalToast(
                    'success',
                    "{{ __('common_responses_and_messages')['applying_changes'] }}"
                );

                clearExtraFields();
                allowSubmit();
            } else {
                showErrorSwal(`{{ __('entity_forms')['orders']['extra_item_error'] }}`);
            }
        }

        function searchProductByBarcode(barcode) {
            $.get(`/api/products/search-by-codebar`, { barcode }, function(product) {
              //* Case: Product not Found
                if (!product || product === null) {
                    launchSwalToast(
                        'warning',
                        "{{ __('entity_forms')['orders']['product_not_found'] }}"
                    );

                    clearBarcodeFields();
                    return;
                }

              //* Register Command
                // Extract product data
                const item = product.product_name;
                const category_id = product.category_id;
                const quantity = parseFloat(1);
                const item_price = parseFloat(product.product_price);

                // Draw and Reset
                stackOrAddCommand(item, category_id, quantity, item_price);

                launchSwalToast(
                    'success',
                    "{{ __('common_responses_and_messages')['applying_changes'] }}"
                );

                clearProductFields(); clearBarcodeFields();
                allowSubmit();
            });
        }

      //* Draw Commands
        // Action Selector
        function stackOrAddCommand(item, category_id, quantity, item_price) {
            const key = buildRowKey(item, category_id, item_price); // Build Command Tracker

          // If Command Tracker already exist, update rows
            if (rowKeyToIndex[key] !== undefined) {
                const index = rowKeyToIndex[key]; // Extract Command ID

                // Extract old Values
                const old_subtotal = subtotal[index] ?? 0;
                const old_quantity = parseFloat($(`#order_row_${index} input[name="cantidad[]"]`).val()) || 0;

                // Calculate new Values
                const new_quantity = old_quantity + quantity;
                const new_subtotal = new_quantity * item_price;

                // Ajuste de totales manteniendo tu lógica
                total = total - old_subtotal + new_subtotal;
                subtotal[index] = new_subtotal;

                // Update DOM
                updateSummaryRow(index, new_quantity, item_price, new_subtotal);
                updateTicketRow(index, item, new_quantity, item_price, new_subtotal);
                updateTotals();

                return { stacked: true, index };
            }

          // Else, create row
            // Define Values
            const index = cont++;
            const sub = quantity * item_price;
            subtotal[index] = sub;
            total += sub;

            rowKeyToIndex[key] = index;

            // Render Changes
            addSummaryRow(index, item, category_id, quantity, item_price, sub);
            addTicketRow(item, quantity, item_price, sub, index);
            updateTotals();

            return { stacked: false, index };
        }

        // Update Rows
        function updateSummaryRow(index, new_quantity, price, new_subtotal) {
            const $row = $(`#order_row_${index}`); // Search row to Update

            // Update hidden values
            $row.find(`input[name="cantidad[]"]`).val(new_quantity); // Quantity
            $row.find(`input[name="precio_articulo[]"]`).val(price); // P.U
            $row.find(`input[name="subtotal[]"]`).val(new_subtotal); // Subtotal

            // Redraw visual values
            // Only replace text using the nodeType 3 (https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType)
                $row.find("td").eq(2).contents().filter(function(){ return this.nodeType === 3; }).remove();
                $row.find("td").eq(2).append(`${new_quantity}`); // Quantity

                $row.find("td").eq(3).contents().filter(function(){ return this.nodeType === 3; }).remove();
                $row.find("td").eq(3).append(`${Number(price).toFixed(2)}`); // Price

                $row.find("td").eq(4).contents().filter(function(){ return this.nodeType === 3; }).remove();
                $row.find("td").eq(4).append(`${Number(new_subtotal).toFixed(2)}`); // Subtotal
        }

        function updateTicketRow(index, item, new_quantity, price, new_subtotal) {
            const $trow = $(`#ticket_row_${index}`); // Search ticket row to Update

            // Redraw visual values
                $trow.find("td").eq(0).text(new_quantity); // Quantity
                $trow.find("td").eq(1).text(item); // Item
                $trow.find("td").eq(2).text(formatCurrency(Number(price).toFixed(2))); // Price
                $trow.find("td").eq(3).text(formatCurrency(Number(new_subtotal).toFixed(2))); // Subtotal
        }

        // Append new Rows
        function addSummaryRow(index, item, category, quantity, price, subtotal) {
            $("#order-table-body").append(`
                <tr class="selected" id="order_row_${index}">
                    <td>
                        <button type="button" class="btn btn-danger" onclick="deleteCommand(${index})"><i class="fas fa-trash"></i></button>
                    </td>
                    <td>
                        <input type="hidden" name="articulo[]" value="${item}">
                        <input type="hidden" name="categoria[]" value="${category}">
                        ${item}
                    </td>
                    <td>
                        <input type="hidden" name="cantidad[]" value="${quantity}">
                        ${quantity}
                    </td>
                    <td>
                        <input type="hidden" name="precio_articulo[]" value="${price}">
                        ${price.toFixed(2)}
                    </td>
                    <td>
                        <input type="hidden" name="subtotal[]" value="${subtotal}">
                        ${subtotal.toFixed(2)}
                    </td>
                </tr>
            `);
        }

        function addTicketRow(item, quantity, price, subtotal, index) {
            $("#ticket_summary").append(`
                <tr id="ticket_row_${index}" style="font-optical-sizing: auto; font-size: 90%">
                    <td class="text-center">${quantity}</td>
                    <td class="text-center">${item}</td>
                    <td class="text-center">${formatCurrency(price.toFixed(2))}</td>
                    <td class="text-center">${formatCurrency(subtotal.toFixed(2))}</td>
                </tr>
            `);
        }

      //* Restore Command Fields
        function clearBarcodeFields() {
            $("#barcode_reader").val('').focus().select();
        }

        function clearProductFields() {
            $("#search_bar").val(null).focus().select();
            $("#select_product").html('<option value="" disabled selected>-- -- --</option>');
            $("#selected_product_category, #selected_product_name, #selected_product_price").val(null);
            $("#selected_product_quantity").val(1);

            $("#discount_product_section").toggle(false);
        }

        function clearExtraFields() {
            $("#extra_product_name, #extra_product_price").val(null);
            $("#extra_product_quantity").val(1);
        }

      //* Update Totals
        function updateTotals() {
            const visual_total = total.toFixed(2);

            $("#visual_total").html(formatCurrency(visual_total));
            $("#total_orden").val(visual_total);
            $("#total_orden_illusory").val(visual_total);
            $("#pago_recibido, #payback").val(null);

            $("#ticket_total").text(formatCurrency(visual_total, false, true));
            $("#ticket_original_amount").text(formatCurrency(visual_total));
            $("#ticket_items_quantity").text($("#ticket_summary tr").length);

            setTimeout(calculateDiscount(), 500);
        }

      //* Observers
        function allowSubmit() {
            if (total > 0) {
                $("#save_order_section, #discount_section").show();
                $("#save_order").prop("disabled", true);
            } else {
                $("#save_order_section, #discount_section").hide();
            }
        }

      //* CRUD Actions
        function deleteCommand(index) {
            total -= subtotal[index] || 0;

            $(`#order_row_${index}`).remove();
            $(`#ticket_row_${index}`).remove();

            removeIndexFromMap(index)
            updateTotals();
            allowSubmit();
        }

        function removeIndexFromMap(index) {
            for (const key in rowKeyToIndex) {
                if (rowKeyToIndex[key] === index) {
                    delete rowKeyToIndex[key];
                    break;
                }
            }
        }

    </script>

    {{-- Ticket & Submit --}}
    <script>
        // On close Ticket, Re-open save request
        window.onafterprint = function(e){
            $(window).off('mousemove', window.onafterprint);

            if ($('#pago_recibido').val() != "" && $('#payback').val())
                $( "#restaurant_form" ).submit();
        };

        // Submit Form
        $(document).ready(function() {
            $('#restaurant_form').on('submit', function (event) {
                event.preventDefault();

                if ($('#barcode_reader').is(':focus')) {
                    return false;
                }

                Swal.fire({
                    title: "{{ __('entity_forms')['orders']['ticket_title'] }}",
                    icon: "question",
                    html: `
                        <h5>{{ __('entity_forms')['orders']['ticket_alert'] }}</h5>
                        <p><small>{{ __('entity_forms')['orders']['ticket_note'] }}</small></p>
                    `,
                    showDenyButton: true,
                    showCancelButton: false,
                    confirmButtonText: "{{ __('entity_forms')['orders']['show_ticket'] }}",
                    denyButtonText: `{{ __('entity_forms')['orders']['save_order'] }}`,
                    denyButtonColor: "#3085d6",
                }).then((result) => {
                    // Print ticket
                    if (result.isConfirmed) {
                        setTimeout(function(){
                            window.print();
                        }, 500);

                    // Save Order
                    } else if (result.isDenied) {
                        $.ajax({
                            url: `{{ route('commands.store') }}`,
                            method: "POST",
                            data: new FormData(this),
                            contentType: false,
                            cache: false,
                            processData: false,
                            dataType: "json",
                            success: function (data) {
                                Swal.fire({
                                    title: "{{ __('common_responses_and_messages')['success'] }}",
                                    text: "{{ __('entity_forms')['orders']['order_created'] }}",
                                    icon: 'success'
                                });

                                setTimeout(function(){
                                    location.reload();
                                }, 1500);
                            }
                        });
                    }
                });
            });
        });
    </script>

    {{-- Search bar Control--}}
    <script>
        function debounce(func, wait) {
            let timeout;
            return function(...args) {
                clearTimeout(timeout);
                timeout = setTimeout(() => func.apply(this, args), wait);
            };
        }

        function onSelectChange() {
            const product_to_search = $(this).val()?.trim();
                if (!product_to_search){
                    $('#select_product').html('<option value="" disabled selected>-- -- --</option>');
                    return;
                }

            $.get(`/api/products/search`, { value: product_to_search }, function(products) {
                let html_select = `<option value="" disabled selected>-- {{ __('common_actions')['select'] }} --</option>`;
                (products || []).forEach(product => {
                    html_select += `<option value="${product.id}">${product.product_name}</option>`;
                });

                $('#select_product').html(html_select);
            });
        }

        function onSelectProduct(){
            let id = $(this).val();
            $.get(`/api/products/${id}/command-data`, function(product){
                $('#selected_product_name').val(product.product_name);
                $('#selected_product_category').val(product.category_id);
                $('#selected_product_price, #selected_product_original_price').val(product.product_price);
                $('#selected_product_discount').val(null);

                const has_price = parseFloat(product.product_price) > 0;
                $("#discount_product_section").toggle(has_price);
            });
        }
    </script>

    {{-- Barcode Reader Control --}}
    <script>
      // Render Functions
        function displayBarcodeReader() {
            const checked = $(`#barcode_status`).prop('checked');

            $("#reader_method_section").toggle(checked);
            $("#search_method_section").toggle(!checked);

            if (checked) clearBarcodeFields();
            else clearProductFields();
        }

      // Reader Behavior
        $(function () {
          // Control Variables
            const $code_reader_field = $('#barcode_reader');
            const MAX_INTERVAL = 35;
            const MIN_LEN = 4;

            let buffer = '';
            let lastTime = 0;

            // Block Manual Data
            $code_reader_field.on('keydown', function (e) {
                if (e.key === 'Tab') return; // Allow Tab
                // if (e.key === 'Enter') return; // Allow Enter

                e.preventDefault();
                clearBarcodeFields();
            });

            // Catch scanned data
            $(document).on('keydown', function (e) {
                if (!$(document.activeElement).is($code_reader_field)) return; // Is the input selected

                const now = Date.now();
                if (lastTime && (now - lastTime) > MAX_INTERVAL) buffer = ''; // Reset if awaiting time reaching
                lastTime = now;

                // Common scan completion process
                if (e.key === 'Enter') {
                    e.preventDefault();

                  // Value respect min length required?
                    if (buffer.length < MIN_LEN) {
                        buffer = ''; lastTime = 0;

                        clearBarcodeFields();
                        return;
                    }

                  // Extract Final Data
                    const scannedCode = buffer; // Get Data
                    $code_reader_field.val(scannedCode); // Show read data
                    buffer = ''; lastTime = 0; // Clean input

                  // Get Product Data
                    searchProductByBarcode(scannedCode);
                    return;
                }

                // Build code with read characters
                if (e.key && e.key.length === 1) buffer += e.key;
            });

            // Avoid Paste code bars
            $code_reader_field.on('paste', function (e) {
                e.preventDefault();
            });

            // Avoid Browser Interactions
            $code_reader_field.attr({
                autocomplete: 'off', autocorrect: 'off', autocapitalize: 'off',
                spellcheck: 'false', inputmode: 'none'
            });
        });


    </script>
@endsection


