<?php
/**
 * MODULO: GESTION DE KITS PROFESIONAL (FIX INVENTARIO)
 * Sistema: Multi-usuario | DB: MS_Datos
 */
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!isset($_SESSION['Acceso']) || $_SESSION['Acceso'] !== 'AccesoSiqueSi') {
    die("Acceso Denegado");
}

$IDUg = $_SESSION['IDUg'] ?? 1;
$DB_TARGET = "MS_Datos";
$T_CAT = $IDUg . "-Productos_Catalogo";
$T_INV = $IDUg . "-Productos_Inventario";
?>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<style>
    :root { --primary: #4e73df; --dark: #404E67; --success: #1cc88a; --danger: #e74a3b; }
    body { background-color: #f8f9fc; font-family: 'Segoe UI', sans-serif; }
    .main-container { background: white; border-radius: 12px; box-shadow: 0 5px 15px rgba(0,0,0,0.08); overflow: hidden; }
    .nav-tabs-custom { background: var(--dark); border: none; padding: 10px 15px 0; }
    .nav-tabs-custom .nav-link { color: rgba(255,255,255,0.6); border: none; font-weight: 600; padding: 12px 20px; }
    .nav-tabs-custom .nav-link.active { background: white; color: var(--dark); border-radius: 10px 10px 0 0; }
    .search-box .select2-container--default .select2-selection--single { height: 50px !important; border: 2px solid #eaecf4 !important; border-radius: 10px !important; display: flex; align-items: center; padding-left: 10px; }
    .kit-pill { background: #f1f3f9; color: var(--primary); padding: 2px 8px; border-radius: 6px; font-size: 11px; font-weight: bold; margin: 2px; display: inline-block; border: 1px solid #d1d3e2; }
</style>

<div class="container-fluid p-4">
    <div class="main-container">
        <ul class="nav nav-tabs nav-tabs-custom" id="kitTabs" role="tablist">
            <li class="nav-item"><a class="nav-link active" data-toggle="tab" href="#constructor-tab"><i class="fas fa-hammer mr-2"></i>Constructor</a></li>
            <li class="nav-item"><a class="nav-link" data-toggle="tab" href="#lista-tab" onclick="listarKits()"><i class="fas fa-boxes mr-2"></i>Kits Guardados</a></li>
        </ul>

        <div class="tab-content p-4">
            <div class="tab-pane fade show active" id="constructor-tab">
                <div class="row">
                    <div class="col-md-4 border-right pr-4">
                        <label class="font-weight-bold small text-muted text-uppercase">1. Buscar Componente</label>
                        <div class="search-box">
                            <select id="buscador_kit" class="form-control" style="width: 100%;"></select>
                        </div>
                        <div class="card mt-4 bg-light border-0">
                            <div class="card-body">
                                <h6 class="font-weight-bold small">RESUMEN</h6>
                                <div class="d-flex justify-content-between"><span>Items:</span> <b id="lbl_cant">0</b></div>
                                <div class="d-flex justify-content-between h5 mt-2"><span>Costo Base:</span> <b id="lbl_costo">$ 0.00</b></div>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-8 pl-4">
                        <h6 class="font-weight-bold small text-uppercase mb-3">2. Composición del Kit</h6>
                        <table class="table table-sm align-middle">
                            <thead class="bg-light">
                                <tr>
                                    <th>Producto</th>
                                    <th class="text-center">Cant.</th>
                                    <th class="text-right">Unitario</th>
                                    <th class="text-right">Subtotal</th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody id="constructor_body"></tbody>
                        </table>
                        
                        <div class="card p-4 mt-4 bg-light border-0 shadow-sm">
                            <div class="row align-items-end">
                                <div class="col-md-7">
                                    <label class="small font-weight-bold">Nombre del Kit:</label>
                                    <input type="text" id="in_nombre" class="form-control mb-2" placeholder="Ej: Paquete de Limpieza">
                                    <label class="small font-weight-bold">SKU Maestro:</label>
                                    <input type="text" id="in_sku" class="form-control" placeholder="SKU-KIT-001">
                                </div>
                                <div class="col-md-5 text-right">
                                    <div id="renta_msg" class="small font-weight-bold mb-1"></div>
                                    <label class="small font-weight-bold text-primary">PRECIO VENTA FINAL:</label>
                                    <input type="number" id="in_precio_venta" class="form-control form-control-lg text-right font-weight-bold" onkeyup="checkPrecio()" placeholder="0.00">
                                </div>
                            </div>
                            <button class="btn btn-primary btn-block btn-lg mt-4 font-weight-bold shadow" onclick="guardarTodo()">
                                <i class="fas fa-save mr-2"></i>GUARDAR KIT COMPLETO
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <div class="tab-pane fade" id="lista-tab">
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>Kit / SKU</th>
                                <th>Componentes</th>
                                <th class="text-right">Precio Venta</th>
                                <th class="text-right">Acciones</th>
                            </tr>
                        </thead>
                        <tbody id="lista_body"></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
let itemsKit = [];
let costoActual = 0;
const DB = "<?php echo $DB_TARGET; ?>";
const T_CAT = "<?php echo $T_CAT; ?>";
const T_INV = "<?php echo $T_INV; ?>";

$(document).ready(function() {
    // Buscador Auto-acompletable
    $('#buscador_kit').select2({
        ajax: {
            url: '../librerias/AJAX/Select.php',
            type: 'POST',
            dataType: 'json',
            delay: 300,
            data: function (params) {
                let term = params.term.replace(/'/g, "\\'");
                let sql = `SELECT c.IDP, c.sku, c.nombre, i.precio_venta 
                           FROM \`${T_CAT}\` c 
                           INNER JOIN \`${T_INV}\` i ON c.sku = i.sku 
                           WHERE c.tipo_item = 'producto' AND c.activo = 1 
                           AND (c.nombre LIKE '%${term}%' OR c.sku LIKE '%${term}%') LIMIT 10`;
                return { sql: sql, db: DB };
            },
            processResults: function (data) {
                let res = data.data || (Array.isArray(data) ? data : []);
                return { results: res.map(p => ({ id: p.IDP, text: p.nombre, sku: p.sku, precio: p.precio_venta, raw: p })) };
            }
        },
        placeholder: "Escribe para buscar...",
        minimumInputLength: 2,
        templateResult: (r) => r.loading ? "..." : `<div><b>${r.text}</b><br><small>${r.sku} - $${parseFloat(r.precio).toFixed(2)}</small></div>`,
        escapeMarkup: (m) => m
    });

    $('#buscador_kit').on('select2:select', function (e) {
        let p = e.params.data.raw;
        let ex = itemsKit.find(x => x.sku === p.sku);
        if(ex) { ex.cant++; } else { itemsKit.push({...p, cant: 1}); }
        render();
        $(this).val(null).trigger('change');
    });
});

function render() {
    const b = $('#constructor_body');
    let h = ''; costoActual = 0;
    itemsKit.forEach((p, i) => {
        let sub = p.cant * p.precio_venta;
        costoActual += sub;
        h += `<tr>
            <td><strong>${p.nombre}</strong><br><small>${p.sku}</small></td>
            <td class="text-center"><input type="number" class="qty-control" value="${p.cant}" onchange="updateCant(${i}, this.value)"></td>
            <td class="text-right">$${parseFloat(p.precio_venta).toFixed(2)}</td>
            <td class="text-right font-weight-bold">$${sub.toFixed(2)}</td>
            <td class="text-center"><i class="fas fa-trash text-danger" style="cursor:pointer" onclick="quitar(${i})"></i></td>
        </tr>`;
    });
    b.html(h);
    $('#lbl_cant').text(itemsKit.length);
    $('#lbl_costo').text(`$ ${costoActual.toFixed(2)}`);
    checkPrecio();
}

function updateCant(i, v) { if(v < 1) return quitar(i); itemsKit[i].cant = v; render(); }
function quitar(i) { itemsKit.splice(i, 1); render(); }

function checkPrecio() {
    const v = parseFloat($('#in_precio_venta').val()) || 0;
    const m = $('#renta_msg');
    if(v === 0) return m.html('');
    if(v < costoActual) {
        m.html('<span class="text-danger">⚠️ Precio bajo el costo ($'+costoActual.toFixed(2)+')</span>');
        $('#in_precio_venta').css('border-color', 'red');
    } else {
        m.html('<span class="text-success">✅ Margen Correcto</span>');
        $('#in_precio_venta').css('border-color', '#1cc88a');
    }
}

// GUARDADO CORREGIDO: SE INCLUYEN TODOS LOS CAMPOS OBLIGATORIOS (IDP, SKU, IDS)
async function guardarTodo() {
    const s = $('#in_sku').val().trim();
    const n = $('#in_nombre').val().trim();
    const p = parseFloat($('#in_precio_venta').val()) || 0;

    if(!s || !n || p === 0 || itemsKit.length === 0) return Swal.fire('Error', 'Completa todos los campos.', 'error');
    if(p < costoActual) return Swal.fire('No rentable', 'El precio es menor al costo.', 'warning');

    Swal.fire({ title: 'Guardando...', didOpen: () => Swal.showLoading() });

    // 1. Validar SKU Duplicado
    const checkSql = `SELECT COUNT(*) as t FROM \`${T_CAT}\` WHERE sku = '${s}'`;
    const check = await fetch('../librerias/AJAX/Select.php', { method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body:`sql=${encodeURIComponent(checkSql)}&db=${DB}` }).then(r=>r.json());
    if((check.data?.[0]?.t || check[0]?.t || 0) > 0) return Swal.fire('Error', 'El SKU ya existe.', 'error');

    // 2. Inserción en Catálogo
    const json = JSON.stringify(itemsKit.map(i => ({sku: i.sku, cant: i.cant})));
    const q1 = `INSERT INTO \`${T_CAT}\` (sku, nombre, tipo_item, Datos, activo) VALUES ('${s}', '${n}', 'kit', '${json}', 1)`;
    
    // 3. Inserción en Inventario (CORREGIDO: Incluimos IDP y IDS)
    // Según tu esquema IDP es obligatorio y único. Usamos el SKU como IDP alfanumérico.
    const q2 = `INSERT INTO \`${T_INV}\` (IDP, sku, IDS, precio_venta, existencia, disponible) VALUES ('${s}', '${s}', 1, ${p}, 0, 0)`;

    try {
        await fetch('../librerias/AJAX/Execute.php', { method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body:`sql=${encodeURIComponent(q1)}&db=${DB}` });
        await fetch('../librerias/AJAX/Execute.php', { method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body:`sql=${encodeURIComponent(q2)}&db=${DB}` });
        Swal.fire('¡Éxito!', 'Kit guardado correctamente en Catálogo e Inventario.', 'success').then(() => location.reload());
    } catch(e) { 
        Swal.fire('Error', 'Fallo al guardar en MS_Datos.', 'error'); 
    }
}

async function listarKits() {
    const b = $('#lista_body');
    b.html('<tr><td colspan="4" class="text-center p-5"><i class="fas fa-sync fa-spin"></i></td></tr>');

    // LEFT JOIN para asegurar traer el precio de la tabla de inventario
    const sql = `SELECT c.sku, c.nombre, c.Datos, i.precio_venta 
                 FROM \`${T_CAT}\` c 
                 LEFT JOIN \`${T_INV}\` i ON c.sku = i.sku 
                 WHERE c.tipo_item = 'kit' AND c.activo = 1 ORDER BY c.IDP DESC`;

    const res = await fetch('../librerias/AJAX/Select.php', { method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body:`sql=${encodeURIComponent(sql)}&db=${DB}` }).then(r=>r.json());
    const data = res.data || (Array.isArray(res) ? res : []);
    
    let h = '';
    data.forEach(k => {
        let comp = '';
        try { JSON.parse(k.Datos).forEach(d => comp += `<span class='kit-pill'>${d.sku} x${d.cant}</span>`); } catch(e){}
        h += `<tr>
            <td><strong>${k.nombre}</strong><br><small>${k.sku}</small></td>
            <td>${comp}</td>
            <td class="text-right font-weight-bold text-success">$${parseFloat(k.precio_venta || 0).toFixed(2)}</td>
            <td class="text-right">
                <button class="btn btn-sm btn-outline-danger" onclick="eliminarKit('${k.sku}')"><i class="fas fa-trash"></i></button>
            </td>
        </tr>`;
    });
    b.html(h || '<tr><td colspan="4" class="text-center">No hay kits</td></tr>');
}

async function eliminarKit(s) {
    const r = await Swal.fire({ title: '¿Eliminar?', icon: 'warning', showCancelButton: true });
    if(r.isConfirmed) {
        await fetch('../librerias/AJAX/Execute.php', { method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body:`sql=${encodeURIComponent(`UPDATE \`${T_CAT}\` SET activo = 0 WHERE sku = '${s}'`)}&db=${DB}` });
        listarKits();
    }
}
</script>