<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#priceModal">
    Obtener Precio
</button>

<!-- Price Modal -->
<div class="modal fade" id="priceModal" tabindex="-1" aria-labelledby="priceModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="priceModalLabel">Calcular Precio</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="priceForm">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="categoria_producto_precio">Categoría de producto</label>
                                <select class="form-control" name="categoria_producto_precio"
                                    id="categoria_producto_precio" onchange="updateFactoresCategoria()">
                                    <option>Selecciona categoría</option>
                                    <?php $__currentLoopData = $categorias; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $categoria): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($categoria->id); ?>"><?php echo e($categoria->nombre); ?></option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>

                            <div class="form-group">
                                <label for="alto" id="lbl-alto">Ancho de Bobina - H (cm)</label>
                                <input type="number" class="form-control" id="alto" name="alto" value="0">
                            </div>
                            <div class="form-group">
                                <label for="ancho1" id="lbl-ancho1">Boca Ancha - A (cm)</label>
                                <input type="number" class="form-control" id="ancho1" name="ancho1" value="0">
                            </div>
                            <div class="form-group">
                                <label for="ancho2" id="lbl-ancho2">Boca Angosta - B (cm)</label>
                                <input type="number" class="form-control" id="ancho2" name="ancho2" value="0">
                            </div>
                            <div class="form-group">
                                <div>
                                    <label for="precio_unitario">Precio Unitario</label>
                                    <p style="font-size: 32px;font-weight:600;color:rgb(0, 89, 255);">Q.<span
                                            id="lbl-precio"></span></p>
                                </div>
                                <div>
                                    <label for="factor_kg">Factor Kg/Millar</label>
                                    <p style="font-size: 32px;font-weight:600;color:rgb(255, 144, 52);"><span
                                            id="lbl-factorkgm"></span></p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="gramos_metro_id">Gramos por Metro</label>
                                <div class="d-flex">
                                    <select class="form-control" id="gramos_metro_id" name="gramos_metro_id" disabled>

                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="tasa_cambio">Tasa de Cambio</label>
                                <input type="number" step="0.01" class="form-control" id="tasa_cambio"
                                    value="7.8" name="tasa_cambio" required>
                            </div>
                            <div class="form-group">
                                <label for="factor_categoria">Factor de conversión</label>
                                <input type="number" step="0.01" class="form-control" id="factor_categoria"
                                    value="1" name="factor_categoria" required>
                            </div>
                            <div class="form-group">
                                <label for="materia_prima_id">Materia Prima</label>
                                <div class="d-flex">
                                    <select class="form-control" id="materia_prima_id" name="materia_prima_id">
                                        <option>Consulta de prorrateo</option>
                                        <?php $__currentLoopData = $productosProrrateo; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <option value="<?php echo e($item->compra->id); ?>"><?php echo e($item->producto->nombre); ?></option>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </select>
                                    <button type="button" class="btn btn-secondary" onclick="viewDolarKilogramo()">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"
                                            fill="currentColor" class="bi bi-eye" viewBox="0 0 16 16">
                                            <path
                                                d="M16 8s-3-5.5-8-5.5S0 8 0 8s3 5.5 8 5.5S16 8 16 8M1.173 8a13 13 0 0 1 1.66-2.043C4.12 4.668 5.88 3.5 8 3.5s3.879 1.168 5.168 2.457A13 13 0 0 1 14.828 8q-.086.13-.195.288c-.335.48-.83 1.12-1.465 1.755C11.879 11.332 10.119 12.5 8 12.5s-3.879-1.168-5.168-2.457A13 13 0 0 1 1.172 8z" />
                                            <path
                                                d="M8 5.5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5M4.5 8a3.5 3.5 0 1 1 7 0 3.5 3.5 0 0 1-7 0" />
                                        </svg>
                                    </button>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="factor_costo_venta">Factor Costo a Precio de Venta</label>
                                <input type="number" step="0.01" class="form-control" readonly
                                    id="factor_costo_venta" value="1">
                            </div>
                            <div class="form-group">
                                <label for="porcentaje_desperdicio">Porcentaje Desperdicio</label>
                                <input type="number" step="1" class="form-control" readonly
                                    id="porcentaje_desperdicio" value="0">
                            </div>
                            <input type="number" step="0.01" class="d-none" hidden id="capas"
                                value="1">
                        </div>
                    </div>
                    <div class="row my-4" style="display: none;" id="detalle-gramaje">
                        <div class="col-md-12">
                            <label>Detalle de Gramaje</label>
                            <table class="table table-striped">
                                <thead class="thead-dark">
                                    <tr>
                                        <th scope="col">Area Total</th>
                                        <th scope="col">Gr/metro cuadrado</th>
                                        <th scope="col">Kgs/000</th>
                                        <th scope="col">Kgs + <span id="label-desperdicio">0</span>%</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td id="tbl-area">0.000000</td>
                                        <td id="tbl-gr-metro">0.000000</td>
                                        <td id="tbl-kgs-millar">0.000000</td>
                                        <td id="tbl-kgs-10">0.000000</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <button class="btn btn-primary" id="calcular-precio">Calcular Precio</button>
                    <button class="btn btn-success" id="aplicar-precio">Aplicar Precio</button>
                    <a class="btn btn-info" id="btn-detalle-gramos" onclick="$('#detalle-gramaje').slideToggle()">Ver
                        Detalle de
                        Calculo</a>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- New Gram Modal -->
