<?php
/**
 * Sistema de Conteo Manual de Inventario (Dual DB)
 * 
 * Permite buscar productos con paginación avanzada y registrar conteos físicos de stock
 * en la sucursal seleccionada. Los cambios se guardan automáticamente y se registran 
 * con fecha y hora en tiempo real en ambas bases de datos, sincronizando inventario_sucursal.
 */

// 1. Cargar Configuración de Base de Datos y Conexión Dual
$configPath = file_exists(__DIR__ . '/db_config.php') ? __DIR__ . '/db_config.php' : __DIR__ . '/../db_config.php';
$dualPdoPath = file_exists(__DIR__ . '/dual_pdo.php') ? __DIR__ . '/dual_pdo.php' : __DIR__ . '/../dual_pdo.php';

if (!file_exists($configPath) || !file_exists($dualPdoPath)) {
    die(json_encode([
        'success' => false,
        'error' => 'Error de configuración: No se encontraron los archivos db_config.php o dual_pdo.php.'
    ]));
}

$config = require $configPath;
require_once $dualPdoPath;

// Instanciar la conexión dual
$pdo = getDualConnection($config);

// Auto-creación automática de la tabla de conteo si no existe (Self-healing)
try {
    $createTableSql = "CREATE TABLE IF NOT EXISTS `inventario_conteos_manuales` (
        `id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        `sucursal_id` INT NOT NULL,
        `producto_id` BIGINT UNSIGNED NOT NULL,
        `cantidad` INT NOT NULL DEFAULT 0,
        `fecha_registro` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY `idx_sucursal_producto` (`sucursal_id`, `producto_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;";
    $pdo->exec($createTableSql);
} catch (Exception $e) {
    error_log("Error al auto-crear tabla de conteo: " . $e->getMessage());
}

// Definir nombres de bases de datos para visualización
$db_principal = $config['db1']['dbname'] ?? 'Principal';
$db_secundaria = $config['db2']['dbname'] ?? 'Secundaria';

