<?php
require_once __DIR__ . '/../../includes/layout.php';
$version = '20260522';
renderHeader('Administrar Productos', 'productos');
?>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">

<style>
:root {
    --bg-page: var(--background);
    --card-bg: var(--surface);
    --primary: var(--primary);
    --primary-light: var(--primary-light);
    --primary-dark: var(--primary-dark);
    --text: var(--text-primary);
    --text-sec: var(--text-secondary);
    --text-ter: var(--text-muted);
    --border: var(--border-light);
    --border-dark: var(--border-color);
    --success: var(--success);
    --warning: var(--warning);
    --danger: var(--danger);
    --info: var(--info);
    --radius-sm: var(--radius-sm);
    --radius-md: var(--radius);
    --radius-lg: var(--radius-lg);
    --shadow-sm: var(--shadow-sm);
    --shadow-md: var(--shadow);
    --shadow-lg: var(--shadow-md);
}

body { font-family: 'Plus Jakarta Sans', sans-serif; background: var(--bg-page); color: var(--text); }

.page-wrap {
    max-width: 1600px; margin: 0 auto; padding: 1.5rem;
}

/* Top bar */
.top-bar {
    background: var(--card-bg); border-radius: var(--radius-lg);
    padding: 1.25rem 1.5rem; margin-bottom: 1.5rem;
    box-shadow: var(--shadow-sm);
    display: flex; gap: 1rem; align-items: center; flex-wrap: wrap;
    border: 1px solid var(--border-dark);
}
.top-bar h2 {
    font-size: 1.1rem; font-weight: 700; color: var(--primary);
    margin: 0; white-space: nowrap;
}
.top-bar h2 span { color: var(--text-sec); font-weight: 400; }

.search-field {
    flex: 1; min-width: 220px; position: relative;
}
.search-field .icon {
    position: absolute; left: 14px; top: 50%; transform: translateY(-50%);
    color: var(--text-ter); font-size: 1rem; pointer-events: none;
}
.search-field input {
    width: 100%; padding: 0.7rem 1rem 0.7rem 2.6rem;
    border: 1px solid var(--border-dark); border-radius: var(--radius-sm);
    background: var(--surface-elevated); color: var(--text); font-size: 0.9rem;
    outline: none; transition: all 0.2s;
}
.search-field input:focus { border-color: var(--primary-light); box-shadow: var(--focus-ring); }

.lab-filter select {
    padding: 0.7rem 2rem 0.7rem 1rem; border: 1px solid var(--border-dark);
    border-radius: var(--radius-sm); background: var(--surface-elevated); color: var(--text);
    font-size: 0.85rem; outline: none; cursor: pointer; appearance: none;
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%236B7280' stroke-width='2'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
    background-repeat: no-repeat; background-position: right 10px center;
    min-width: 180px;
}
.lab-filter select:focus { border-color: var(--primary-light); box-shadow: var(--focus-ring); }

.stats-badge {
    background: var(--primary); color: white; padding: 0.4rem 1rem;
    border-radius: 20px; font-size: 0.8rem; font-weight: 600;
    white-space: nowrap;
}

/* Card */
.card {
    background: var(--card-bg); border-radius: var(--radius-lg);
    box-shadow: var(--shadow-sm); overflow: hidden;
    border: 1px solid var(--border-dark);
}

/* Table */
.table-wrap { overflow-x: auto; padding: 0; }

table.prod-table {
    width: 100%; border-collapse: collapse; font-size: 0.85rem;
}
.prod-table thead { background: var(--primary); }
.prod-table th {
    color: white; font-weight: 600; font-size: 0.75rem;
    text-transform: uppercase; letter-spacing: 0.04em;
    padding: 0.85rem 0.75rem; text-align: left; white-space: nowrap;
}
.prod-table td {
    padding: 0.7rem 0.75rem; border-bottom: 1px solid var(--border);
    vertical-align: middle; background: var(--card-bg);
}
.prod-table tbody tr:hover td { background: var(--surface-hover); }

.code-stack { line-height: 1.6; }
.code-stack .main { font-weight: 700; font-size: 0.85rem; color: var(--primary); }
.code-stack .sub { font-size: 0.75rem; color: var(--text-sec); }

.prod-name { font-weight: 600; color: var(--text); }

