<?php
/**
 * GET /api/inventario/alertas/stock_minimo.php
 */
require_once '../../config/database.php';
require_once '../../includes/helpers.php';

$pdo = getConnection();
$sucursal_id = isset($_GET['sucursal_id']) ? (int)$_GET['sucursal_id'] : 0;

try {
    $params = [];
    $sql = "
        SELECT 
            p.CodigoInterno, p.NombreComercial, 
            i.stock_total, i.stock_minimo,
            (i.stock_minimo - i.stock_total) as faltante,
            s.nombre as sucursal
        FROM inventario_sucursal i
        JOIN productos p ON i.producto_id = p.id
        JOIN sucursales s ON i.sucursal_id = s.id
        WHERE i.stock_minimo > 0 AND i.stock_total <= i.stock_minimo
    ";
    
    if ($sucursal_id > 0) {
        $sql .= " AND i.sucursal_id = ?";
        $params[] = $sucursal_id;
    }
    
    $sql .= " ORDER BY faltante DESC, i.stock_total ASC";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $alertas = $stmt->fetchAll(PDO::FETCH_ASSOC);

    json_success($alertas);

} catch (Exception $e) {
    json_error('Error: ' . $e->getMessage());
}
?>
