<?php
/* --------------------------------------------------------------------------------
   MÓDULO: NUEVA COMPRA PRO (CON GESTIÓN DE SERIES EN MODAL)
   --------------------------------------------------------------------------------
*/

// 1. SEGURIDAD
error_reporting(E_ALL);
ini_set('display_errors', 0); 
session_start();
if (!isset($_SESSION['Acceso']) || $_SESSION['Acceso'] !== 'AccesoSiqueSi') { die("Acceso Denegado"); }

// 2. CONFIGURACIÓN DB
$nombre_bd    = "MS_Datos"; 
$IDU_Contexto = isset($_GET['IDU']) ? $_GET['IDU'] : ($_SESSION['IDU'] ?? '1'); 
$prefijo   =  $IDUg;
	echo "<script> console.log('ID Usuario: $prefijo'); </script>";

// Mapeo de Tablas
$tb_cab      = $prefijo . "-Compras_Cabecera";
$tb_det      = $prefijo . "-Compras_Detalle";
$tb_prov     = $prefijo . "-Proveedores";        
$tb_prod_cat = $prefijo . "-Productos_Catalogo";     
$tb_prod_inv = $prefijo . "-Productos_Inventario"; 
$tb_series   = $prefijo . "-Productos_Series";
?>

<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@ttskch/select2-bootstrap4-theme@x.x.x/dist/select2-bootstrap4.min.css">
<style>
    /* ESTILOS DE LA VISTA */
    .module-compra { font-family: 'Segoe UI', sans-serif; color: #444; }
    .card-pro { border: none; border-radius: 8px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); background: #fff; margin-bottom: 20px; }
    .card-header-pro { background: #fff; padding: 15px 20px; border-bottom: 2px solid #f1f1f1; font-weight: 700; color: #333; display: flex; justify-content: space-between; align-items: center; border-radius: 8px 8px 0 0; }
    .form-control-pro { border: 1px solid #e0e0e0; border-radius: 6px; padding: 8px 12px; height: 40px; width: 100%; }
    .select2-container--bootstrap4 .select2-selection--single { height: 40px !important; line-height: 24px; border: 1px solid #e0e0e0; }
    
    /* Botones de Acción */
    .btn-action { border: none; padding: 10px 20px; border-radius: 6px; font-weight: 600; cursor: pointer; transition: 0.2s; }
    .btn-add { background: #4099ff; color: white; width: 100%; }
    .btn-save { background: #2ed8b6; color: white; box-shadow: 0 4px 10px rgba(46, 216, 182, 0.3); }
    
    /* Botones de Series (Estados) */
    .btn-series { font-size: 0.8rem; padding: 5px 12px; border-radius: 20px; font-weight: 600; border: none; cursor: pointer; display: inline-flex; align-items: center; gap: 5px; transition: all 0.3s; }
    .btn-series-ok { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
    .btn-series-warn { background: #fff3cd; color: #856404; border: 1px solid #ffeeba; animation: pulse 2s infinite; }
    .btn-series-off { background: #f8f9fa; color: #6c757d; border: 1px solid #dee2e6; }
    .btn-series-off:hover { background: #e2e6ea; }

    /* Totales y Textos */
    .total-display { font-size: 2rem; font-weight: 800; color: #2ed8b6; text-align: right; }
    .text-sku { font-family: 'Consolas', monospace; color: #888; font-size: 0.85rem; }
    
    @keyframes pulse { 0% { box-shadow: 0 0 0 0 rgba(255, 193, 7, 0.4); } 70% { box-shadow: 0 0 0 10px rgba(255, 193, 7, 0); } 100% { box-shadow: 0 0 0 0 rgba(255, 193, 7, 0); } }
</style>

<div class="module-compra p-2">

    <div class="d-flex justify-content-between align-items-center mb-3">
        <div>
            <h4 class="m-0 font-weight-bold">Nueva Compra</h4>
            <small class="text-muted">Recepción de inventario con gestión de series</small>
        </div>
        <div>
            <button class="btn btn-light border mr-2" onclick="location.reload()"><i class="fas fa-eraser"></i> Limpiar</button>
            <button class="btn-action btn-save" onclick="procesarCompra()"><i class="fas fa-check-circle mr-1"></i> FINALIZAR COMPRA</button>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-4">
            <div class="card-pro h-100">
                <div class="card-header-pro">
                    <span><i class="far fa-file-alt text-primary mr-2"></i> Datos Generales</span>
                </div>
                <div class="p-4">
                    <div class="form-group mb-3">
                        <label class="font-weight-bold text-muted small">PROVEEDOR</label>
                        <select id="IDP" class="form-control" style="width: 100%;"></select>
                        <div class="text-right mt-1"><small id="rfc_display" class="text-info font-weight-bold"></small></div>
                    </div>
                    <div class="row">
                        <div class="col-6">
                            <div class="form-group mb-3">
                                <label class="font-weight-bold text-muted small">FOLIO</label>
                                <input type="text" id="Folio" class="form-control-pro" placeholder="Ej. A-100">
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="form-group mb-3">
                                <label class="font-weight-bold text-muted small">FECHA</label>
                                <input type="date" id="Fecha" class="form-control-pro" value="<?php echo date('Y-m-d'); ?>">
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="font-weight-bold text-muted small">NOTAS</label>
                        <textarea id="Notas" class="form-control-pro" rows="3" style="height: auto;"></textarea>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-8">
            <div class="card-pro">
                <div class="card-header-pro">
                    <span><i class="fas fa-box-open text-primary mr-2"></i> Productos</span>
                    <span class="badge badge-primary p-2" id="badge_count">0 Items</span>
                </div>
                
                <div class="p-3 bg-light border-bottom">
                    <div class="row align-items-end gutter-10">
                        <div class="col-md-5">
                            <label class="small font-weight-bold text-muted">BUSCAR PRODUCTO</label>
                            <select id="BuscarSKU" class="form-control" style="width: 100%;"></select>
                            <input type="hidden" id="TmpNombre"><input type="hidden" id="TmpSKU">
                        </div>
                        <div class="col-md-2">
                            <label class="small font-weight-bold text-muted">COSTO UNIT.</label>
                            <input type="number" id="TmpCosto" class="form-control-pro" step="0.01" placeholder="$0.00">
                        </div>
                        <div class="col-md-2">
                            <label class="small font-weight-bold text-muted">CANTIDAD</label>
                            <input type="number" id="TmpCant" class="form-control-pro text-center" value="1" min="1">
                        </div>
                        <div class="col-md-3">
                            <button class="btn-action btn-add" onclick="agregarAlCarrito()"><i class="fas fa-plus"></i> AGREGAR</button>
                        </div>
                    </div>
                </div>

                <div class="table-responsive" style="min-height: 300px; max-height: 500px; overflow-y: auto;">
                    <table class="table-cart" style="width:100%">
                        <thead>
                            <tr style="background:#f9f9f9; border-bottom:1px solid #eee;">
                                <th style="padding:10px;">SKU</th>
                                <th style="padding:10px;">Descripción / Gestión</th>
                                <th style="padding:10px; text-align:center;">Cant.</th>
                                <th style="padding:10px; text-align:right;">Costo</th>
                                <th style="padding:10px; text-align:right;">Total</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody id="tbody_carrito">
                            <tr><td colspan="6" class="text-center py-5 text-muted">Carrito Vacío</td></tr>
                        </tbody>
                    </table>
                </div>

                <div class="p-3 bg-white border-top text-right">
                    <span class="text-muted mr-3">TOTAL COMPRA:</span>
                    <span id="total_display" class="total-display">$0.00</span>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    // CONFIGURACIÓN CENTRAL
    const APP = {
        db:       "<?php echo $nombre_bd; ?>",
        user:     "<?php echo $_SESSION['IDU'] ?? 'ADMIN'; ?>",
        sucursal: "<?php echo $_SESSION['IDS_Sucursal'] ?? 1; ?>",
        tables: {
            prov:   "<?php echo $tb_prov; ?>",
            cat:    "<?php echo $tb_prod_cat; ?>",
            inv:    "<?php echo $tb_prod_inv; ?>",
            cab:    "<?php echo $tb_cab; ?>",
            det:    "<?php echo $tb_det; ?>",
            series: "<?php echo $tb_series; ?>"
        }
    };

    let carrito = [];
    let Toast; 

    $(document).ready(function() {
        Toast = Swal.mixin({ toast: true, position: 'top-end', showConfirmButton: false, timer: 3000, timerProgressBar: true });
        initProveedores();
        initBuscadorProductos();
    });

    // ----------------------------------------------------------------------
    // 1. CARGA DE DATOS (AJAX)
    // ----------------------------------------------------------------------
    async function sqlRequest(sql, type = 'SELECT') {
        const url = type === 'SELECT' ? '../librerias/AJAX/Select.php' : '../librerias/AJAX/Execute.php';
        const formData = new FormData(); formData.append('sql', sql); formData.append('db', APP.db);
        try {
            const res = await fetch(url, { method: 'POST', body: formData });
            return await res.json();
        } catch (error) { return { status: 'error', message: error }; }
    }

    function initProveedores() {
        const q = `SELECT IDPr, razon_social, rfc FROM \`${APP.db}\`.\`${APP.tables.prov}\` WHERE activo = 1 ORDER BY razon_social ASC`;
        sqlRequest(q).then(res => {
            const sel = $('#IDP');
            sel.empty().append('<option value="">-- Seleccionar --</option>');
            if(res.data) res.data.forEach(p => {
                const opt = new Option(p.razon_social, p.IDPr, false, false);
                $(opt).attr('data-rfc', p.rfc || 'S/RFC');
                sel.append(opt);
            });
            sel.select2({ theme: 'bootstrap4', width: '100%' });
            sel.on('change', function() { $('#rfc_display').text($(this).find(':selected').attr('data-rfc') || ''); });
        });
    }

    function initBuscadorProductos() {
        $('#BuscarSKU').select2({
            theme: 'bootstrap4', placeholder: 'Buscar producto...', minimumInputLength: 2,
            ajax: {
                url: '../librerias/AJAX/Select.php', type: 'POST', dataType: 'json', delay: 250,
                data: function(params) {
                    const term = params.term.replace(/'/g, ""); 
                    const sql = `SELECT T1.sku as id, T1.nombre as text, T2.costo_promedio FROM \`${APP.db}\`.\`${APP.tables.cat}\` T1 LEFT JOIN \`${APP.db}\`.\`${APP.tables.inv}\` T2 ON T1.sku = T2.sku WHERE (T1.nombre LIKE '%${term}%' OR T1.sku LIKE '%${term}%') AND T1.activo = 1 LIMIT 20`;
                    return { sql: sql, db: APP.db };
                },
                processResults: function(data) {
                    return { results: data.data ? data.data.map(item => ({ id: item.id, text: item.text, nombre_real: item.text, costo: item.costo_promedio || 0 })) : [] };
                }
            }
        });
        $('#BuscarSKU').on('select2:select', function(e) {
            const data = e.params.data;
            $('#TmpSKU').val(data.id); $('#TmpNombre').val(data.nombre_real); $('#TmpCosto').val(parseFloat(data.costo).toFixed(2)); $('#TmpCant').focus().select();
        });
    }

    // ----------------------------------------------------------------------
    // 2. LOGICA DEL CARRITO
    // ----------------------------------------------------------------------
    function agregarAlCarrito() {
        const sku = $('#TmpSKU').val();
        const nombre = $('#TmpNombre').val();
        const costo = parseFloat($('#TmpCosto').val());
        const cant = parseInt($('#TmpCant').val());

        if(!sku) return Toast.fire({ icon: 'warning', title: 'Busca un producto.' });
        if(isNaN(costo) || costo < 0) return Toast.fire({ icon: 'error', title: 'Costo inválido.' });
        if(isNaN(cant) || cant <= 0) return Toast.fire({ icon: 'error', title: 'Cantidad inválida.' });

        const index = carrito.findIndex(i => i.sku === sku);
        if(index > -1) {
            carrito[index].cant += cant;
            carrito[index].costo = costo;
            carrito[index].subtotal = carrito[index].cant * costo;
            Toast.fire({ icon: 'info', title: 'Producto actualizado.' });
        } else {
            // Inicializamos: Por defecto asumimos que NO lleva series hasta que el usuario decida en el modal,
            // O podemos asumir que SÍ. Aquí pondremos usa_serie: false por defecto para agilizar, y el usuario activa en el modal.
            // *NOTA*: Si prefieres que por defecto pida series, cambia usa_serie: true.
            carrito.push({ 
                sku, nombre, cant, costo, subtotal: cant * costo, 
                series: [], 
                usa_serie: false // Estado inicial
            });
            Toast.fire({ icon: 'success', title: 'Producto agregado.' });
        }
        renderCarrito(); limpiarInputProducto();
    }

    function renderCarrito() {
        const tbody = $('#tbody_carrito'); tbody.empty();
        let total = 0;

        if(carrito.length === 0) {
            tbody.html('<tr><td colspan="6" class="text-center py-5 text-muted">Carrito Vacío</td></tr>');
            $('#total_display').text('$0.00'); $('#badge_count').text('0 Items'); return;
        }

        carrito.forEach((item, idx) => {
            total += item.subtotal;
            
            // Lógica del Botón de Series
            let btnHTML = '';
            if(item.usa_serie) {
                const faltan = item.cant - item.series.length;
                const isOK = faltan === 0;
                const clase = isOK ? 'btn-series-ok' : 'btn-series-warn';
                const icono = isOK ? '<i class="fas fa-check"></i>' : '<i class="fas fa-exclamation-triangle"></i>';
                const texto = isOK ? 'Series Listas' : `Faltan ${faltan}`;
                btnHTML = `<button class="btn-series ${clase}" onclick="gestionarSeries(${idx})">${icono} ${texto}</button>`;
            } else {
                btnHTML = `<button class="btn-series btn-series-off" onclick="gestionarSeries(${idx})"><i class="fas fa-ban"></i> Sin Series</button>`;
            }

            const fila = `
                <tr style="border-bottom:1px solid #f1f1f1;">
                    <td class="text-sku p-2">${item.sku}</td>
                    <td class="p-2">
                        <span class="font-weight-bold text-dark">${item.nombre}</span><br>
                        ${btnHTML}
                    </td>
                    <td class="text-center font-weight-bold p-2">${item.cant}</td>
                    <td class="text-right p-2">$${item.costo.toFixed(2)}</td>
                    <td class="text-right font-weight-bold p-2">$${item.subtotal.toFixed(2)}</td>
                    <td class="text-center p-2"><button class="btn btn-sm text-danger" onclick="eliminarItem(${idx})"><i class="fas fa-trash"></i></button></td>
                </tr>
            `;
            tbody.append(fila);
        });

        const f = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
        $('#total_display').text(f.format(total));
        $('#badge_count').text(carrito.length + ' Items');
    }

    function eliminarItem(idx) { carrito.splice(idx, 1); renderCarrito(); }
    
    function limpiarInputProducto() {
        $('#BuscarSKU').val(null).trigger('change'); $('#TmpSKU').val(''); $('#TmpNombre').val(''); 
        $('#TmpCosto').val(''); $('#TmpCant').val('1'); $('#BuscarSKU').select2('open');
    }

    // ----------------------------------------------------------------------
    // 3. GESTIÓN DE SERIES (MODAL INTELIGENTE)
    // ----------------------------------------------------------------------
    async function gestionarSeries(idx) {
        const item = carrito[idx];
        const textoActual = item.series ? item.series.join('\n') : '';
        const isChecked = item.usa_serie ? 'checked' : '';
        const bgArea = item.usa_serie ? '#fff' : '#f8f9fa';
        const disabled = item.usa_serie ? '' : 'disabled';

        // HTML del Modal
        const htmlContent = `
            <div class="text-left border-bottom pb-2 mb-2">
                <div class="custom-control custom-switch">
                    <input type="checkbox" class="custom-control-input" id="checkSeries" ${isChecked}>
                    <label class="custom-control-label font-weight-bold text-primary" for="checkSeries">
                        Este producto requiere Números de Serie
                    </label>
                </div>
            </div>
            <textarea id="inputSeries" class="form-control" rows="8" ${disabled}
                placeholder="Escanea aquí (uno por línea)..."
                style="font-family:monospace; background-color:${bgArea}">${textoActual}</textarea>
            <div class="text-right mt-1">
                <small class="text-muted">Requeridos: <b>${item.cant}</b></small>
            </div>
        `;

        const { value: formValues } = await Swal.fire({
            title: `Series: ${item.sku}`,
            html: htmlContent,
            showCancelButton: true,
            confirmButtonText: 'Guardar Configuración',
            didOpen: () => {
                const chk = document.getElementById('checkSeries');
                const txt = document.getElementById('inputSeries');
                chk.addEventListener('change', (e) => {
                    txt.disabled = !e.target.checked;
                    txt.style.backgroundColor = e.target.checked ? '#fff' : '#f8f9fa';
                    if(e.target.checked) txt.focus();
                });
            },
            preConfirm: () => {
                const usa = document.getElementById('checkSeries').checked;
                const raw = document.getElementById('inputSeries').value;
                const lineas = raw.split('\n').map(l => l.trim()).filter(l => l !== '');

                if (usa) {
                    if (lineas.length !== item.cant) {
                        Swal.showValidationMessage(`Error: Se requieren ${item.cant} series, ingresaste ${lineas.length}.`);
                        return false;
                    }
                    const unicos = [...new Set(lineas)];
                    if (unicos.length !== lineas.length) {
                        Swal.showValidationMessage(`Error: Hay series duplicadas.`);
                        return false;
                    }
                    return { usa: true, series: lineas };
                } else {
                    return { usa: false, series: [] };
                }
            }
        });

        if (formValues) {
            carrito[idx].usa_serie = formValues.usa;
            carrito[idx].series = formValues.series;
            renderCarrito();
            Toast.fire({ icon: 'success', title: 'Configuración guardada.' });
        }
    }

    // ----------------------------------------------------------------------
    // 4. GUARDADO FINAL
    // ----------------------------------------------------------------------
    async function procesarCompra() {
        const idp = $('#IDP').val();
        const folio = $('#Folio').val();
        const fecha = $('#Fecha').val();
        const notas = $('#Notas').val();

        if(!idp) return Swal.fire('Error', 'Selecciona Proveedor', 'warning');
        if(!folio) return Swal.fire('Error', 'Falta Folio', 'warning');
        if(carrito.length === 0) return Swal.fire('Error', 'Carrito vacío', 'warning');

        // Validar series completas antes de enviar
        for(let item of carrito) {
            if(item.usa_serie && item.series.length !== item.cant) {
                return Swal.fire('Series Incompletas', `Revisa el producto ${item.sku}. Faltan series.`, 'error');
            }
        }

        const total = carrito.reduce((sum, i) => sum + i.subtotal, 0);

        Swal.fire({
            title: '¿Finalizar Compra?',
            text: `Total: $${total.toFixed(2)}`,
            icon: 'question', showCancelButton: true, confirmButtonText: 'Sí, Guardar', confirmButtonColor: '#2ed8b6'
        }).then(async (r) => {
            if(r.isConfirmed) {
                Swal.fire({title:'Guardando...', allowOutsideClick:false, didOpen:()=>Swal.showLoading()});
                
                try {
                    // 1. Cabecera
                    const sqlCab = `INSERT INTO \`${APP.db}\`.\`${APP.tables.cab}\` (Folio_Factura, IDP, IDS_Sucursal, IDU_Usuario, Fecha, Total_Compra, Estado, Notas) VALUES ('${folio}', ${idp}, ${APP.sucursal}, '${APP.user}', '${fecha} 00:00:00', ${total}, 'Finalizada', '${notas.replace(/'/g, "")}')`;
                    const resCab = await sqlRequest(sqlCab, 'EXECUTE');
                    if(!resCab.last_id) throw new Error("Error en Cabecera");
                    const idCompra = resCab.last_id;

                    // 2. Detalles
                    let valsDet = [];
                    carrito.forEach(i => valsDet.push(`(${idCompra}, '${i.sku}', ${i.cant}, ${i.costo}, ${i.subtotal})`));
                    const sqlDet = `INSERT INTO \`${APP.db}\`.\`${APP.tables.det}\` (ID_Compra, SKU, Cantidad, Costo_Unitario, Subtotal) VALUES ${valsDet.join(',')}`;
                    await sqlRequest(sqlDet, 'EXECUTE');

                    // 3. Series (Solo las que apliquen)
                    let valsSer = [];
                    carrito.forEach(i => {
                        if(i.usa_serie) {
                            i.series.forEach(s => valsSer.push(`('${i.sku}', '${s.replace(/'/g,"")}', ${idCompra}, 'DISPONIBLE')`));
                        }
                    });
                    if(valsSer.length > 0) {
                        const sqlSer = `INSERT INTO \`${APP.db}\`.\`${APP.tables.series}\` (SKU, Serie, ID_Compra, Estado) VALUES ${valsSer.join(',')}`;
                        await sqlRequest(sqlSer, 'EXECUTE');
                    }

                    // 4. Inventario (Upsert)
                    for(let i of carrito) {
                        const sqlInv = `INSERT INTO \`${APP.db}\`.\`${APP.tables.inv}\` (IDP, sku, IDS, existencia, costo_promedio, stock_minimo, stock_maximo) VALUES (0, '${i.sku}', ${APP.sucursal}, ${i.cant}, ${i.costo}, 0, 0) ON DUPLICATE KEY UPDATE existencia=existencia+${i.cant}, costo_promedio=${i.costo}, ultimo_movimiento=NOW()`;
                        await sqlRequest(sqlInv, 'EXECUTE');
                    }

                    Swal.fire('Éxito', 'Compra guardada correctamente', 'success').then(()=>location.reload());

                } catch(e) {
                    Swal.fire('Error', e.message, 'error');
                }
            }
        });
    }
</script>