.lab-name { color: var(--text-sec); font-size: 0.85rem; }

/* Presentations */
.pres-grid { display: flex; flex-direction: column; gap: 4px; }
.pres-item {
    display: flex; align-items: center; gap: 6px; font-size: 0.8rem;
    background: var(--surface-elevated); padding: 3px 8px; border-radius: 6px;
    border: 1px solid var(--border);
}
.pres-item .label { font-weight: 600; min-width: 48px; color: var(--text); }
.pres-item .eq { color: var(--text-ter); font-size: 0.7rem; }
.pres-item input {
    width: 52px; padding: 3px 6px; border: 1px solid var(--border-dark);
    border-radius: 6px; font-size: 0.8rem; text-align: center;
    background: var(--card-bg); outline: none; transition: all 0.15s;
    color: var(--text);
}
.pres-item input:focus { border-color: var(--primary-light); box-shadow: 0 0 0 2px rgba(30,58,95,0.1); }
.pres-item input:disabled { background: transparent; border-color: transparent; cursor: default; }
.pres-item .unit { color: var(--text-ter); font-size: 0.65rem; }

/* Checkboxes */
.chk-wrap { text-align: center; }
.chk-wrap input[type="checkbox"] {
    width: 18px; height: 18px; cursor: pointer; accent-color: var(--primary);
    border-radius: 4px;
}

/* Category select */
.cat-select {
    padding: 5px 8px; border: 1px solid var(--border-dark); border-radius: 6px;
    font-size: 0.8rem; background: var(--card-bg); color: var(--text); outline: none;
    max-width: 130px; cursor: pointer;
}
.cat-select:focus { border-color: var(--primary-light); }
.cat-select:disabled { background: transparent; border-color: transparent; cursor: default; padding-left: 0; }

