{% extends 'Master/MenuBgTemplate.html.twig' %}

{% block body %}
    <div class="container-fluid">
        <div class="row">
            <div class="col">
                <h1 class="h3">
                    <i class="fa-solid fa-cut me-2"></i> {{ fsc.title }}
                </h1>
                <p>{{ trans('copy-p') }}</p>
                <form method="post" onsubmit="animateSpinner('add')">
                    {{ formToken() }}
                    <input type="hidden" name="action" value="save"/>
                    <input type="hidden" name="code" value="{{ fsc.modelCode }}"/>
                    <input type="hidden" name="model" value="{{ fsc.modelClass }}"/>
                    <div class="card shadow mb-4">
                        <div class="card-body">
                            <div class="row g-2">
                                {% if fsc.model.codcliente %}
                                    <div class="col-sm-6 col-md">
                                        <div class="mb-3">
                                            <div class="input-group">
                                                <span class="input-group-text">
                                                    <i class="fa-solid fa-search"></i>
                                                </span>
                                                <input type="hidden" id="codclienteAutocomplete" name="codcliente"
                                                       value="{{ fsc.model.codcliente }}"/>
                                                <input type="text" id="codcliente"
                                                       value="{{ fsc.model.nombrecliente | raw }}"
                                                       class="form-control autocomplete-dc"
                                                       data-field="codcliente" data-source="Cliente"
                                                       data-fieldcode="codcliente" data-fieldtitle="nombre"
                                                       placeholder="{{ trans('customer') }}" autocomplete="off"/>
                                            </div>
                                        </div>
                                    </div>
                                {% elseif fsc.model.codproveedor %}
                                    <div class="col-sm-6 col-md">
                                        <div class="mb-3">
                                            <div class="input-group">
                                                <span class="input-group-text">
                                                    <i class="fa-solid fa-search"></i>
                                                </span>
                                                <input type="hidden" id="codproveedorAutocomplete" name="codproveedor"
                                                       value="{{ fsc.model.codproveedor }}"/>
                                                <input type="text" id="codproveedor"
                                                       value="{{ fsc.model.nombre | raw }}"
                                                       class="form-control autocomplete-dc"
                                                       data-field="codproveedor" data-source="Proveedor"
                                                       data-fieldcode="codproveedor" data-fieldtitle="nombre"
                                                       placeholder="{{ trans('supplier') }}" autocomplete="off"/>
                                            </div>
                                        </div>
                                    </div>
                                {% endif %}
                                <div class="col-sm-6 col-md">
                                    <div class="mb-3">
                                        <input type="date" name="fecha" value="{{ "now" | date('Y-m-d') }}"
                                               class="form-control" required/>
                                    </div>
                                </div>
                                <div class="col-sm-6 col-md">
                                    <div class="mb-3">
                                        <input type="time" name="hora" value="{{ "now" | date('H:i:s') }}"
                                               class="form-control" required/>
                                    </div>
                                </div>
                                {% if fsc.model.codcliente %}
                                    <div class="col-sm-6 col-md">
                                        <div class="mb-3">
                                            <div class="input-group">
                                                <span class="input-group-text">
                                                    <i class="fa-solid fa-hashtag"></i>
                                                </span>
                                                <input type="text" name="numero2" class="form-control"
                                                       placeholder="{{ trans('number2') }}"/>
                                            </div>
                                        </div>
                                    </div>
                                {% elseif fsc.model.codproveedor %}
                                    <div class="col-sm-6 col-md">
                                        <div class="mb-3">
                                            <div class="input-group">
                                                <span class="input-group-text">
                                                    <i class="fa-solid fa-hashtag"></i>
                                                </span>
                                                <input type="text" name="numproveedor" class="form-control"
                                                       placeholder="{{ trans('numsupplier') }}"/>
                                            </div>
                                        </div>
                                    </div>
                                {% endif %}
                            </div>
                            <div class="row g-2">
                                {% if fsc.empresa.count() > 1 %}
                                    <div class="col-sm-6 col-md">
                                        <div class="mb-3">
                                            {{ trans('company') }}
                                            <select name="idempresa" id="idempresa" class="form-select" required>
                                                {% for item in fsc.codeModel.all('empresas', 'idempresa', 'nombrecorto', false) %}
                                                    {% if item.code == fsc.model.idempresa %}
                                                        <option value="{{ item.code }}" selected>
                                                            {{ item.description }}
                                                        </option>
                                                    {% else %}
                                                        <option value="{{ item.code }}">
                                                            {{ item.description }}
                                                        </option>
                                                    {% endif %}
                                                {% endfor %}
                                            </select>
                                        </div>
                                    </div>
                                {% endif %}
                                <div class="col-sm-6 col-md">
                                    <div class="mb-3">
                                        {{ trans('warehouse') }}
                                        <select name="codalmacen" id="codalmacen" class="form-select" required>
                                            {% for item in fsc.warehousesList %}
                                                {% if item.code == fsc.model.codalmacen %}
                                                    <option value="{{ item.code }}" data-idempresa="{{ item.idempresa }}" selected>
                                                        {{ item.description }}
                                                    </option>
                                                {% else %}
                                                    <option value="{{ item.code }}" data-idempresa="{{ item.idempresa }}">
                                                        {{ item.description }}
                                                    </option>
                                                {% endif %}
                                            {% endfor %}
                                        </select>
                                    </div>
                                </div>
                                <div class="col-sm-6 col-md">
                                    <div class="mb-3">
                                        {{ trans('serie') }}
                                        <select name="codserie" id="codserie" class="form-select" required>
                                            {% for item in fsc.codeModel.all('series', 'codserie', 'descripcion', false) %}
                                                {% if item.code == fsc.model.codserie %}
                                                    <option value="{{ item.code }}" selected>
                                                        {{ item.description }}
                                                    </option>
                                                {% else %}
                                                    <option value="{{ item.code }}">
                                                        {{ item.description }}
                                                    </option>
                                                {% endif %}
                                            {% endfor %}
                                        </select>
                                    </div>
                                </div>
                                <div class="col-sm-6 col-md">
                                    <div class="mb-3">
                                        {{ trans('payment-method') }}
                                        <select name="codpago" id="codpago" class="form-select" required>
                                            {% for item in fsc.paymentMethodsList %}
                                                {% if item.code == fsc.model.codpago %}
                                                    <option value="{{ item.code }}" data-idempresa="{{ item.idempresa }}" selected>
                                                        {{ item.description }}
                                                    </option>
                                                {% else %}
                                                    <option value="{{ item.code }}" data-idempresa="{{ item.idempresa }}">
                                                        {{ item.description }}
                                                    </option>
                                                {% endif %}
                                            {% endfor %}
                                        </select>
                                    </div>
                                </div>
                                <div class="col-sm-6 col-md">
                                    <div class="mb-3">
                                        {{ trans('global-dto') }}
                                        <div class="input-group">
                                            <span class="input-group-text">
                                                    <i class="fa-solid fa-percentage"></i>
                                                </span>
                                            <input type="number" max="100" min="0" step="any" name="dtopor1"
                                                   class="form-control" value="{{ fsc.model.dtopor1 }}"/>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-sm-6 col-md">
                                    <div class="mb-3">
                                        {{ trans('global-dto-2') }}
                                        <div class="input-group">
                                            <span class="input-group-text">
                                                    <i class="fa-solid fa-percentage"></i>
                                                </span>
                                            <input type="number" max="100" min="0" step="any" name="dtopor2"
                                                   class="form-control" value="{{ fsc.model.dtopor2 }}"/>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                <tr>
                                    <th>{{ trans('reference') }}</th>
                                    <th>{{ trans('description') }}</th>
                                    <th class="text-end">{{ trans('quantity') }}</th>
                                    <th class="text-end">{{ trans('price') }}</th>
                                    <th class="text-end">{{ trans('dto') }}</th>
                                    <th class="text-end">{{ trans('dto-2') }}</th>
                                </tr>
                                </thead>
                                <tbody>
                                {% for line in fsc.model.getLines() %}
                                    <tr>
                                        <td>{{ line.referencia }}</td>
                                        <td>{{ line.descripcion | raw | nl2br }}</td>
                                        <td class="text-end">{{ line.cantidad }}</td>
                                        <td class="text-end">{{ number(line.pvpunitario) }}</td>
                                        <td class="text-end">{{ number(line.dtopor) }}%</td>
                                        <td class="text-end">{{ number(line.dtopor2) }}%</td>
                                    </tr>
                                {% endfor %}
                                </tbody>
                            </table>
                        </div>
                        <div class="card-body">
                            {{ trans('observations') }}
                            <textarea name="observaciones" class="form-control">{{ fsc.model.observaciones }}</textarea>
                        </div>
                        <div class="card-footer">
                            <div class="row">
                                <div class="col">
                                    <a href="{{ asset(fsc.model.url()) }}" class="btn btn-spin-action btn-secondary">
                                        <i class="fa-solid fa-arrow-left me-1"></i> {{ trans('back') }}
                                    </a>
                                </div>
                                <div class="col-auto">
                                    <button type="submit" class="btn btn-spin-action btn-primary">
                                        <i class="fa-solid fa-save me-1"></i> {{ trans('save') }}
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
{% 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>
        function businessDocViewAutocompleteGetData(formId, formData, term) {
            let rawForm = $("form[id=" + formId + "]").serializeArray();
            $.each(rawForm, function (i, input) {
                formData[input.name] = input.value;
            });
            formData["action"] = "autocomplete";
            formData["term"] = term;
            return formData;
        }

        function updateSelectsByCompany(idempresa) {
            if (!idempresa) {
                return;
            }

            // Convertir idempresa a número para comparación consistente
            var empresaNum = parseInt(idempresa);

            // Actualizar almacenes
            var selectedAlmacen = $("#codalmacen").val();
            var almacenValido = false;

            $("#codalmacen option").each(function() {
                var optionEmpresa = $(this).data("idempresa");

                // Si no tiene empresa asignada o coincide con la empresa seleccionada
                if (optionEmpresa === undefined || optionEmpresa === null || optionEmpresa === "" || parseInt(optionEmpresa) === empresaNum) {
                    $(this).prop("disabled", false).show();
                    if ($(this).val() === selectedAlmacen) {
                        almacenValido = true;
                    }
                } else {
                    $(this).prop("disabled", true).hide();
                }
            });

            // Si el almacén seleccionado no es válido, seleccionar el primero disponible
            if (!almacenValido) {
                var firstValidAlmacen = $("#codalmacen option:not(:disabled):first").val();
                if (firstValidAlmacen) {
                    $("#codalmacen").val(firstValidAlmacen);
                }
            }

            // Actualizar formas de pago
            var selectedPago = $("#codpago").val();
            var pagoValido = false;

            $("#codpago option").each(function() {
                var optionEmpresa = $(this).data("idempresa");

                // Si no tiene empresa asignada o coincide con la empresa seleccionada
                if (optionEmpresa === undefined || optionEmpresa === null || optionEmpresa === "" || parseInt(optionEmpresa) === empresaNum) {
                    $(this).prop("disabled", false).show();
                    if ($(this).val() === selectedPago) {
                        pagoValido = true;
                    }
                } else {
                    $(this).prop("disabled", true).hide();
                }
            });

            // Si la forma de pago seleccionada no es válida, seleccionar la primera disponible
            if (!pagoValido) {
                var firstValidPago = $("#codpago option:not(:disabled):first").val();
                if (firstValidPago) {
                    $("#codpago").val(firstValidPago);
                }
            }
        }

        $(document).ready(function () {
            // Evento para cuando cambia la empresa
            $("#idempresa").on("change", function() {
                updateSelectsByCompany($(this).val());
            });

            // Inicializar los selectores con la empresa actual al cargar la página
            var currentEmpresa = $("#idempresa").val();
            if (currentEmpresa) {
                updateSelectsByCompany(currentEmpresa);
            } else {
                // Si no hay selector de empresa (solo hay una), usar la empresa del modelo
                {% if fsc.model.idempresa %}
                updateSelectsByCompany({{ fsc.model.idempresa }});
                {% endif %}
            }

            $(".autocomplete-dc").each(function () {
                let data = {
                    field: $(this).attr("data-field"),
                    fieldcode: $(this).attr("data-fieldcode"),
                    fieldtitle: $(this).attr("data-fieldtitle"),
                    source: $(this).attr("data-source")
                };
                let formName = $(this).closest("form").attr("name");
                $(this).autocomplete({
                    source: function (request, response) {
                        $.ajax({
                            method: "POST",
                            url: "{{ fsc.url() }}",
                            data: businessDocViewAutocompleteGetData(formName, data, request.term),
                            dataType: "json",
                            success: function (results) {
                                let values = [];
                                results.forEach(function (element) {
                                    if (element.key === null || element.key === element.value) {
                                        values.push(element);
                                    } else {
                                        values.push({key: element.key, value: element.key + " | " + element.value});
                                    }
                                });
                                response(values);
                            },
                            error: function (msg) {
                                alert(msg.status + " " + msg.responseText);
                            }
                        });
                    },
                    select: function (event, ui) {
                        if (ui.item.key !== null) {
                            $("#" + data.field + "Autocomplete").val(ui.item.key);
                            let value = ui.item.value.split(" | ");
                            if (value.length > 1) {
                                ui.item.value = value[1];
                            } else {
                                ui.item.value = value[0];
                            }
                        }
                    },
                    open: function (event, ui) {
                        $(this).autocomplete('widget').css('z-index', 1500);
                        return false;
                    }
                });
            });
        });
    </script>
{% endblock %}