<?php
require_once __DIR__ . '/../../includes/layout.php';
$pdo = getDBConnection();
renderHeader('Distribución desde Bodega', 'distribucion');
?>
<link rel="stylesheet" href="assets/css/bootstrap-icons.min.css">
<style>
:root {
  --surface-card: #ffffff;
  --border-color: #e2e8f0;
  --text-primary: #2F2F2F;
  --text-secondary: #64748b;
  --accent-color: #0284c7;
  --dc-primary: #0284c7;
  --dc-primary-light: #38bdf8;
}

.dc-container { max-width: 1400px; margin: 0 auto; padding: 1.5rem; }
.dc-topbar { display: flex; flex-wrap: wrap; align-items: center; gap: 1rem; margin-bottom: 1.5rem; }
.dc-topbar h1 { font-size: 1.5rem; font-weight: 800; color: var(--text-primary); display: flex; align-items: center; gap: 0.5rem; margin: 0; }
.dc-topbar h1 small { font-size: 0.875rem; font-weight: 400; color: var(--text-secondary); }

.btn { display: inline-flex; align-items: center; gap: 0.4rem; padding: 0.5rem 1.25rem; border-radius: 0.75rem; font-size: 0.8rem; font-weight: 700; border: none; cursor: pointer; transition: all 0.15s; text-decoration: none; }
.btn-primary { background: var(--accent-color); color: #fff; }
.btn-primary:hover { background: #0369a1; }
.btn-outline { background: transparent; color: var(--text-secondary); border: 1px solid var(--border-color); }
.btn-outline:hover { background: #f8fafc; color: var(--text-primary); }
.btn-sm { padding: 0.35rem 0.75rem; font-size: 0.75rem; }

.dc-tabs { display: flex; gap: 0.25rem; border-bottom: 2px solid var(--border-color); margin-bottom: 1.5rem; overflow-x: auto; }
.dc-tab { padding: 0.6rem 1.25rem; font-size: 0.85rem; font-weight: 600; color: var(--text-secondary); border: none; background: none; cursor: pointer; white-space: nowrap; border-bottom: 2px solid transparent; margin-bottom: -2px; transition: all 0.15s; }
.dc-tab:hover { color: var(--text-primary); }
.dc-tab.active { color: var(--dc-primary); border-bottom-color: var(--dc-primary); }

.dc-card { background: var(--surface-card); border: 1px solid var(--border-color); border-radius: 1rem; padding: 1.5rem; margin-bottom: 1rem; }

.dc-grid-3 { display: grid; grid-template-columns: 1fr; gap: 1rem; margin-bottom: 1rem; }
@media (min-width: 1024px) { .dc-grid-3 { grid-template-columns: 1fr 2fr; } }

.dc-stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 0.75rem; margin-bottom: 1rem; }
.dc-stat { background: #f8fafc; border: 1px solid var(--border-color); border-radius: 0.75rem; padding: 0.75rem 1rem; text-align: center; }
.dc-stat-label { font-size: 0.7rem; text-transform: uppercase; font-weight: 700; color: var(--text-secondary); letter-spacing: 0.03em; }
.dc-stat-value { font-size: 1.5rem; font-weight: 800; color: var(--text-primary); line-height: 1.3; }

table.dc-data { width: 100%; border-collapse: collapse; }
table.dc-data thead th { padding: 0.65rem 0.75rem; font-size: 0.7rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; color: var(--text-secondary); border-bottom: 2px solid var(--border-color); text-align: left; white-space: nowrap; }
table.dc-data tbody td { padding: 0.65rem 0.75rem; font-size: 0.85rem; border-bottom: 1px solid var(--border-color); vertical-align: middle; }
table.dc-data tbody tr:hover { background: #f8fafc; }

.filter-row { display: flex; flex-wrap: wrap; gap: 0.75rem; align-items: center; margin-bottom: 1rem; }
.filter-row input[type="text"], .filter-row select { padding: 0.5rem 0.75rem; border-radius: 0.75rem; border: 1px solid var(--border-color); background: var(--surface-card); color: var(--text-primary); font-size: 0.85rem; }
.filter-row input:focus, .filter-row select:focus { outline: none; border-color: var(--accent-color); }

.tab-content { display: none; }
.tab-content.active { display: block; }

.search-input { width: 100%; padding: 0.65rem 0.9rem; border-radius: 0.75rem; border: 1px solid var(--border-color); font-size: 0.9rem; color: var(--text-primary); box-sizing: border-box; }
.search-input:focus { outline: none; border-color: var(--accent-color); }

.prod-result { padding: 0.6rem 0.8rem; border-radius: 0.75rem; cursor: pointer; border: 1px solid transparent; transition: all 0.1s; }
.prod-result:hover { background: #f8fafc; border-color: var(--border-color); }
.prod-result.selected { background: #f0f9ff; border-color: var(--accent-color); }

.dist-suc-card { background: #f8fafc; border: 1px solid var(--border-color); border-radius: 0.75rem; padding: 0.75rem; }
.dist-suc-card label { display: block; font-size: 0.8rem; font-weight: 600; color: var(--text-secondary); margin-bottom: 0.3rem; }
.dist-suc-card input[type="number"] { width: 100%; padding: 0.5rem 0.65rem; border-radius: 0.75rem; border: 1px solid var(--border-color); font-size: 0.85rem; text-align: right; box-sizing: border-box; }
.dist-suc-card input:focus { outline: none; border-color: var(--accent-color); }

.hist-item { background: var(--surface-card); border: 1px solid var(--border-color); border-radius: 1rem; padding: 1rem; margin-bottom: 0.75rem; }
.hist-item-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem; }
.hist-item-header .id { font-family: monospace; font-size: 0.75rem; color: var(--text-secondary); }
.hist-item-header .fecha { font-weight: 700; font-size: 0.9rem; }
.hist-item-header .estado { font-size: 0.65rem; font-weight: 700; text-transform: uppercase; padding: 0.2rem 0.6rem; border-radius: 1rem; background: #d1fae5; color: #065f46; }
.hist-item-meta { font-size: 0.8rem; color: var(--text-secondary); margin-bottom: 0.5rem; }

.text-green { color: #059669; }
.text-amber { color: #d97706; }
.text-muted { color: var(--text-secondary); }
.text-center { text-align: center; }
.font-mono { font-family: 'Courier New', monospace; }
.num { text-align: right; font-variant-numeric: tabular-nums; }
.scroll-y { max-height: 65vh; overflow-y: auto; }
</style>

<div class="dc-container">

  <div class="dc-topbar">
    <h1><i class="bi bi-truck"></i> Distribución desde Bodega <small>Gestión de inventario en BodegaCentral</small></h1>
  </div>

  <div class="dc-tabs">
    <button class="dc-tab active" data-tab="distribuir" onclick="switchTab('distribuir')"><i class="bi bi-truck"></i> Distribuir</button>
    <button class="dc-tab" data-tab="bodega" onclick="switchTab('bodega')"><i class="bi bi-house-door"></i> Stock en Bodega</button>
    <button class="dc-tab" data-tab="historial" onclick="switchTab('historial')"><i class="bi bi-clock-history"></i> Historial</button>
  </div>

  <!-- ===== TAB: DISTRIBUIR ===== -->
  <div id="tab-distribuir" class="tab-content active">
    <div class="dc-grid-3">
      <!-- Buscador productos -->
      <div class="dc-card">
        <div style="font-size:0.85rem;font-weight:700;color:var(--text-secondary);margin-bottom:0.75rem;"><i class="bi bi-search" style="color:var(--accent-color);"></i> Buscar Producto</div>
        <input type="text" id="buscarProducto" class="search-input" placeholder="Nombre, código o barra..." oninput="buscarProd()">
        <div id="resultadosBusqueda" class="scroll-y" style="margin-top:0.5rem;"></div>
      </div>

      <!-- Info producto y distribución -->
      <div class="dc-card">
        <div style="font-size:0.85rem;font-weight:700;color:var(--text-secondary);margin-bottom:0.75rem;" id="distribTitle"><i class="bi bi-box" style="color:var(--accent-color);"></i> Seleccione un producto</div>
        <div id="distribProductInfo" style="display:none;">
          <div class="dc-stats">
            <div class="dc-stat"><div class="dc-stat-label">Stock Bodega</div><div class="dc-stat-value" id="dStockBodega">0</div></div>
            <div class="dc-stat"><div class="dc-stat-label">Facturado</div><div class="dc-stat-value text-green" id="dStockFact">0</div></div>
            <div class="dc-stat"><div class="dc-stat-label">No Facturado</div><div class="dc-stat-value text-amber" id="dStockNoFact">0</div></div>
          </div>
          <input type="hidden" id="dProductoId" value="">
          <div id="distribSucursales"></div>
          <div style="display:flex;align-items:center;justify-content:space-between;margin-top:1rem;padding-top:1rem;border-top:1px solid var(--border-color);">
            <div><span class="text-muted" style="font-size:0.8rem;">Total a distribuir: </span><span class="dc-stat-value" id="dTotalDistrib" style="font-size:1.25rem;">0</span></div>
            <button class="btn btn-primary" onclick="ejecutarDistribucion()"><i class="bi bi-truck"></i> Distribuir</button>
          </div>
        </div>
        <div id="distribEmpty" style="text-align:center;padding:2rem 0;color:var(--text-secondary);">
          <i class="bi bi-box-seam" style="font-size:2rem;display:block;margin-bottom:0.5rem;"></i>
          Busque un producto para comenzar
        </div>
      </div>
    </div>
  </div>

  <!-- ===== TAB: STOCK EN BODEGA ===== -->
  <div id="tab-bodega" class="tab-content">
    <div class="dc-card">
      <div class="filter-row">
        <input type="text" id="filtroBodega" placeholder="Buscar en bodega..." oninput="cargarBodega()">
        <span class="text-muted" style="font-size:0.8rem;" id="bodegaCount"></span>
      </div>
      <div id="bodegaContent" class="scroll-y"><p class="text-muted text-center" style="padding:2rem;">Cargando...</p></div>
    </div>
  </div>

  <!-- ===== TAB: HISTORIAL ===== -->
  <div id="tab-historial" class="tab-content">
    <div class="dc-card">
      <div class="filter-row">
        <span class="text-muted" style="font-size:0.8rem;" id="historialCount"></span>
        <button class="btn btn-outline btn-sm" onclick="cargarHistorial()"><i class="bi bi-arrow-clockwise"></i> Recargar</button>
      </div>
      <div id="historialContent" class="scroll-y"><p class="text-muted text-center" style="padding:2rem;">Cargando...</p></div>
    </div>
  </div>
</div>

<script src="assets/js/sweetalert2.min.js"></script>
<script>
let sucursales = [];
let productoSeleccionado = null;

async function init() {
    try {
        const r = await fetch('api/distribucion/index.php?action=sucursales');
        sucursales = await r.json().then(d => d.data || d);
    } catch(e) {}
    cargarBodega();
    cargarHistorial();
}
init();

function switchTab(tab) {
    document.querySelectorAll('.dc-tab').forEach(b => b.classList.remove('active'));
    document.querySelector(`.dc-tab[data-tab="${tab}"]`)?.classList.add('active');
    document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
    document.getElementById(`tab-${tab}`)?.classList.add('active');
}

// ===================== BUSQUEDA DE PRODUCTOS =====================
let timeoutBusqueda = null;
function buscarProd() {
    clearTimeout(timeoutBusqueda);
    timeoutBusqueda = setTimeout(async () => {
        const q = document.getElementById('buscarProducto').value.trim();
        if (q.length < 2) { document.getElementById('resultadosBusqueda').innerHTML = '<p class="text-muted text-center" style="font-size:0.8rem;padding:1rem;">Escriba al menos 2 caracteres</p>'; return; }
        try {
            const r = await fetch(`api/distribucion/index.php?action=productos_bodega&q=${encodeURIComponent(q)}`);
            const d = await r.json();
            const prods = d.data || [];
            const cont = document.getElementById('resultadosBusqueda');
            if (!prods.length) { cont.innerHTML = '<p class="text-muted text-center" style="font-size:0.8rem;padding:1rem;">Sin resultados</p>'; return; }
            cont.innerHTML = prods.map(p => `<div class="prod-result ${productoSeleccionado?.producto_id===p.producto_id?'selected':''}" onclick="seleccionarProducto(JSON.parse('${JSON.stringify(p).replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'))">
                <div style="font-size:0.85rem;font-weight:600;color:var(--text-primary);">${p.producto||''}</div>
                <div style="font-size:0.7rem;color:var(--text-secondary);">${p.codigo||''} ${p.categoria?'· '+p.categoria:''} · Stock: <strong>${p.stock_total}</strong> uds</div>
            </div>`).join('');
        } catch(e) {}
    }, 300);
}

function esc(s) {
    if (!s) return '';
    const d = document.createElement('div');
    d.textContent = s;
    return d.innerHTML;
}

function seleccionarProducto(p) {
    productoSeleccionado = p;
    document.getElementById('dProductoId').value = p.producto_id;
    document.getElementById('dStockBodega').textContent = p.stock_total;
    document.getElementById('dStockFact').textContent = p.stock_facturado;
    document.getElementById('dStockNoFact').textContent = p.stock_no_facturado;
    document.getElementById('distribTitle').innerHTML = `<i class="bi bi-box" style="color:var(--accent-color);"></i> ${esc(p.producto)} <span style="font-size:0.75rem;font-weight:400;color:var(--text-secondary);">${p.codigo||''}</span>`;
    document.getElementById('distribProductInfo').style.display = 'block';
    document.getElementById('distribEmpty').style.display = 'none';
    document.getElementById('buscarProducto').value = p.producto;
    document.getElementById('resultadosBusqueda').innerHTML = '';
    renderDistribInputs();
}

function renderDistribInputs() {
    const cont = document.getElementById('distribSucursales');
    const maxStock = productoSeleccionado?.stock_total || 0;
    cont.innerHTML = '<div style="font-size:0.75rem;font-weight:700;text-transform:uppercase;letter-spacing:0.03em;color:var(--text-secondary);margin-bottom:0.75rem;">Distribuir a sucursales</div>';
    let html = '<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:0.75rem;">';
    sucursales.forEach(s => {
        const name = esc(s.nombre) || '';
        html += `<div class="dist-suc-card">
            <label>${name.replace(/^\([^)]*\)\s*/,'')}</label>
            <div style="display:flex;align-items:center;gap:0.5rem;">
                <input type="number" min="0" max="${maxStock}" value="0" class="distrib-cantidad" data-suc="${s.id}" oninput="actualizarTotalDistrib()">
                <span class="text-muted" style="font-size:0.75rem;">uds</span>
            </div>
        </div>`;
    });
    html += '</div>';
    cont.innerHTML = html;
    actualizarTotalDistrib();
}

function actualizarTotalDistrib() {
    let total = 0;
    document.querySelectorAll('.distrib-cantidad').forEach(inp => { total += parseInt(inp.value) || 0; });
    const el = document.getElementById('dTotalDistrib');
    el.textContent = total;
    const max = productoSeleccionado?.stock_total || 0;
    el.style.color = total > max ? '#dc2626' : (total > 0 ? '#059669' : 'var(--text-primary)');
}

async function ejecutarDistribucion() {
    if (!productoSeleccionado) { Swal.fire('Error', 'Seleccione un producto', 'error'); return; }
    const distribucion = [];
    document.querySelectorAll('.distrib-cantidad').forEach(inp => {
        const cant = parseInt(inp.value) || 0;
        if (cant > 0) distribucion.push({sucursal_id: parseInt(inp.dataset.suc), cantidad: cant});
    });
    if (!distribucion.length) { Swal.fire('Error', 'Debe asignar al menos 1 unidad a alguna sucursal', 'error'); return; }
    const total = distribucion.reduce((s, i) => s + i.cantidad, 0);
    if (total > (productoSeleccionado.stock_total || 0)) {
        Swal.fire('Error', `No hay suficiente stock. Disponible: ${productoSeleccionado.stock_total}, solicitado: ${total}`, 'error');
        return;
    }
    try {
        const r = await fetch('api/distribucion/index.php?action=distribuir', {
            method: 'POST', headers: {'Content-Type':'application/json'},
            body: JSON.stringify({producto_id: productoSeleccionado.producto_id, distribucion})
        });
        const res = await r.json();
        if (res.success) {
            Swal.fire('¡Distribuido!', res.message || 'Producto distribuido correctamente', 'success');
            productoSeleccionado = null;
            document.getElementById('distribProductInfo').style.display = 'none';
            document.getElementById('distribEmpty').style.display = 'block';
            document.getElementById('buscarProducto').value = '';
            document.getElementById('resultadosBusqueda').innerHTML = '';
            cargarBodega();
            cargarHistorial();
        } else {
            Swal.fire('Error', res.error, 'error');
        }
    } catch(e) { Swal.fire('Error', e.message, 'error'); }
}

// ===================== STOCK EN BODEGA =====================
async function cargarBodega() {
    const q = document.getElementById('filtroBodega')?.value || '';
    try {
        const url = q ? `api/distribucion/index.php?action=productos_bodega&q=${encodeURIComponent(q)}` : 'api/distribucion/index.php?action=productos_bodega';
        const r = await fetch(url);
        const d = await r.json();
        const prods = d.data || [];
        document.getElementById('bodegaCount').textContent = prods.length + ' productos';
        if (!prods.length) { document.getElementById('bodegaContent').innerHTML = '<p class="text-muted text-center" style="padding:2rem;">Sin productos en bodega</p>'; return; }
        let html = '<table class="dc-data"><thead><tr><th>Producto</th><th class="num">Stock</th><th class="num">Facturado</th><th class="num">No Fact.</th><th class="num">Costo Prom.</th><th class="text-center">Acción</th></tr></thead><tbody>';
        prods.forEach(p => {
            const prodEsc = esc(p.producto||'');
            const codEsc = esc(p.codigo||'');
            const catEsc = esc(p.categoria||'');
            const pJson = JSON.stringify(p).replace(/'/g, "\\'");
            html += `<tr>
                <td><div style="font-weight:600;">${prodEsc}</div><div class="text-muted" style="font-size:0.7rem;">${codEsc} ${catEsc?'· '+catEsc:''}</div></td>
                <td class="num" style="font-weight:700;">${p.stock_total}</td>
                <td class="num text-green">${p.stock_facturado}</td>
                <td class="num text-amber">${p.stock_no_facturado}</td>
                <td class="num text-muted">Q${parseFloat(p.costo_promedio_local||0).toFixed(2)}</td>
                <td class="text-center">
                    <button onclick='irADistribuir(${JSON.stringify(p).replace(/'/g,"\\'")})' class="btn btn-outline btn-sm"><i class="bi bi-truck"></i> Distribuir</button>
                </td></tr>`;
        });
        html += '</tbody></table>';
        document.getElementById('bodegaContent').innerHTML = html;
    } catch(e) { document.getElementById('bodegaContent').innerHTML = `<p style="color:#dc2626;font-size:0.85rem;">${e.message}</p>`; }
}

function irADistribuir(p) {
    switchTab('distribuir');
    seleccionarProducto(p);
}

// ===================== HISTORIAL =====================
async function cargarHistorial() {
    try {
        const r = await fetch('api/distribucion/index.php?action=historial&limit=200');
        const d = await r.json();
        const hist = d.data || [];
        document.getElementById('historialCount').textContent = hist.length + ' distribuciones';
        const cont = document.getElementById('historialContent');
        if (!hist.length) { cont.innerHTML = '<p class="text-muted text-center" style="padding:2rem;">Sin distribuciones aún</p>'; return; }
        let html = '';
        hist.forEach(h => {
            const destEsc = esc(h.destino||'');
            const usrEsc = esc(h.usuario||'');
            html += `<div class="hist-item">
                <div class="hist-item-header">
                    <div><span class="id">#${h.id}</span> <span class="fecha">${h.fecha||''}</span></div>
                    <span class="estado">${h.estado}</span>
                </div>
                <div class="hist-item-meta"><i class="bi bi-arrow-right"></i> ${destEsc} ${h.usuario?'· '+usrEsc:''}</div>
                <table class="dc-data"><thead><tr><th>Producto</th><th class="num">Cantidad</th></tr></thead><tbody>`;
            (h.productos||[]).forEach(p => {
                const prodEsc = esc(p.producto||'');
                const codEsc = esc(p.codigo||'');
                html += `<tr><td>${prodEsc} <span class="text-muted" style="font-size:0.7rem;">${codEsc}</span></td><td class="num" style="font-weight:700;">${p.cantidad} ${p.presentacion||'uds'}</td></tr>`;
            });
            html += `</tbody></table></div>`;
        });
        cont.innerHTML = html;
    } catch(e) { document.getElementById('historialContent').innerHTML = `<p style="color:#dc2626;font-size:0.85rem;">${e.message}</p>`; }
}
</script>
<?php renderFooter(); ?>