// Obtener listado de sucursales para el selector
$sucursales = [];
try {
    $sucursales = $pdo->query("SELECT id, nombre FROM sucursales ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $sucursales = [];
}

// 2. Rutas de API internas
$action = $_GET['action'] ?? '';

// API: Buscar productos y traer sus conteos
if ($action === 'search') {
    header('Content-Type: application/json; charset=utf-8');
    
    $sucursalId = intval($_GET['sucursal_id'] ?? 0);
    $q = trim($_GET['q'] ?? '');
    $filter = trim($_GET['filter'] ?? 'all');
    $page = max(1, intval($_GET['page'] ?? 1));
    $limit = max(5, min(100, intval($_GET['limit'] ?? 15)));
    $offset = ($page - 1) * $limit;

    if ($sucursalId <= 0) {
        echo json_encode(['success' => false, 'error' => 'Debe seleccionar una sucursal válida.']);
        exit;
    }

    try {
        $where = [];
        $params = [];

        if (!empty($q)) {
            if ($filter === 'name') {
                $where[] = "(p.NombreComercial LIKE ? OR p.NombreGenerico LIKE ?)";
                $params[] = "%$q%";
                $params[] = "%$q%";
            } elseif ($filter === 'code') {
                $where[] = "(p.CodigoInterno LIKE ? OR p.CodigoBarra LIKE ?)";
                $params[] = "%$q%";
                $params[] = "%$q%";
            } elseif ($filter === 'lab') {
                $where[] = "p.laboratorio LIKE ?";
                $params[] = "%$q%";
            } else {
                $where[] = "(p.NombreComercial LIKE ? OR p.NombreGenerico LIKE ? OR p.CodigoInterno LIKE ? OR p.CodigoBarra LIKE ? OR p.laboratorio LIKE ?)";
                $params[] = "%$q%";
                $params[] = "%$q%";
                $params[] = "%$q%";
                $params[] = "%$q%";
                $params[] = "%$q%";
            }
        }

        $whereSql = !empty($where) ? "WHERE " . implode(" AND ", $where) : "";
        
        $sql = "SELECT SQL_CALC_FOUND_ROWS p.* FROM `productos` p $whereSql ORDER BY p.id DESC LIMIT $offset, $limit";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $productos = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Obtener total de registros
        $total = $pdo->query("SELECT FOUND_ROWS()")->fetchColumn();
        $totalPages = ceil($total / $limit);

        // Preparar consultas para la unidad base y conteo
        $stmtBaseUnit = $pdo->prepare("
            SELECT pr.nombre AS presentacion_nombre 
            FROM `producto_presentaciones` pp
            INNER JOIN `presentaciones` pr ON pp.presentacion_id = pr.id
            WHERE pp.producto_id = ? AND pp.activo = 1
            ORDER BY pp.es_unidad_base DESC, pp.factor_conversion ASC
            LIMIT 1
        ");

        $stmtConteo = $pdo->prepare("
            SELECT cantidad, DATE_FORMAT(fecha_registro, '%d/%m/%Y %H:%i:%s') as fecha_registro_formatted 
            FROM `inventario_conteos_manuales` 
            WHERE sucursal_id = ? AND producto_id = ?
            LIMIT 1
        ");

        foreach ($productos as &$p) {
            // Obtener unidad base
            $stmtBaseUnit->execute([$p['id']]);
            $baseUnit = $stmtBaseUnit->fetch(PDO::FETCH_ASSOC);
            $p['unidad_base'] = $baseUnit ? $baseUnit['presentacion_nombre'] : 'UNIDAD';

            // Obtener conteo existente
            $stmtConteo->execute([$sucursalId, $p['id']]);
            $conteo = $stmtConteo->fetch(PDO::FETCH_ASSOC);
            $p['cantidad_contada'] = $conteo ? intval($conteo['cantidad']) : 0;
            $p['fecha_conteo'] = $conteo ? $conteo['fecha_registro_formatted'] : null;
        }

        echo json_encode([
            'success' => true,
            'data' => $productos,
            'pagination' => [
                'total' => $total,
                'page' => $page,
                'limit' => $limit,
                'total_pages' => $totalPages
            ]
        ]);
        exit;
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        exit;
    }
}

// API: Guardar conteo físico y sincronizar inventario_sucursal
if ($action === 'save_conteo' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json; charset=utf-8');
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    $sucursalId = intval($input['sucursal_id'] ?? 0);
    $productoId = intval($input['producto_id'] ?? 0);
    $cantidad = intval($input['cantidad'] ?? 0);

    if ($sucursalId <= 0 || $productoId <= 0 || $cantidad < 0) {
        echo json_encode(['success' => false, 'error' => 'Datos inválidos para registrar el conteo.']);
        exit;
    }

    try {
        $pdo->beginTransaction();

        // 1. Registrar conteo físico en la tabla de historial/auditoría
        $sql1 = "INSERT INTO `inventario_conteos_manuales` 
                (`sucursal_id`, `producto_id`, `cantidad`) 
                VALUES (?, ?, ?)
                ON DUPLICATE KEY UPDATE 
                `cantidad` = VALUES(`cantidad`)";
        $stmt1 = $pdo->prepare($sql1);
        $stmt1->execute([$sucursalId, $productoId, $cantidad]);

        // 2. Sincronizar el stock activo en inventario_sucursal (usado por el POS y el resto del sistema)
        $sql2 = "INSERT INTO `inventario_sucursal` 
                (`producto_id`, `sucursal_id`, `stock_total`, `stock_facturado`, `stock_no_facturado`) 
                VALUES (?, ?, ?, ?, 0)
                ON DUPLICATE KEY UPDATE 
                `stock_total` = VALUES(`stock_total`),
                `stock_facturado` = VALUES(`stock_facturado`)";
        $stmt2 = $pdo->prepare($sql2);
        $stmt2->execute([$productoId, $sucursalId, $cantidad, $cantidad]);

        $pdo->commit();

        // Obtener la fecha/hora formateada actual para devolverla al cliente
        $stmtDate = $pdo->prepare("SELECT DATE_FORMAT(fecha_registro, '%d/%m/%Y %H:%i:%s') as fecha_registro_formatted FROM `inventario_conteos_manuales` WHERE sucursal_id = ? AND producto_id = ?");
        $stmtDate->execute([$sucursalId, $productoId]);
        $fecha = $stmtDate->fetchColumn() ?: date('d/m/Y H:i:s');

        echo json_encode([
            'success' => true, 
            'message' => 'Conteo y stock de POS actualizados exitosamente.',
            'fecha_conteo' => $fecha
        ]);
        exit;
    } catch (Exception $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        http_response_code(500);
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        exit;
    }
}

// API: Reiniciar/Inicializar todo el inventario a cero
if ($action === 'reset_inventory' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json; charset=utf-8');
    
    try {
        $pdo->beginTransaction();

        // 1. Poner todo el stock a 0 en inventario_sucursal
        $pdo->exec("UPDATE `inventario_sucursal` SET `stock_total` = 0, `stock_facturado` = 0, `stock_no_facturado` = 0");

        // 2. Limpiar el historial de conteos manuales
        $pdo->exec("DELETE FROM `inventario_conteos_manuales`");

        $pdo->commit();

        echo json_encode([
            'success' => true, 
            'message' => 'Inventario inicializado a CERO en ambas bases de datos.'
        ]);
        exit;
    } catch (Exception $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        http_response_code(500);
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Conteo Manual de Inventario</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary: #0b0f19;
            --primary-light: #151f32;
            --accent: #10b981;
            --accent-hover: #059669;
            --surface: rgba(21, 31, 50, 0.85);
            --border: rgba(255, 255, 255, 0.12);
            --text: #ffffff;
            --text-secondary: #cbd5e1;
            --borderless-bg: rgba(15, 23, 42, 0.55);
        }

        body {
            background-color: var(--primary);
            background-image: 
                radial-gradient(circle at 10% 20%, rgba(16, 185, 129, 0.08) 0%, transparent 40%),
                radial-gradient(circle at 90% 80%, rgba(59, 130, 246, 0.05) 0%, transparent 40%);
            color: var(--text);
            font-family: 'Plus Jakarta Sans', sans-serif;
            min-height: 100vh;
        }

        .glass-card {
            background: var(--surface);
            backdrop-filter: blur(20px);
            border: 1px solid var(--border);
            border-radius: 1.25rem;
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
        }

        .search-input {
            background: rgba(15, 23, 42, 0.7) !important;
            border: 1px solid var(--border) !important;
            color: white !important;
            border-radius: 0.75rem !important;
            padding: 0.75rem 1.25rem !important;
            font-weight: 500;
        }

        .search-input:focus {
            border-color: var(--accent) !important;
            box-shadow: 0 0 0 4px rgba(16, 185, 129, 0.25) !important;
        }

        .filter-select {
            background: rgba(15, 23, 42, 0.7) !important;
            border: 1px solid var(--border) !important;
            color: white !important;
            border-radius: 0.75rem !important;
            padding: 0.75rem 1.25rem !important;
            font-weight: 600;
            cursor: pointer;
        }

        .table-custom {
            --bs-table-bg: transparent;
            --bs-table-color: var(--text);
            --bs-table-border-color: var(--border);
            margin-bottom: 0;
        }

        .table-custom th {
            font-weight: 700;
            text-transform: uppercase;
            font-size: 0.8rem;
            letter-spacing: 0.75px;
            color: #94a3b8;
            padding: 1.2rem 1rem;
            background: rgba(15, 23, 42, 0.3);
        }

        .table-custom td {
            padding: 0.8rem 1rem;
            vertical-align: middle;
            border-bottom: 1px solid var(--border);
        }

        .tr-product {
            transition: background-color 0.2s;
        }

        .tr-product:hover {
            background-color: rgba(255, 255, 255, 0.02);
        }

        .pagination-custom .page-link {
            background: rgba(21, 31, 50, 0.7);
            border: 1px solid var(--border);
            color: var(--text-secondary);
            padding: 0.6rem 1rem;
            transition: all 0.2s;
        }

        .pagination-custom .page-item.active .page-link {
            background: var(--accent);
            border-color: var(--accent);
            color: white;
            font-weight: 700;
        }

        .pagination-custom .page-link:hover {
            background: rgba(16, 185, 129, 0.2);
            color: white;
            border-color: var(--accent);
        }

        /* Colores de alto contraste por tipo de dato */
        .color-nombre-comercial {
            color: #ffffff;
            font-weight: 700;
            font-size: 1rem;
        }
        .color-nombre-generico {
            color: #cbd5e1; /* slate-300 */
            font-size: 0.85rem;
        }
        .color-laboratorio {
            color: #fbbf24; /* amber-400 */
            font-weight: 700;
            font-size: 0.775rem;
            text-transform: uppercase;
        }
        .color-codigo-interno {
            color: #38bdf8; /* sky-400 */
            font-weight: 700;
            font-size: 0.875rem;
        }
        .color-codigo-barra {
            color: #e2e8f0; /* slate-200 */
            font-size: 0.8rem;
        }

        /* Caja de conteo */
        .conteo-input {
            background: rgba(15, 23, 42, 0.8) !important;
            border: 1px solid rgba(255, 255, 255, 0.2) !important;
            color: #10b981 !important;
            font-weight: 800 !important;
            font-size: 1.1rem !important;
            text-align: center;
            border-radius: 0.5rem;
            padding: 0.4rem 0.5rem;
            width: 75px;
            transition: all 0.15s;
        }

        .conteo-input:focus {
            border-color: var(--accent) !important;
            box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.3) !important;
            background: #0f172a !important;
            outline: none;
        }

        .add-input {
            background: rgba(15, 23, 42, 0.6) !important;
            border: 1px solid rgba(255, 255, 255, 0.15) !important;
            color: #ffffff !important;
            border-radius: 0.4rem 0 0 0.4rem !important;
            text-align: center;
            font-weight: 700;
            font-size: 0.85rem;
            width: 55px;
        }

        .add-input:focus {
            outline: none;
            border-color: var(--accent) !important;
        }

        .btn-add-conteo {
            background: #10b981;
            color: white;
            border: 1px solid #10b981;
            border-radius: 0 0.4rem 0.4rem 0;
            padding: 0.25rem 0.55rem;
            font-weight: bold;
            transition: all 0.15s;
        }

        .btn-add-conteo:hover {
            background: #059669;
            border-color: #059669;
        }

        .badge-base-unit {
            background: #334155;
            color: white;
            font-weight: 700;
            font-size: 0.75rem;
            padding: 0.35rem 0.65rem;
            border-radius: 0.4rem;
            border: 1px solid rgba(255, 255, 255, 0.15);
            text-transform: uppercase;
        }

        .sucursal-select-card {
            background: rgba(16, 185, 129, 0.08);
            border: 1px solid rgba(16, 185, 129, 0.25);
            border-radius: 1rem;
        }
    </style>
</head>
<body class="py-5">

<div class="container">
    <!-- Header -->
    <div class="glass-card p-4 mb-4 text-center position-relative">
        <div class="position-absolute top-50 end-0 translate-middle-y me-4 d-none d-md-block">
            <button type="button" class="btn btn-outline-danger btn-sm fw-bold px-3 py-2" onclick="confirmResetInventory()">
                <i class="fa-solid fa-rotate-left me-1"></i> Inicializar Cero
            </button>
        </div>
        <h2 class="fw-bold text-white mb-2"><i class="fa-solid fa-list-check text-success me-2"></i> Conteo Manual de Inventario</h2>
        <p class="text-secondary mb-0"><span class="badge bg-success me-1">Dual DB</span> Sincroniza al instante en <code><?= htmlspecialchars($db_principal) ?></code> y <code><?= htmlspecialchars($db_secundaria) ?></code></p>
        <div class="mt-3 d-md-none">
            <button type="button" class="btn btn-outline-danger btn-sm fw-bold w-100" onclick="confirmResetInventory()">
                <i class="fa-solid fa-rotate-left me-1"></i> Inicializar Todo a Cero
            </button>
        </div>
    </div>

    <!-- Selector de Sucursal Obligatorio -->
    <div class="glass-card p-4 mb-4 sucursal-select-card">
        <div class="row align-items-center g-3">
            <div class="col-md-4 text-md-end">
                <h5 class="fw-bold text-white mb-0"><i class="fa-solid fa-store text-success me-2"></i> Seleccione la Sucursal de Trabajo:</h5>
            </div>
            <div class="col-md-6">
                <select id="sucursalSelect" class="form-select filter-select border-success">
                    <option value="" disabled selected>-- Elija la Sucursal para Trabajar --</option>
                    <?php foreach ($sucursales as $s): ?>
                        <option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['nombre']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>
    </div>

    <!-- Zona de Búsqueda (Bloqueada hasta elegir sucursal) -->
    <div class="glass-card p-4 mb-4" id="searchContainer" style="opacity: 0.5; pointer-events: none;">
        <div class="row g-3">
            <div class="col-md-7">
                <input type="text" id="searchInput" class="form-control search-input" placeholder="Escriba para buscar por nombre, código o laboratorio...">
            </div>
            <div class="col-md-3">
                <select id="filterSelect" class="form-select filter-select">
                    <option value="all">🔍 Buscar en Todo</option>
                    <option value="name">📦 Nombre Comercial/Genérico</option>
                    <option value="code">🔑 Código Interno/Barras</option>
                    <option value="lab">🧪 Laboratorio</option>
                </select>
            </div>
            <div class="col-md-2">
                <button id="btnSearch" class="btn btn-success w-100 py-3 rounded-3 fw-bold"><i class="fa-solid fa-magnifying-glass me-2"></i> Buscar</button>
            </div>
        </div>
    </div>

    <!-- Grid / Resultados -->
    <div class="glass-card p-4 mb-4" id="resultsContainer" style="opacity: 0.5; pointer-events: none;">
        <!-- Banner de Sucursal requerida -->
        <div class="alert alert-warning text-center fw-bold py-4 mb-0" id="sucursalWarningAlert">
            <i class="fa-solid fa-triangle-exclamation me-2 fs-5"></i> DEBE SELECCIONAR UNA SUCURSAL EN LA PARTE SUPERIOR PARA COMENZAR EL CONTEO
        </div>

        <div class="table-responsive d-none" id="tableWrapper">
            <table class="table table-custom align-middle">
                <thead>
                    <tr>
                        <th style="width: 15%">Códigos</th>
                        <th style="width: 30%">Producto / Laboratorio</th>
                        <th style="width: 15%">U. Mínima</th>
                        <th style="width: 25%">Conteo Físico</th>
                        <th style="width: 15%" class="text-center">Último Registro</th>
                    </tr>
                </thead>
                <tbody id="productsTableBody">
                    <!-- Dinámico -->
                </tbody>
            </table>
        </div>

        <!-- Paginación -->
        <div class="d-none justify-content-between align-items-center mt-4 flex-wrap gap-3" id="paginationWrapper">
            <div class="text-secondary small" id="paginationInfo">Mostrando 0 de 0 productos</div>
            <nav>
                <ul class="pagination pagination-custom mb-0" id="paginationList">
                    <!-- Dinámico -->
                </ul>
            </nav>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    // Variables globales
    let productsData = []; 
    let currentPage = 1;
    let currentLimit = 15;
    let searchDebounceTimeout = null;

    document.addEventListener('DOMContentLoaded', () => {
        const sucursalSelect = document.getElementById('sucursalSelect');
        
        // Recuperar sucursal desde localStorage si ya existía
        const savedSucursal = localStorage.getItem('active_conteo_sucursal');
        if (savedSucursal) {
            sucursalSelect.value = savedSucursal;
            unlockUI(savedSucursal);
        }

        // Evento de cambio de sucursal
        sucursalSelect.addEventListener('change', (e) => {
            const val = e.target.value;
            localStorage.setItem('active_conteo_sucursal', val);
            unlockUI(val);
        });

        // Búsqueda en tiempo real (debounced)
        document.getElementById('searchInput').addEventListener('input', () => {
            clearTimeout(searchDebounceTimeout);
            searchDebounceTimeout = setTimeout(() => {
                loadProducts(1);
            }, 300);
        });

        document.getElementById('filterSelect').addEventListener('change', () => {
            loadProducts(1);
        });

        document.getElementById('btnSearch').addEventListener('click', () => {
            loadProducts(1);
        });
    });

    // Desbloquear interfaz de conteo
    function unlockUI(sucursalId) {
        if (!sucursalId) return;

        const searchContainer = document.getElementById('searchContainer');
        const resultsContainer = document.getElementById('resultsContainer');
        const sucursalWarningAlert = document.getElementById('sucursalWarningAlert');
        const tableWrapper = document.getElementById('tableWrapper');
        const paginationWrapper = document.getElementById('paginationWrapper');

        searchContainer.style.opacity = '1';
        searchContainer.style.pointerEvents = 'auto';
        resultsContainer.style.opacity = '1';
        resultsContainer.style.pointerEvents = 'auto';

        sucursalWarningAlert.classList.add('d-none');
        tableWrapper.classList.remove('d-none');
        paginationWrapper.classList.remove('d-none');

        loadProducts(1);
    }

    // Cargar catálogo de productos y sus conteos
    async function loadProducts(page = 1) {
        currentPage = page;
        const sucursalId = document.getElementById('sucursalSelect').value;
        const q = document.getElementById('searchInput').value.trim();
        const filter = document.getElementById('filterSelect').value;
        const tbody = document.getElementById('productsTableBody');

        if (!sucursalId) return;

        tbody.innerHTML = `
            <tr>
                <td colspan="5" class="text-center py-5 text-secondary">
                    <div class="spinner-border text-success mb-3" role="status"></div>
                    <div>Buscando stock de productos...</div>
                </td>
            </tr>
        `;

        try {
            const res = await fetch(`?action=search&sucursal_id=${sucursalId}&q=${encodeURIComponent(q)}&filter=${filter}&page=${page}&limit=${currentLimit}`);
            const json = await res.json();

            if (!json.success) {
                tbody.innerHTML = `<tr><td colspan="5" class="text-center text-danger py-4"><i class="fa-solid fa-circle-exclamation me-2"></i> Error: ${json.error}</td></tr>`;
                return;
            }

            productsData = json.data;
            renderProductsTable();
            renderPagination(json.pagination);
        } catch (err) {
            tbody.innerHTML = `<tr><td colspan="5" class="text-center text-danger py-4"><i class="fa-solid fa-circle-exclamation me-2"></i> Error: ${err.message}</td></tr>`;
        }
    }

    // Renderizar cuerpo de la tabla
    function renderProductsTable() {
        const tbody = document.getElementById('productsTableBody');
        tbody.innerHTML = '';

        if (productsData.length === 0) {
            tbody.innerHTML = '<tr><td colspan="5" class="text-center py-5 text-secondary">No se encontraron productos.</td></tr>';
            return;
        }

        productsData.forEach(p => {
            const tr = document.createElement('tr');
            tr.id = `row_${p.id}`;
            tr.className = 'tr-product';

            const cellCodigos = `
                <div class="mb-1"><span class="color-codigo-interno font-monospace">${escapeHtml(p.CodigoInterno || 'S/C')}</span></div>
                <div class="color-codigo-barra font-monospace" style="opacity: 0.7;">${escapeHtml(p.CodigoBarra || '-')}</div>
            `;

            const cellProducto = `
                <div class="color-nombre-comercial mb-1">${escapeHtml(p.NombreComercial)}</div>
                <div class="color-nombre-generico mb-1" style="opacity: 0.7;">${escapeHtml(p.NombreGenerico || '')}</div>
                <div class="color-laboratorio">${escapeHtml(p.laboratorio || '')}</div>
            `;

            const cellBaseUnit = `
                <span class="badge-base-unit">${escapeHtml(p.unidad_base)}</span>
            `;

            const cellConteo = `
                <div class="d-flex align-items-center gap-2">
                    <input type="number" min="0" class="conteo-input" 
                           id="conteo_total_${p.id}" value="${p.cantidad_contada}" 
                           onblur="saveConteo(${p.id}, this.value)"
                           onkeydown="if(event.key === 'Enter') { this.blur(); }">
                    
                    <div class="input-group input-group-sm" style="width: 105px;">
                        <input type="number" min="1" id="add_${p.id}" 
                               class="form-control add-input" placeholder="+ Sumar"
                               onkeydown="if(event.key === 'Enter') { addConteo(${p.id}); }">
                        <button class="btn btn-add-conteo" onclick="addConteo(${p.id})"><i class="fa-solid fa-plus"></i></button>
                    </div>
                </div>
            `;

            const cellFecha = `
                <div class="text-center" id="date_cell_${p.id}">
                    ${p.fecha_conteo ? `<span class="small text-secondary fw-semibold"><i class="fa-solid fa-clock text-success me-1"></i> ${p.fecha_conteo}</span>` : '<span class="text-secondary small italic" style="opacity: 0.5;">No contado</span>'}
                </div>
            `;

            tr.innerHTML = `
                <td>${cellCodigos}</td>
                <td>${cellProducto}</td>
                <td>${cellBaseUnit}</td>
                <td>${cellConteo}</td>
                <td>${cellFecha}</td>
            `;
            tbody.appendChild(tr);
        });
    }

    // Guardar conteo físico total (por blur / Enter)
    async function saveConteo(productId, val) {
        const sucursalId = document.getElementById('sucursalSelect').value;
        if (!sucursalId) return;

        const p = productsData.find(prod => prod.id === productId);
        if (!p) return;

        const qty = parseInt(val);
        if (isNaN(qty) || qty < 0) {
            document.getElementById(`conteo_total_${productId}`).value = p.cantidad_contada;
            return;
        }

        if (p.cantidad_contada === qty) return;

        const oldQty = p.cantidad_contada;
        p.cantidad_contada = qty;

        const success = await persistConteoToServer(productId, qty);
        if (!success) {
            p.cantidad_contada = oldQty;
            document.getElementById(`conteo_total_${productId}`).value = oldQty;
        }
    }

    // Agregar/Sumar al conteo existente
    async function addConteo(productId) {
        const sucursalId = document.getElementById('sucursalSelect').value;
        const addInput = document.getElementById(`add_${productId}`);
        const addQty = parseInt(addInput.value);

        if (isNaN(addQty) || addQty <= 0) return;

        const p = productsData.find(prod => prod.id === productId);
        if (!p) return;

        const newQty = p.cantidad_contada + addQty;
        addInput.value = '';

        p.cantidad_contada = newQty;
        document.getElementById(`conteo_total_${productId}`).value = newQty;

        const success = await persistConteoToServer(productId, newQty);
        if (!success) {
            const oldQty = newQty - addQty;
            p.cantidad_contada = oldQty;
            document.getElementById(`conteo_total_${productId}`).value = oldQty;
        }
    }

    // Persistir conteo a la base de datos y sincronizar con inventario_sucursal
    async function persistConteoToServer(productId, qty) {
        const sucursalId = document.getElementById('sucursalSelect').value;
        const dateCell = document.getElementById(`date_cell_${productId}`);
        
        dateCell.innerHTML = '<span class="text-info small"><i class="fa-solid fa-spinner fa-spin"></i> Guardando...</span>';

        try {
            const res = await fetch('?action=save_conteo', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    sucursal_id: sucursalId,
                    producto_id: productId,
                    cantidad: qty
                })
            });

            const data = await res.json();
            if (data.success) {
                dateCell.innerHTML = `<span class="small text-success fw-bold animate__animated animate__flash"><i class="fa-solid fa-clock me-1"></i> ${data.fecha_conteo}</span>`;
                setTimeout(() => {
                    dateCell.innerHTML = `<span class="small text-secondary fw-semibold"><i class="fa-solid fa-clock text-success me-1"></i> ${data.fecha_conteo}</span>`;
                }, 2000);
                return true;
            } else {
                dateCell.innerHTML = '<span class="text-danger small"><i class="fa-solid fa-circle-exclamation"></i> Error</span>';
                Swal.fire('Error al guardar conteo', data.error || 'Ocurrió un error.', 'error');
                return false;
            }
        } catch (err) {
            dateCell.innerHTML = '<span class="text-danger small"><i class="fa-solid fa-triangle-exclamation"></i> Error Red</span>';
            Swal.fire('Error de red', err.message, 'error');
            return false;
        }
    }

    // Confirmar reinicio del inventario completo a CERO
    function confirmResetInventory() {
        Swal.fire({
            title: '¿Inicializar inventario a CERO?',
            text: "¡Esta acción pondrá en 0 el stock de todos los productos en todas las sucursales y borrará los conteos manuales previos para empezar desde cero!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#ef4444',
            cancelButtonColor: '#64748b',
            confirmButtonText: 'Sí, reiniciar todo a CERO',
            cancelButtonText: 'Cancelar'
        }).then(async (result) => {
            if (result.isConfirmed) {
                try {
                    const res = await fetch('?action=reset_inventory', { method: 'POST' });
                    const data = await res.json();
                    if (data.success) {
                        Swal.fire('¡Inventario en Cero!', data.message, 'success').then(() => {
                            loadProducts(currentPage);
                        });
                    } else {
                        Swal.fire('Error', data.error || 'No se pudo reiniciar.', 'error');
                    }
                } catch (err) {
                    Swal.fire('Error de Red', err.message, 'error');
                }
            }
        });
    }

    // Renderizar paginador
    function renderPagination(info) {
        const infoSpan = document.getElementById('paginationInfo');
        const list = document.getElementById('paginationList');
        list.innerHTML = '';

        const start = (info.page - 1) * info.limit + 1;
        const end = Math.min(info.total, info.page * info.limit);
        infoSpan.textContent = `Mostrando ${info.total > 0 ? start : 0} a ${end} de ${info.total} productos`;

        if (info.total_pages <= 1) return;

        // Botón Anterior
        const prevLi = document.createElement('li');
        prevLi.className = `page-item ${info.page === 1 ? 'disabled' : ''}`;
        prevLi.innerHTML = `<a class="page-link" href="#" onclick="loadProducts(${info.page - 1}); return false;"><i class="fa-solid fa-chevron-left"></i></a>`;
        list.appendChild(prevLi);

        let startPage = Math.max(1, info.page - 2);
        let endPage = Math.min(info.total_pages, startPage + 4);
        if (endPage - startPage < 4) {
            startPage = Math.max(1, endPage - 4);
        }

        for (let i = startPage; i <= endPage; i++) {
            const li = document.createElement('li');
            li.className = `page-item ${info.page === i ? 'active' : ''}`;
            li.innerHTML = `<a class="page-link" href="#" onclick="loadProducts(${i}); return false;">${i}</a>`;
            list.appendChild(li);
        }

        // Botón Siguiente
        const nextLi = document.createElement('li');
        nextLi.className = `page-item ${info.page === info.total_pages ? 'disabled' : ''}`;
        nextLi.innerHTML = `<a class="page-link" href="#" onclick="loadProducts(${info.page + 1}); return false;"><i class="fa-solid fa-chevron-right"></i></a>`;
        list.appendChild(nextLi);
    }

    function escapeHtml(str) {
        if (!str) return '';
        return str
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }
</script>
</body>
</html>
