<?php
/**
 * ICYLAB OS - Módulo de Stock
 * Index homologado y contenido en pantalla.
 */
require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/permissions.php';
require_once '../../core/database.php';
require_once '../../core/format.php';

require_login();
require_permission('module.stock');

$page_title = 'Stock';
$pdo = db();
$q = isset($_GET['q']) ? trim($_GET['q']) : '';

$sql = "SELECT p.id, p.name, p.sku, p.stock, p.unit, p.price, c.name AS category_name
        FROM products p
        LEFT JOIN product_categories c ON p.category_id = c.id
        WHERE p.is_active = 1";
$params = [];

if ($q !== '') {
    $sql .= " AND (p.name LIKE ? OR p.sku LIKE ? OR REPLACE(REPLACE(p.sku, '.', ''), '-', '') LIKE ?)";
    $params[] = '%' . $q . '%';
    $params[] = '%' . $q . '%';
    $params[] = '%' . preg_replace('/[^0-9a-zA-Z]/', '', $q) . '%';
}

$sql .= " ORDER BY p.name ASC LIMIT 500";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);

$totalSkus = count($products);
$totalStock = 0.0;
$noStock = 0;
foreach ($products as $product) {
    $qty = (float)($product['stock'] ?? 0);
    $totalStock += $qty;
    if ($qty <= 0) $noStock++;
}

require_once '../../layouts/header.php';
require_once '../../layouts/sidebar.php';
?>

<main class="app-main no-scroll-main" id="stock-main">
    <?php require_once '../../layouts/topbar.php'; ?>

    <section class="content">
        <div class="page-header">
            <div class="page-header-content">
                <span class="label">Operación</span>
                <h1>Stock</h1>
                <p class="text-secondary">Inventario operativo por producto, SKU y categoría.</p>
            </div>

            <div class="cluster actions-cluster page-header-actions">
                <a class="btn btn-outline" href="/modules/operations/">
                    <i data-lucide="flask-conical"></i>
                    <span>Producción</span>
                </a>
                <a class="btn btn-primary" href="/modules/products/">
                    <i data-lucide="package-plus"></i>
                    <span>Gestionar productos</span>
                </a>
            </div>
        </div>

        <section class="grid grid-3 mb-4">
            <article class="kpi-card">
                <div class="kpi-label">SKU visibles</div>
                <div class="kpi-value"><?php echo number_format($totalSkus, 0, ',', '.'); ?></div>
                <div class="kpi-subtitle">Según filtros aplicados.</div>
            </article>
            <article class="kpi-card">
                <div class="kpi-label">Unidades</div>
                <div class="kpi-value"><?php echo number_format($totalStock, 0, ',', '.'); ?></div>
                <div class="kpi-subtitle">Stock agregado en productos activos.</div>
            </article>
            <article class="kpi-card">
                <div class="kpi-label">Sin stock</div>
                <div class="kpi-value"><?php echo number_format($noStock, 0, ',', '.'); ?></div>
                <div class="kpi-subtitle">Productos con disponibilidad en cero.</div>
            </article>
        </section>

        <section class="card card-table-container">
            <div class="card-header">
                <div>
                    <h2>Inventario</h2>
                    <p class="text-secondary">Busca en vivo por nombre de producto o SKU.</p>
                </div>
                <form class="filter-bar-container" method="get" action="/modules/stock/" style="min-width:min(360px,100%);">
                    <input class="input" id="stockLiveSearch" name="q" value="<?php echo htmlspecialchars($q, ENT_QUOTES, 'UTF-8'); ?>" type="search" placeholder="Buscar producto o SKU..." autocomplete="off">
                </form>
            </div>

            <div class="table-wrap table-container-scroll stock-list-scroll">
                <table class="table" id="stockTable">
                    <thead>
                        <tr>
                            <th>Producto</th>
                            <th>SKU</th>
                            <th>Categoría</th>
                            <th>Stock</th>
                            <th>Precio</th>
                            <th>Acciones</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($products as $product): ?>
                            <?php
                            $searchText = trim(($product['name'] ?? '') . ' ' . ($product['sku'] ?? '') . ' ' . preg_replace('/[^0-9a-zA-Z]/', '', (string)($product['sku'] ?? '')));
                            $qty = (float)($product['stock'] ?? 0);
                            ?>
                            <tr class="stock-row" data-stock-search="<?php echo htmlspecialchars(strtolower($searchText), ENT_QUOTES, 'UTF-8'); ?>">
                                <td>
                                    <strong><?php echo htmlspecialchars($product['name'] ?? 'Producto sin nombre', ENT_QUOTES, 'UTF-8'); ?></strong>
                                    <div class="text-muted"><?php echo htmlspecialchars($product['unit'] ?? 'unidad', ENT_QUOTES, 'UTF-8'); ?></div>
                                </td>
                                <td><?php echo htmlspecialchars($product['sku'] ?: 'S/S', ENT_QUOTES, 'UTF-8'); ?></td>
                                <td><?php echo htmlspecialchars($product['category_name'] ?: 'Sin categoría', ENT_QUOTES, 'UTF-8'); ?></td>
                                <td><strong><?php echo number_format($qty, 2, ',', '.'); ?></strong></td>
                                <td><?php echo function_exists('money_clp') ? money_clp($product['price'] ?? 0) : '$' . number_format((float)($product['price'] ?? 0), 0, ',', '.'); ?></td>
                                <td>
                                    <div class="row-actions">
                                        <a class="btn btn-sm btn-outline" href="/modules/products/?q=<?php echo urlencode($product['sku'] ?? $product['name'] ?? ''); ?>">
                                            <i data-lucide="external-link"></i>
                                            <span>Ver</span>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (!$products): ?>
                            <tr><td colspan="6" class="text-muted">No hay productos para el filtro aplicado.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </section>
    </section>

    <script>
    (function () {
        var input = document.getElementById('stockLiveSearch');
        var rows = Array.prototype.slice.call(document.querySelectorAll('#stockTable .stock-row'));
        function normalize(value) {
            if (window.ICY_NORMALIZE_SEARCH) return window.ICY_NORMALIZE_SEARCH(value);
            return String(value || '').toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').trim();
        }
        function compact(value) {
            return normalize(value).replace(/[^0-9a-z]/g, '');
        }
        function apply() {
            var raw = input ? input.value : '';
            var query = normalize(raw);
            var compactQuery = compact(raw);
            rows.forEach(function (row) {
                var rawHaystack = row.getAttribute('data-stock-search') || '';
                var haystack = normalize(rawHaystack);
                var compactHaystack = compact(rawHaystack);
                var show = !query || haystack.indexOf(query) !== -1 || (compactQuery.length >= 2 && compactHaystack.indexOf(compactQuery) !== -1);
                row.hidden = !show;
                row.style.display = show ? '' : 'none';
            });
        }
        if (input) {
            input.addEventListener('input', apply, { passive: true });
            apply();
        }
        if (window.lucide) lucide.createIcons();
    })();
    </script>
</main>

<?php require_once '../../layouts/footer.php'; ?>
