{% extends "Master/MenuBghTemplate.html.twig" %}

{% block bodyHeaderOptions %}
    <br/>
    <br/>
    <br/>
    <br/>
    <br/>
{% endblock %}

{% block body %}
    <div class="container" style="margin-top: -42px">
        <div class="row">
            <div class="col">
                <div class="card shadow mb-5">
                    <div class="card-body"></div>
                    <div class="card-footer p-2">
                        <button class="btn btn-lg btn-block btn-success btn-spin-action" onclick="initNewService()">
                            {{ trans('new-service') }}
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    {{ parent() }}

    <!-- Modal warehouse -->
    {% block modalWarehouse %}
        <div class="modal fade" id="warehouseModal" tabindex="-1" aria-labelledby="warehouseModalLabel"
             aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="warehouseModalLabel">
                            <i class="fa-solid fa-warehouse mr-1"></i> {{ trans('warehouse') }}
                        </h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="{{ trans('close') }}">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <select class="form-control mb-3" id="warehouseSelect">
                            {% for company in fsc.getCompanies() %}
                                <optgroup label="{{ company.nombrecorto }}">
                                    {% for warehouse in company.getWarehouses() %}
                                        {% if warehouse.activo == false %}
                                        {% elseif warehouse.codalmacen == fsc.codalmacen %}
                                            <option value="{{ warehouse.codalmacen }}" selected>
                                                {{ warehouse.nombre }}
                                            </option>
                                        {% else %}
                                            <option value="{{ warehouse.codalmacen }}">{{ warehouse.nombre }}</option>
                                        {% endif %}
                                    {% endfor %}
                                </optgroup>
                            {% endfor %}
                        </select>
                        <button type="button" class="btn btn-block btn-primary btn-spin-action"
                                onclick="saveWarehouse()">
                            {{ trans('continue') }}
                        </button>
                    </div>
                </div>
            </div>
        </div>
    {% endblock %}

    <!-- Modal customer -->
    {% block modalCustomer %}
        <div class="modal fade" id="customerModal" tabindex="-1" aria-labelledby="customerModalLabel"
             aria-hidden="true">
            <div class="modal-dialog modal-dialog-scrollable">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="customerModalLabel">
                            <i class="fa-solid fa-users mr-1"></i> {{ trans('customers') }}
                        </h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="{{ trans('close') }}">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body p-0">
                        <div class="input-group p-3">
                            <input type="text" id="findCustomerInput" class="form-control ui-autocomplete-input"
                                   placeholder="{{ trans('search') }}" autocomplete="off"/>
                            <div class="input-group-append">
                                <button class="btn btn-primary" type="button">
                                    <i class="fa-solid fa-search"></i>
                                </button>
                            </div>
                        </div>
                        <table class="table table-hover mb-0">
                            {% for customer in fsc.getModalCustomers() %}
                                {% set customerName = customer.nombre == customer.razonsocial ? customer.nombre : customer.nombre ~ ' <span>(' ~ customer.razonsocial ~ ')</span>' %}
                                <tr class="clickableRow" data-codcliente="{{ customer.codcliente }}">
                                    <td>
                                        <i class="fa-solid fa-user fa-fw"></i> {{ customerName | raw }}
                                    </td>
                                </tr>
                            {% endfor %}
                        </table>
                    </div>
                    <div class="modal-footer p-2">
                        <button type="button" class="btn btn-block btn-success btn-spin-action"
                                onclick="showModalNewCustomer()">
                            <i class="fa-solid fa-user-plus mr-1"></i> {{ trans('new-customer') | capitalize }}
                        </button>
                        <button type="button" class="btn btn-block btn-outline-secondary btn-spin-action"
                                onclick="showModalWarehouse()">
                            <i class="fa-solid fa-arrow-left mr-1"></i> {{ trans('change-warehouse') }}
                        </button>
                    </div>
                </div>
            </div>
        </div>
    {% endblock %}

    <!-- Modal new customer -->
    {% block modalNewCustomer %}
        <div class="modal fade" id="newCustomerModal" tabindex="-1" aria-labelledby="newCustomerModalLabel"
             aria-hidden="true">
            <div class="modal-dialog modal-dialog-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="newCustomerModalLabel">
                            <i class="fa-solid fa-user-plus mr-1"></i> {{ trans('new-customer') | capitalize }}
                        </h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="{{ trans('close') }}">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="form-row">
                            <div class="col">
                                <div class="form-group">
                                    {{ trans('name') }}
                                    <input type="text" name="name" class="form-control" maxlength="100"
                                           onkeyup="return checkCustomer(this)"/>
                                </div>
                            </div>
                            <div class="col">
                                <div class="form-group">
                                    {{ trans('cifnif') }}
                                    <input type="text" name="cifnif" class="form-control" maxlength="30"
                                           onkeyup="return checkCustomer(this)"/>
                                </div>
                            </div>
                            <div id="checkDuplicateCustomerMsg"
                                 class="col-12 form-group alert alert-danger text-center d-none">
                                {{ trans('duplicate-customer-name-or-cif') }}
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="col">
                                <div class="form-group">
                                    {{ trans('phone') }}
                                    <input type="text" name="phone1" class="form-control" maxlength="30"/>
                                </div>
                            </div>
                            <div class="col">
                                <div class="form-group">
                                    {{ trans('phone2') }}
                                    <input type="text" name="phone2" class="form-control" maxlength="30"/>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            {{ trans('email') }}
                            <input type="email" name="email" class="form-control" maxlength="100"/>
                        </div>
                        <div class="form-group">
                            {{ trans('address') }}
                            <input type="text" name="address" class="form-control" maxlength="100"/>
                        </div>
                        <div class="form-row">
                            <div class="col">
                                <div class="form-group">
                                    {{ trans('zip-code') }}
                                    <input type="text" name="zip" class="form-control" maxlength="10"/>
                                </div>
                            </div>
                            <div class="col">
                                <div class="form-group">
                                    {{ trans('city') }}
                                    <input list="cities" name="city" class="form-control" maxlength="100"/>
                                    <datalist id="cities">
                                        {% for city in fsc.codeModel.all('ciudades','ciudad','ciudad',false) %}
                                        <option value="{{ city.code }}">
                                            {% endfor %}
                                    </datalist>
                                </div>
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="col">
                                <div class="form-group">
                                    {{ trans('province') }}
                                    <input list="provinces" name="province" class="form-control" maxlength="100"/>
                                    <datalist id="provinces">
                                        {% for province in fsc.codeModel.all('provincias','provincia','provincia',false) %}
                                        <option value="{{ province.code }}">
                                            {% endfor %}
                                    </datalist>
                                </div>
                            </div>
                            <div class="col">
                                <div class="form-group">
                                    {{ trans('country') }}
                                    <select name="country" class="form-control" required>
                                        {% for country in fsc.codeModel.all('paises','codpais','nombre',false) %}
                                            {% if country.code == settings('default','codpais') %}
                                                <option value="{{ country.code }}" selected>
                                                    {{ country.description }}
                                                </option>
                                            {% else %}
                                                <option value="{{ country.code }}">{{ country.description }}</option>
                                            {% endif %}
                                        {% endfor %}
                                    </select>
                                </div>
                            </div>
                        </div>
                        {% for item in getIncludeViews('NewServicioAT', 'newCustomerModal') %}
                            {% include item['path'] %}
                        {% endfor %}
                    </div>
                    <div class="modal-footer p-2">
                        <button type="button" class="btn btn-lg btn-block btn-success btn-spin-action"
                                onclick="saveNewCustomer()">
                            <i class="fa-solid fa-floppy-disk mr-1"></i> {{ trans('save') }}
                        </button>
                        <button type="button" class="btn btn-block btn-outline-secondary btn-spin-action"
                                onclick="showModalCustomer()">
                            <i class="fa-solid fa-arrow-left mr-1"></i> {{ trans('change-customer') }}
                        </button>
                    </div>
                </div>
            </div>
        </div>
    {% endblock %}

    <!-- Modal machines customer -->
    {% block modalMachine %}
        <div class="modal fade" id="machineModal" tabindex="-1" aria-labelledby="machineModalLabel"
             aria-hidden="true">
            <div class="modal-dialog modal-dialog-scrollable">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="machineModalLabel">
                            <i class="fa-solid fa-laptop-medical mr-1"></i> {{ trans('machines') }}
                        </h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="{{ trans('close') }}">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body p-0">
                        <table class="table table-hover mb-0">
                            <thead>
                            <tr>
                                <th>{{ trans('name') }}</th>
                                <th>{{ trans('serial-number') }}</th>
                                <th>{{ trans('description') }}</th>
                            </tr>
                            </thead>
                            <tbody id="customerMachines"></tbody>
                        </table>
                    </div>
                    <div class="modal-footer p-2">
                        <button type="button" class="btn btn-block btn-primary btn-spin-action"
                                onclick="saveMachine(null)">
                            <i class="fa-solid fa-ban mr-1"></i> {{ trans('no-machine') }}
                        </button>
                        <button type="button" class="btn btn-block btn-success btn-spin-action"
                                onclick="showModalNewMachine()">
                            <i class="fa-solid fa-laptop-medical mr-1"></i> {{ trans('new-machine') }}
                        </button>
                        <button type="button" class="btn btn-block btn-outline-secondary mt-4 btn-spin-action"
                                onclick="showModalCustomer()">
                            <i class="fa-solid fa-arrow-left mr-1"></i> {{ trans('change-customer') }}
                        </button>
                    </div>
                </div>
            </div>
        </div>
    {% endblock %}

    <!-- Modal new machine customer -->
    {% block modalNewMachine %}
        <div class="modal fade" id="newMachineModal" tabindex="-1" aria-labelledby="newMachineModalLabel"
             aria-hidden="true">
            <div class="modal-dialog modal-dialog-scrollable">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="newMachineModalLabel">
                            <i class="fa-solid fa-laptop-medical mr-1"></i> {{ trans('new-machine') }}
                        </h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="{{ trans('close') }}">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            {{ trans('name') }}
                            <input type="text" name="name" class="form-control" maxlength="100" required/>
                        </div>
                        <div class="form-group">
                            {{ trans('serial-number') }}
                            <input type="text" name="serial_number" class="form-control" maxlength="100"/>
                        </div>
                        <div class="form-group">
                            {{ trans('manufacturer') }}
                            <select name="manufacturer" class="form-control" required>
                                {% for manufacture in fsc.codeModel.all('fabricantes','codfabricante','nombre') %}
                                    <option value="{{ manufacture.code }}">{{ manufacture.description }}</option>
                                {% endfor %}
                            </select>
                        </div>
                        <div class="form-group">
                            {{ trans('description') }}
                            <textarea name="description" class="form-control" maxlength="100"></textarea>
                        </div>
                        {% for item in getIncludeViews('NewServicioAT', 'newMachineModal') %}
                            {% include item['path'] %}
                        {% endfor %}
                    </div>
                    <div class="modal-footer p-2">
                        <button type="button" class="btn btn-lg btn-block btn-success btn-spin-action"
                                onclick="saveNewMachine()">
                            <i class="fa-solid fa-floppy-disk mr-1"></i> {{ trans('save') }}
                        </button>
                        <button type="button" class="btn btn-block btn-outline-secondary btn-spin-action"
                                onclick="showModalMachine()">
                            <i class="fa-solid fa-arrow-left mr-1"></i> {{ trans('change-machine') }}
                        </button>
                    </div>
                </div>
            </div>
        </div>
    {% endblock %}
{% endblock %}