<div class="modal fade" id="newGramModal" tabindex="-1" aria-labelledby="newGramModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="newGramModalLabel">Nuevo Gramos por Metro</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="newGramForm">
                    <div class="form-group">
                        <label for="new_calibre">Calibre</label>
                        <input type="number" class="form-control" id="new_calibre" name="new_calibre" required>
                    </div>
                    <div class="form-group">
                        <label for="new_factor">Factor</label>
                        <input type="number" step="0.01" class="form-control" id="new_factor" name="new_factor"
                            required>
                    </div>
                    <button type="submit" class="btn btn-primary">Guardar</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    function viewDolarKilogramo() {
        let select = document.getElementById("materia_prima_id");
        let url = `<?php echo e(route('compras.detalle', ':id')); ?>#desgloce-prorrateo`;
        let materiaPrimaId = select.value;
        url = url.replace(':id', materiaPrimaId);
        window
            .open(url, '_blank')
            .focus();
    }

    async function updateFactoresCategoria() {
        try {
            let data = await getCategoriaData();
            let selectGramos = document.getElementById("gramos_metro_id");
            selectGramos.innerHTML = "";
            data.detalles.forEach(gramo => {
                let option = document.createElement("option");
                option.value = gramo.valor;
                option.text = gramo.nombre;
                selectGramos.appendChild(option);
            });
            selectGramos.removeAttribute("disabled");
            let factorCategoria = document.getElementById("factor_categoria");
            let factorCostoVenta = document.getElementById("factor_costo_venta");
            let capasMaterial = document.getElementById("capas");
            let desperdicio_material = document.getElementById("porcentaje_desperdicio");
            let labelDesperdicio = document.getElementById("label-desperdicio");
            factorCategoria.value = data.factor;
            factorCostoVenta.value = data.factor_costo_venta;
            capasMaterial.value = data.capas;
            desperdicio_material.value = data.porcentaje_desperdicio;
            labelDesperdicio.innerText = data.porcentaje_desperdicio;
            setNombresLabel(data.tipo);
            console.log(data);
        } catch (error) {
            console.error(error);
        }
    }

    function setNombresLabel(tipo) {
        let alto = document.getElementById("lbl-alto");
        let ancho1 = document.getElementById("lbl-ancho1");
        let ancho2 = document.getElementById("lbl-ancho2");
        let btnAncho2 = document.getElementById("ancho2");

        if (tipo == 0) {
            alto.innerText = "Ancho de Bobina - H (cm)";
            ancho1.innerText = "Boca Ancha - A (cm)";
            ancho2.innerText = "Boca Angosta - B (cm)";
            // Habilitar campo de boca angosta
            btnAncho2.removeAttribute("disabled");
        }
        if (tipo == 1) {
            alto.innerText = "Ancho de Boca (cm)";
            ancho1.innerText = "Largo (cm)";
            ancho2.innerText = "No aplica";
            // Deshabilitar campo de boca angosta
            btnAncho2.setAttribute("disabled", true);
        }
        if (tipo == 2) {
            alto.innerText = "Ancho (cm)";
            ancho1.innerText = "Largo (cm)";
            ancho2.innerText = "No aplica";
            btnAncho2.setAttribute("disabled", true);
        }
    }

    async function getCategoriaData() {
        let categoriaId = document.getElementById("categoria_producto_precio").value;
        let url = `<?php echo e(route('categoria.detalle', ':id')); ?>`;
        url = url.replace(':id', categoriaId);

        try {
            let response = await fetch(url);
            if (!response.ok) {
                throw new Error(`Error: ${response.statusText}`);
            }
            let data = await response.json();
            return data;
        } catch (error) {
            console.error(error);
            throw error; // Re-throw the error so it can be caught in updateFactoresCategoria
        }
    }

    function setPrecio(precio) {
        let lblPrecio = document.getElementById("lbl-precio");
        let lblFactor = document.getElementById("lbl-factorkgm");
        let ancho1 = parseFloat(document.getElementById("ancho1").value);
        let ancho2 = parseFloat(document.getElementById("ancho2").value);
        let alto = parseFloat(document.getElementById("alto").value);
        let gramos = parseFloat(document.getElementById("gramos_metro_id").value);
        let tasaCambio = parseFloat(document.getElementById("tasa_cambio").value);
        let dolarKilogramo = parseFloat(document.getElementById("factor_categoria").value);
        let factorCostoVenta = parseFloat(document.getElementById("factor_costo_venta").value);
        let capas = parseFloat(document.getElementById("capas").value);
        let desperdicio = parseFloat(document.getElementById("porcentaje_desperdicio").value);
        let area1 = ancho1 + ancho2;
        let area = area1 * alto;
        console.log('ancho1:', ancho1);
        console.log('ancho2:', ancho2);
        console.log('alto:', alto);
        console.log('area:', area);
        console.log('capas:', capas);
        let kgs = area * 1000 * gramos / 10000 / 1000;
        desperdicio = desperdicio / 100;
        let factor_conversion = kgs * (1 + desperdicio);
        console.log('kgs/millar:', kgs);
        console.log("factor conversion:", factor_conversion);
        console.log("factor costo venta:", factorCostoVenta);
        if (capas == 2) {
            factor_conversion = factor_conversion * 2;
        }
        console.log("factor conversion:", factor_conversion);
        let precio_usd = factor_conversion * dolarKilogramo * factorCostoVenta;
        console.log('precioUSD:', precio_usd);
        let precio_gtq = precio_usd * tasaCambio;
        let precio_iva = precio_gtq * 1.12;
        let precio_final = Math.round(precio_iva);
        lblPrecio.innerText = precio_final.toFixed(2);
        lblFactor.innerText = factor_conversion.toFixed(2);
        setDetalleGramos(area, gramos, kgs, factor_conversion);
    }

    function setDetalleGramos(area, gr_metro, kgs_millar, kgs_10) {
        let area_tabla = document.getElementById('tbl-area');
        let gr_metro_tabla = document.getElementById('tbl-gr-metro');
        let kgs_millar_tabla = document.getElementById('tbl-kgs-millar');
        let kgs_10_tabla = document.getElementById('tbl-kgs-10');

        area_tabla.innerText = area.toFixed(2);
        gr_metro_tabla.innerText = gr_metro.toFixed(2);
        kgs_millar_tabla.innerText = kgs_millar.toFixed(2);
        kgs_10_tabla.innerText = kgs_10.toFixed(2);
    }

    document.getElementById("calcular-precio").addEventListener("click", function(event) {
        event.preventDefault();
        setPrecio();
    });

    document.getElementById("aplicar-precio").addEventListener("click", function(event) {
        event.preventDefault();
        let precio_calc = document.getElementById("lbl-precio").innerText;
        let factor_calc = document.getElementById("lbl-factorkgm").innerText;
        document.getElementById("input_precio_unitario").value = precio_calc;
        document.getElementById("input_precio_venta").value = precio_calc;
        document.getElementById("input_factor_kg").value = factor_calc;

        // Ocultar modal
        $('#priceModal').modal('hide');
    });
</script>
<?php /**PATH /home/devpwg5/laravelrp.com/resources/views/components/calculo-precio.blade.php ENDPATH**/ ?>