<?php
/**
 * TechShop Perú - Gestión Rápida de Stock (Admin)
 */
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/database.php';
require_once __DIR__ . '/../includes/functions.php';

require_admin();
$db = db();

$mensaje = '';

// Procesar actualización rápida de stock
if ($_SERVER['REQUEST_METHOD'] === 'POST' && csrf_verify()) {
    $prod_id = (int)($_POST['producto_id'] ?? 0);
    $nuevo_stock = (int)($_POST['stock'] ?? 0);
    
    if ($prod_id > 0 && $nuevo_stock >= 0) {
        $stmt = $db->prepare('UPDATE productos SET stock = ? WHERE id = ?');
        if ($stmt->execute([$nuevo_stock, $prod_id])) {
            $msg = 'Stock actualizado correctamente.';
            if ($nuevo_stock > 0) {
                require_once __DIR__ . '/../includes/mail_functions.php';
                $enviados = send_stock_alert_email($prod_id);
                if ($enviados > 0) {
                    $msg .= " Se enviaron {$enviados} alertas por correo a clientes suscritos.";
                }
            }
            set_flash('success', $msg);
        } else {
            set_flash('error', 'Error al actualizar el stock.');
        }
    } else {
        set_flash('error', 'Datos inválidos.');
    }
    redirect('panel-admin-tech/stock.php');
}

// Obtener todos los productos ordenados por stock (menor a mayor)
$stmt = $db->query('
    SELECT p.id, p.nombre, p.sku, p.stock, c.nombre as categoria
    FROM productos p
    JOIN categorias c ON p.categoria_id = c.id
    WHERE p.activo = 1
    ORDER BY p.stock ASC
');
$productos = $stmt->fetchAll();

$page_title = 'Control de Inventario y Stock';
require_once __DIR__ . '/views/layout.php';
?>

<div class="card border-0 shadow-sm rounded-4">
    <div class="card-header bg-white border-0 px-4 pt-4 pb-2 d-flex justify-content-between align-items-center">
        <h5 class="fw-bold mb-0">
            <i class="bi bi-box-seam me-2 text-primary"></i>Gestión Rápida de Stock
        </h5>
    </div>
    
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-light">
                    <tr>
                        <th class="px-4">Producto</th>
                        <th>SKU</th>
                        <th>Categoría</th>
                        <th class="text-center">Stock Actual</th>
                        <th width="200">Actualizar Stock</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($productos as $p): 
                        $badge_class = $p['stock'] == 0 ? 'bg-danger' : ($p['stock'] <= 5 ? 'bg-warning text-dark' : 'bg-success');
                    ?>
                    <tr class="<?= $p['stock'] <= 5 ? 'table-warning' : '' ?>">
                        <td class="px-4 fw-medium">
                            <?= e($p['nombre']) ?>
                            <?php if($p['stock'] <= 5): ?>
                                <i class="bi bi-exclamation-triangle-fill text-danger ms-2" title="Stock bajo"></i>
                            <?php endif; ?>
                        </td>
                        <td class="text-muted small"><?= e($p['sku']) ?></td>
                        <td><span class="badge bg-secondary"><?= e($p['categoria']) ?></span></td>
                        <td class="text-center">
                            <span class="badge <?= $badge_class ?> fs-6"><?= $p['stock'] ?></span>
                        </td>
                        <td>
                            <form action="" method="post" class="d-flex align-items-center gap-2">
                                <input type="hidden" name="csrf_token" value="<?= csrf_token() ?>">
                                <input type="hidden" name="producto_id" value="<?= $p['id'] ?>">
                                <input type="number" name="stock" class="form-control form-control-sm" value="<?= $p['stock'] ?>" min="0" style="width: 80px;" required>
                                <button type="submit" class="btn btn-sm btn-primary py-1"><i class="bi bi-check2"></i> Guardar</button>
                            </form>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