/* Action buttons */
.action-wrap { display: flex; gap: 4px; }
.action-wrap button {
    width: 32px; height: 32px; border: none; border-radius: 8px;
    cursor: pointer; font-size: 0.9rem; display: inline-flex;
    align-items: center; justify-content: center;
    transition: all 0.2s; font-weight: 600;
}
.action-wrap button:hover { transform: translateY(-1px); }
.btn-edit { background: #FEF3C7; color: #D97706; }
.btn-edit:hover { background: #FDE68A; }
.btn-save { background: #DBEAFE; color: #2563EB; }
.btn-save:hover { background: #BFDBFE; }
.btn-cancel { background: #F3F4F6; color: #6B7280; }
.btn-cancel:hover { background: #E5E7EB; }
.btn-delete { background: #FEE2E2; color: #DC2626; }
.btn-delete:hover { background: #FECACA; }
.action-wrap .hide { display: none; }

/* Empty state */
.empty-state { text-align: center; padding: 3rem 1rem; color: var(--text-sec); }
.empty-state .icon { font-size: 2.5rem; margin-bottom: 0.75rem; }
.empty-state p { font-size: 0.9rem; }

/* Pagination */
.pagination-bar {
    display: flex; justify-content: center; align-items: center;
    gap: 6px; padding: 1rem; background: var(--card-bg);
    border-top: 1px solid var(--border);
}
.pagination-bar button {
    min-width: 36px; height: 36px; border: 1px solid var(--border-dark);
    border-radius: 8px; background: var(--card-bg); color: var(--text);
    cursor: pointer; font-size: 0.8rem; font-weight: 600;
    transition: all 0.15s; display: inline-flex; align-items: center; justify-content: center;
}
.pagination-bar button:hover:not(:disabled) { background: var(--primary); color: white; border-color: var(--primary); }
.pagination-bar button:disabled { opacity: 0.35; cursor: default; }
.pagination-bar .page-info {
    font-size: 0.8rem; color: var(--text-sec); margin: 0 8px; font-weight: 500;
}

/* Toast */
.toast {
    position: fixed; bottom: 2rem; right: 2rem;
    padding: 0.85rem 1.5rem; border-radius: var(--radius-md);
    color: white; font-weight: 600; font-size: 0.9rem;
    z-index: 99999; box-shadow: var(--shadow-lg);
    animation: slideUp 0.3s ease; display: flex; align-items: center; gap: 8px;
}
.toast-success { background: var(--success); }
.toast-error { background: var(--danger); }
@keyframes slideUp { from { opacity: 0; transform: translateY(16px); } to { opacity: 1; transform: translateY(0); } }

/* Editing row highlight */
tr.editing td { background: rgba(245, 158, 11, 0.08) !important; }
tr.editing .pres-item { background: var(--card-bg); border-color: var(--border-dark); }
tr.editing .pres-item input:disabled { background: var(--card-bg); border-color: var(--border-dark); }
tr.editing .cat-select:disabled { background: var(--card-bg); border-color: var(--border-dark); cursor: pointer; padding-left: 5px; }

@media (max-width: 1100px) {
    .top-bar { flex-direction: column; align-items: stretch; }
    .top-bar h2 { text-align: center; }
    .search-field { min-width: auto; }
}
</style>

<div class="page-wrap">

    <!-- Top Bar -->
    <div class="top-bar">
        <h2>📦 <span>Administrar Productos</span></h2>
        <div class="search-field">
            <span class="icon">🔍</span>
            <input type="text" id="searchQuery" placeholder="Buscar por c&oacute;digo, nombre o laboratorio..." autofocus>
        </div>
        <div class="lab-filter">
            <select id="filterLaboratorio">
                <option value="">Todos los laboratorios</option>
            </select>
        </div>
        <span id="stats" class="stats-badge">—</span>
    </div>

    <!-- Table Card -->
    <div class="card">
        <div class="table-wrap">
            <table class="prod-table">
                <thead>
                    <tr>
                        <th style="width:110px;">C&oacute;digos</th>
                        <th style="min-width:140px;">Producto</th>
                        <th style="width:110px;">Laboratorio</th>
                        <th style="min-width:200px;">Presentaciones</th>
                        <th style="width:58px;">Exento</th>
                        <th style="width:58px;">Receta</th>
                        <th style="width:115px;">Categor&iacute;a</th>
                        <th style="width:100px;">Acci&oacute;n</th>
                    </tr>
                </thead>
                <tbody id="tbody">
                    <tr><td colspan="8"><div class="empty-state"><div class="icon">⏳</div><p>Cargando productos...</p></div></td></tr>
                </tbody>
            </table>
        </div>
        <div id="pagination" class="pagination-bar"></div>
    </div>

</div>

<script>
let currentPage = 1;
let editingRow = null;

function showToast(msg, type) {
    const existing = document.querySelector('.toast');
    if (existing) existing.remove();
    const t = document.createElement('div');
    t.className = 'toast toast-' + type;
    t.innerHTML = (type === 'success' ? '✓ ' : '✗ ') + msg;
    document.body.appendChild(t);
    setTimeout(() => t.remove(), 3000);
}

async function loadProductos() {
    const query = document.getElementById('searchQuery').value.trim();
    const laboratorio = document.getElementById('filterLaboratorio').value;
    const stats = document.getElementById('stats');
    const tbody = document.getElementById('tbody');
    const pagination = document.getElementById('pagination');

    tbody.innerHTML = '<tr><td colspan="8"><div class="empty-state"><div class="icon">⏳</div><p>Cargando productos...</p></div></td></tr>';

    try {
        const params = new URLSearchParams({ page: currentPage, limit: 50 });
        if (query) params.set('query', query);
        if (laboratorio) params.set('laboratorio', laboratorio);

        const res = await fetch('api/productos/administrar/listar.php?' + params.toString());
        const data = await res.json();

        if (!data.success) {
            tbody.innerHTML = '<tr><td colspan="8"><div class="empty-state"><div class="icon">⚠️</div><p style="color:#dc2626;">Error: ' + (data.message || 'desconocido') + '</p></div></td></tr>';
            return;
        }

        const r = data.data;
        stats.textContent = r.total + ' prod. — Pág. ' + r.page + '/' + r.pages;

        // Populate lab filter only once
        const labSelect = document.getElementById('filterLaboratorio');
        if (labSelect.options.length <= 1 && r.laboratorios) {
            r.laboratorios.forEach(function(lab) {
                const opt = document.createElement('option');
                opt.value = lab;
                opt.textContent = lab;
                labSelect.appendChild(opt);
            });
        }

        if (!r.productos || r.productos.length === 0) {
            tbody.innerHTML = '<tr><td colspan="8"><div class="empty-state"><div class="icon">🔍</div><p>No se encontraron productos con esos criterios.</p></div></td></tr>';
            pagination.innerHTML = '';
            return;
        }

        let html = '';
        r.productos.forEach(function(p) {
            const catOptions = r.categorias.map(function(c) {
                const sel = c.id === p.id_categoria ? 'selected' : '';
                return '<option value="' + c.id + '" ' + sel + '>' + c.nombre + '</option>';
            }).join('');

            let presHtml = '';
            if (p.presentaciones && p.presentaciones.length > 0) {
                p.presentaciones.forEach(function(pr) {
                    presHtml += '<div class="pres-item">' +
                        '<span class="label">' + pr.nombre + '</span>' +
                        '<span class="eq">=</span>' +
                        '<input type="number" class="pres-factor" data-pid="' + pr.id + '" value="' + pr.factor_conversion + '" min="1" disabled>' +
                        '<span class="unit">uds</span>' +
                        '</div>';
                });
            } else {
                presHtml = '<span style="color:var(--text-ter);font-size:0.75rem;padding:4px 0;">Sin presentaciones</span>';
            }

            html += '<tr data-id="' + p.id + '">' +
                '<td><div class="code-stack"><div class="main">' + (p.CodigoInterno || '--') + '</div><div class="sub">' + (p.CodigoBarra || '—') + '</div></div></td>' +
                '<td><div class="prod-name">' + p.NombreComercial + '</div></td>' +
                '<td><div class="lab-name">' + (p.laboratorio || '—') + '</div></td>' +
                '<td><div class="pres-grid">' + presHtml + '</div></td>' +
                '<td class="chk-wrap"><input type="checkbox" class="chk-exento" ' + (p.exento_iva ? 'checked' : '') + ' disabled></td>' +
                '<td class="chk-wrap"><input type="checkbox" class="chk-receta" ' + (p.receta_controlada ? 'checked' : '') + ' disabled></td>' +
                '<td><select class="cat-select" disabled>' + catOptions + '</select></td>' +
                '<td><div class="action-wrap">' +
                '<button class="btn-edit" onclick="editRow(this)" title="Editar">✎</button>' +
                '<button class="btn-save hide" onclick="saveRow(this)" title="Guardar">✓</button>' +
                '<button class="btn-cancel hide" onclick="cancelRow(this)" title="Cancelar">✕</button>' +
                '<button class="btn-delete" onclick="deleteRow(this)" title="Eliminar">🗑</button>' +
                '</div></td>' +
                '</tr>';
        });
        tbody.innerHTML = html;

        // Pagination
        let pHtml = '';
        pHtml += '<button ' + (r.page <= 1 ? 'disabled' : '') + ' onclick="goPage(1)">««</button>';
        pHtml += '<button ' + (r.page <= 1 ? 'disabled' : '') + ' onclick="goPage(' + (r.page - 1) + ')">‹</button>';
        pHtml += '<span class="page-info">' + r.page + ' / ' + r.pages + '</span>';
        pHtml += '<button ' + (r.page >= r.pages ? 'disabled' : '') + ' onclick="goPage(' + (r.page + 1) + ')">›</button>';
        pHtml += '<button ' + (r.page >= r.pages ? 'disabled' : '') + ' onclick="goPage(' + r.pages + ')">»»</button>';
        pagination.innerHTML = pHtml;

    } catch (e) {
        tbody.innerHTML = '<tr><td colspan="8"><div class="empty-state"><div class="icon">⚠️</div><p style="color:#dc2626;">Error de conexi&oacute;n al servidor.</p></div></td></tr>';
    }
}

function goPage(p) {
    currentPage = p;
    loadProductos();
}

function editRow(btn) {
    const tr = btn.closest('tr');
    if (editingRow && editingRow !== tr) cancelRow(editingRow.querySelector('.btn-cancel'));
    editingRow = tr;
    tr.classList.add('editing');

    tr.querySelectorAll('.pres-factor, .chk-exento, .chk-receta, .cat-select').forEach(function(el) {
        el.disabled = false;
    });
    btn.classList.add('hide');
    tr.querySelector('.btn-save').classList.remove('hide');
    tr.querySelector('.btn-cancel').classList.remove('hide');
}

function cancelRow(btn) {
    const tr = btn.closest('tr');
    tr.classList.remove('editing');
    tr.querySelectorAll('.pres-factor, .chk-exento, .chk-receta, .cat-select').forEach(function(el) {
        el.disabled = true;
    });
    tr.querySelector('.btn-edit').classList.remove('hide');
    tr.querySelector('.btn-save').classList.add('hide');
    btn.classList.add('hide');
    editingRow = null;
    loadProductos();
}

async function saveRow(btn) {
    const tr = btn.closest('tr');
    const id = tr.dataset.id;
    const exento = tr.querySelector('.chk-exento').checked ? 1 : 0;
    const receta = tr.querySelector('.chk-receta').checked ? 1 : 0;
    const categoria = tr.querySelector('.cat-select').value;

    btn.textContent = '⏳';
    btn.disabled = true;

    try {
        let ok = true;

        // Save exento_iva
        let r1 = await fetch('api/inventario/productos/actualizar.php', {
            method: 'POST', headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({ id: id, field: 'exento_iva', value: exento })
        });
        let d1 = await r1.json();
        if (!d1.success) { showToast('Error al guardar exento: ' + (d1.message || ''), 'error'); ok = false; }

        if (ok) {
            let r2 = await fetch('api/inventario/productos/actualizar.php', {
                method: 'POST', headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ id: id, field: 'receta_controlada', value: receta })
            });
            let d2 = await r2.json();
            if (!d2.success) { showToast('Error al guardar receta: ' + (d2.message || ''), 'error'); ok = false; }
        }

        if (ok && categoria) {
            let r3 = await fetch('api/inventario/productos/actualizar.php', {
                method: 'POST', headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ id: id, field: 'id_categoria', value: parseInt(categoria) })
            });
            let d3 = await r3.json();
            if (!d3.success) { showToast('Error al guardar categoría: ' + (d3.message || ''), 'error'); ok = false; }
        }

        // Save presentation factors
        if (ok) {
            const factors = tr.querySelectorAll('.pres-factor');
            for (const inp of factors) {
                const pid = inp.dataset.pid;
                const val = parseInt(inp.value) || 1;
                let r4 = await fetch('api/productos/administrar/guardar_presentacion.php', {
                    method: 'POST', headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({ producto_id: parseInt(id), presentacion_id: parseInt(pid), factor_conversion: val })
                });
                let d4 = await r4.json();
                if (!d4.success) { showToast('Error al guardar presentación: ' + (d4.message || ''), 'error'); ok = false; break; }
            }
        }

        if (ok) {
            showToast('Producto actualizado', 'success');
            tr.classList.remove('editing');
            tr.querySelectorAll('.pres-factor, .chk-exento, .chk-receta, .cat-select').forEach(function(el) {
                el.disabled = true;
            });
            tr.querySelector('.btn-edit').classList.remove('hide');
            btn.classList.add('hide');
            tr.querySelector('.btn-cancel').classList.add('hide');
            editingRow = null;
            loadProductos();
        }
    } catch (e) {
        showToast('Error de conexión', 'error');
    }
    btn.textContent = '✓';
    btn.disabled = false;
}

async function deleteRow(btn) {
    if (!confirm('¿Eliminar este producto? Esta acción no se puede deshacer.')) return;
    const tr = btn.closest('tr');
    const id = tr.dataset.id;

    btn.textContent = '⏳';
    btn.disabled = true;
    try {
        const res = await fetch('api/inventario/productos/eliminar.php', {
            method: 'POST', headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({ id: parseInt(id) })
        });
        const data = await res.json();
        if (data.success) {
            showToast('Producto eliminado', 'success');
            loadProductos();
        } else {
            showToast('Error: ' + (data.message || ''), 'error');
            btn.textContent = '🗑';
            btn.disabled = false;
        }
    } catch (e) {
        showToast('Error de conexión', 'error');
        btn.textContent = '🗑';
        btn.disabled = false;
    }
}

// Debounced search
let searchTimeout;
document.getElementById('searchQuery').addEventListener('input', function() {
    clearTimeout(searchTimeout);
    searchTimeout = setTimeout(function() {
        currentPage = 1;
        loadProductos();
    }, 350);
});

document.getElementById('filterLaboratorio').addEventListener('change', function() {
    currentPage = 1;
    loadProductos();
});

document.addEventListener('DOMContentLoaded', loadProductos);
</script>

<?php renderFooter(); ?>