{% block css %}
    {{ parent() }}
    <link rel="stylesheet" href="{{ asset('node_modules/jquery-ui-dist/jquery-ui.min.css') }}"/>
{% endblock %}

{% block javascripts %}
    {{ parent() }}
    <script src="{{ asset('node_modules/jquery-ui-dist/jquery-ui.min.js') }}"></script>
    <script>
        let waitCounterNewCustomer = 0;
        let codalmacen = '{{ fsc.codalmacen }}';
        let codcliente = '{{ fsc.codcliente }}';
        let idmaquina = {{ fsc.idmaquina ?? 0 }};

        async function checkCustomer(event) {
            // usamos un contador y un temporizador para solamente procesar la última llamada
            waitCounterNewCustomer++;
            let waitNum = waitCounterNewCustomer;
            await new Promise(r => setTimeout(r, 300));
            if (waitNum < waitCounterNewCustomer) {
                return false;
            }

            let formData = new FormData();
            formData.append('name', $('#newCustomerModal input[name="name"]').val());
            formData.append('cifnif', $('#newCustomerModal input[name="cifnif"]').val());
            return sendFormService(formData, 'checkDuplicateCustomer');
        }

        function initNewService() {
            // si solo tengo un almacén, y tengo un cliente y una máquina, se guarda el servicio
            if ($('#warehouseSelect option').length === 1 && codcliente !== '' && idmaquina > 0) {
                saveNewService();
                return;
            }

            // si solo tengo un almacén, y tengo un cliente, pero no una máquina
            // se muestra el modal de máquinas o no, según la configuración
            if ($('#warehouseSelect option').length === 1 && codcliente !== '' && idmaquina <= 0) {
                saveCustomer(codcliente);
                return;
            }

            // si hay más de un almacén, se muestra el modal para seleccionar el almacén
            if ($('#warehouseSelect option').length > 1) {
                showModalWarehouse();
            } else {
                // si no se muestra el modal de clientes
                showModalCustomer();
            }
        }

        function saveCustomer(code) {
            codcliente = code;

            {% if settings('servicios', 'new_service_without_machine', false) %}
            saveNewService();
            {% else %}
            let formData = new FormData();
            formData.append('codcliente', codcliente);
            sendFormService(formData, 'renderCustomerMachines');
            {% endif %}
        }

        function saveMachine(code) {
            idmaquina = code;
            saveNewService();
        }

        function saveNewCustomer() {
            animateSpinner('add');

            let formData = new FormData();

            $('#newCustomerModal input').each(function () {
                formData.append($(this).attr('name'), $(this).val());
            });

            $('#newMachineModal textarea').each(function () {
                formData.append($(this).attr('name'), $(this).val());
            });

            $('#newCustomerModal select').each(function () {
                formData.append($(this).attr('name'), $(this).find('option:selected').val());
            });

            sendFormService(formData, 'saveNewCustomer');
        }

        function saveNewMachine() {
            animateSpinner('add');

            let formData = new FormData();
            formData.append('codcliente', codcliente);

            $('#newMachineModal input').each(function () {
                formData.append($(this).attr('name'), $(this).val());
            });

            $('#newMachineModal select').each(function () {
                formData.append($(this).attr('name'), $(this).find('option:selected').val());
            });

            $('#newMachineModal textarea').each(function () {
                formData.append($(this).attr('name'), $(this).val());
            });

            sendFormService(formData, 'saveNewMachine');
        }

        function saveNewService() {
            animateSpinner('add');

            let formData = new FormData();
            formData.append('codcliente', codcliente);

            if (codalmacen) {
                formData.append('codalmacen', codalmacen);
            }

            if (idmaquina > 0) {
                formData.append('idmaquina', idmaquina);
            }

            sendFormService(formData, 'saveNewService');
        }

        function saveWarehouse() {
            codalmacen = $('#warehouseSelect').val();

            // si tenemos idmaquina en la url, se guarda el servicio
            {% if fsc.idmaquina > 0 %}
            saveMachine('{{ fsc.idmaquina }}');
            {% elseif fsc.codcliente != '' and settings('servicios', 'new_service_without_machine', false) %}
            // si ya tenemos codcliente en la url,
            // y la configuración permite guardar servicios sin máquina, se guarda el servicio
            saveNewService();
            {% elseif fsc.codcliente != '' %}
            // si ya tenemos codcliente en la url, se guarda el cliente
            saveCustomer('{{ fsc.codcliente }}');
            {% else %}
            // si no se muestra el modal de clientes
            showModalCustomer();
            {% endif %}
        }

        function sendFormService(formData, action) {
            formData.append('action', action);
            formData.append('ajax', true);

            fetch('{{ fsc.url() }}' + window.location.search, {
                method: 'POST',
                body: formData
            }).then(function (response) {
                if (response.ok) {
                    animateSpinner('remove', true);
                    return response.json();
                }
                animateSpinner('remove', false);
                return Promise.reject(response);
            }).then(function (data) {
                if (data.redirect) {
                    window.location.href = data.redirect;
                    return;
                }

                if (data.checkDuplicateCustomer) {
                    $('#checkDuplicateCustomerMsg').removeClass('d-none');
                } else {
                    $('#checkDuplicateCustomerMsg').addClass('d-none');
                }

                if (data.renderCustomerMachines) {
                    $('#customerMachines').html(data.html);
                    showModalMachine();
                }

                if (data.saveNewCustomer) {
                    saveCustomer(data.codcliente);
                }

                if (data.saveNewMachine) {
                    saveMachine(data.idmaquina);
                }

                if (data.saveNewService) {
                    window.location.href = data.url;
                    return;
                }

                // si hay mensajes de error
                if (data.messages) {
                    data.messages.forEach(function (msg) {
                        if (msg.level === 'danger') {
                            setToast(msg.message, msg.level, '', 0);
                        } else {
                            setToast(msg.message, msg.level);
                        }
                    });
                }

                animateSpinner('remove');
            }).catch(function (error) {
                alert('error sendFormService');
                console.warn(error);
                animateSpinner('remove', false);
                return false;
            });

            return true;
        }

        function showModalCustomer() {
            $('#warehouseModal').modal('hide');
            $('#newCustomerModal').modal('hide');
            $('#machineModal').modal('hide');
            $('#newMachineModal').modal('hide');

            $('#findCustomerInput').val('');
            $('#customerModal').modal('show').on('shown.bs.modal', function (event) {
                $('#findCustomerInput').focus();
            });
        }

        function showModalMachine() {
            $('#warehouseModal').modal('hide');
            $('#customerModal').modal('hide');
            $('#newCustomerModal').modal('hide');
            $('#newMachineModal').modal('hide');

            $('#machineModal').modal('show');
        }

        function showModalNewCustomer() {
            $('#warehouseModal').modal('hide');
            $('#customerModal').modal('hide');
            $('#machineModal').modal('hide');
            $('#newMachineModal').modal('hide');

            $('#newCustomerModal').modal('show').on('shown.bs.modal', function (event) {
                $('#newCustomerModal input').first().focus();
            });
        }

        function showModalNewMachine() {
            $('#warehouseModal').modal('hide');
            $('#customerModal').modal('hide');
            $('#newCustomerModal').modal('hide');
            $('#machineModal').modal('hide');

            $('#newMachineModal').modal('show').on('shown.bs.modal', function (event) {
                $('#newMachineModal input').first().focus();
            });
        }

        function showModalWarehouse() {
            $('#customerModal').modal('hide');
            $('#newCustomerModal').modal('hide');
            $('#machineModal').modal('hide');
            $('#newMachineModal').modal('hide');

            $('#warehouseModal').modal('show').on('shown.bs.modal', function (event) {
                $('#warehouseSelect').focus();
            });
        }

        $(document).ready(function () {
            $("#findCustomerInput").autocomplete({
                autoFocus: true,
                source: function (request, response) {
                    $.ajax({
                        method: "POST",
                        url: '{{ fsc.url() }}',
                        data: {
                            action: 'findCustomer',
                            term: request.term,
                            ajax: true,
                        },
                        dataType: "json",
                        success: function (results) {
                            response(results.customers);
                        },
                        error: function (msg) {
                            alert(msg.status + " " + msg.responseText);
                        }
                    });
                },
                select: function (event, ui) {
                    if (ui.item.key !== null) {
                        const value = ui.item.value.split(" | ");
                        if (value.length > 1) {
                            saveCustomer(value[0]);
                        }
                    }
                },
                open: function (event, ui) {
                    $(this).autocomplete('widget').css('z-index', 1500);
                    return false;
                }
            });

            $(document).on('click', '#customerModal .clickableRow', function () {
                saveCustomer($(this).data('codcliente'));
            });

            $(document).on('click', '#machineModal .clickableRow', function () {
                saveMachine($(this).data('idmaquina'));
            });

            initNewService();
        });
    </script>
{% endblock %}