<?php
/**
 * GET /api/inventario/productos/real_time.php
 * Retorna el inventario en tiempo real, consolidado o detallado por sucursal, con filas distintas para Facturado y No Facturado.
 */
ini_set('display_errors', 0);
error_reporting(E_ALL);
header('Content-Type: application/json; charset=utf-8');

require_once '../../config/database.php';
require_once '../../includes/helpers.php';

$pdo = getDBConnection();

try {
    $query = isset($_GET['query']) ? trim($_GET['query']) : '';
    $sucursal_id = isset($_GET['sucursal_id']) ? (int)$_GET['sucursal_id'] : 0; // 0 = Todas
    $solo_existencias = isset($_GET['solo_existencias']) ? (int)$_GET['solo_existencias'] : 1; // 1 = Solo con existencias
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 15;
    if ($page < 1) $page = 1;
    if ($limit < 1) $limit = 15;
    $offset = ($page - 1) * $limit;

    // 1. Construir filtros de búsqueda
    $whereConditions = ["p.estado = 1"];
    $params = [];

    if (!empty($query)) {
        $whereConditions[] = "(p.CodigoInterno LIKE :query1 OR p.CodigoBarra LIKE :query2 OR p.NombreComercial LIKE :query3 OR p.NombreGenerico LIKE :query4 OR p.laboratorio LIKE :query5)";
        $params[':query1'] = "%{$query}%";
        $params[':query2'] = "%{$query}%";
        $params[':query3'] = "%{$query}%";
        $params[':query4'] = "%{$query}%";
        $params[':query5'] = "%{$query}%";
    }
    $whereClause = implode(" AND ", $whereConditions);

    // 2. Conteo de registros totales (por producto base)
    if ($solo_existencias === 1) {
        if ($sucursal_id === 0) {
            $countSql = "
                SELECT COUNT(DISTINCT p.id) as total 
                FROM productos p
                LEFT JOIN inventario_sucursal s1 ON p.id = s1.producto_id AND s1.sucursal_id = 1
                LEFT JOIN inventario_sucursal s2 ON p.id = s2.producto_id AND s2.sucursal_id = 2
                LEFT JOIN inventario_sucursal s3 ON p.id = s3.producto_id AND s3.sucursal_id = 3
                LEFT JOIN inventario_sucursal s4 ON p.id = s4.producto_id AND s4.sucursal_id = 4
                LEFT JOIN inventario_sucursal s5 ON p.id = s5.producto_id AND s5.sucursal_id = 5
                WHERE {$whereClause}
                  AND (COALESCE(s1.stock_total, 0) + COALESCE(s2.stock_total, 0) + COALESCE(s3.stock_total, 0) + COALESCE(s4.stock_total, 0) + COALESCE(s5.stock_total, 0)) > 0
            ";
        } else {
            $countSql = "
                SELECT COUNT(DISTINCT p.id) as total 
                FROM productos p
                LEFT JOIN inventario_sucursal s ON p.id = s.producto_id AND s.sucursal_id = :sucursal_id
                WHERE {$whereClause}
                  AND COALESCE(s.stock_total, 0) > 0
            ";
        }
    } else {
        $countSql = "SELECT COUNT(*) as total FROM productos p WHERE {$whereClause}";
    }

    $countStmt = $pdo->prepare($countSql);
    if ($solo_existencias === 1 && $sucursal_id > 0) {
        $countStmt->bindValue(':sucursal_id', $sucursal_id, PDO::PARAM_INT);
    }
    foreach ($params as $key => $val) {
        $countStmt->bindValue($key, $val, PDO::PARAM_STR);
    }
    $countStmt->execute();
    $total = (int)$countStmt->fetchColumn();

    // Calcular totales valorizados globales
    $grand_total_stock = 0;
    $grand_total_stock_f = 0;
    $grand_total_stock_nf = 0;
    $grand_total_valorizado = 0.0;
    $grand_total_valorizado_f = 0.0;
    $grand_total_valorizado_nf = 0.0;

    if ($sucursal_id === 0) {
        $totalsSql = "
            SELECT 
                SUM(COALESCE(s1.stock_total, 0) + COALESCE(s2.stock_total, 0) + COALESCE(s3.stock_total, 0) + COALESCE(s4.stock_total, 0) + COALESCE(s5.stock_total, 0)) as total_stock,
                SUM(COALESCE(s1.stock_facturado, 0) + COALESCE(s2.stock_facturado, 0) + COALESCE(s3.stock_facturado, 0) + COALESCE(s4.stock_facturado, 0) + COALESCE(s5.stock_facturado, 0)) as total_stock_f,
                SUM(COALESCE(s1.stock_no_facturado, 0) + COALESCE(s2.stock_no_facturado, 0) + COALESCE(s3.stock_no_facturado, 0) + COALESCE(s4.stock_no_facturado, 0) + COALESCE(s5.stock_no_facturado, 0)) as total_stock_nf,
                
                SUM((COALESCE(s1.stock_total, 0) + COALESCE(s2.stock_total, 0) + COALESCE(s3.stock_total, 0) + COALESCE(s4.stock_total, 0) + COALESCE(s5.stock_total, 0)) * COALESCE(pcp.costo_promedio_unidad_base, 0)) as total_valorizado,
                SUM((COALESCE(s1.stock_facturado, 0) + COALESCE(s2.stock_facturado, 0) + COALESCE(s3.stock_facturado, 0) + COALESCE(s4.stock_facturado, 0) + COALESCE(s5.stock_facturado, 0)) * COALESCE(pcp.costo_promedio_unidad_base, 0)) as total_valorizado_f,
                SUM((COALESCE(s1.stock_no_facturado, 0) + COALESCE(s2.stock_no_facturado, 0) + COALESCE(s3.stock_no_facturado, 0) + COALESCE(s4.stock_no_facturado, 0) + COALESCE(s5.stock_no_facturado, 0)) * COALESCE(pcp.costo_promedio_unidad_base, 0)) as total_valorizado_nf
            FROM productos p
            LEFT JOIN productos_costo_promedio pcp ON p.id = pcp.producto_id
            LEFT JOIN inventario_sucursal s1 ON p.id = s1.producto_id AND s1.sucursal_id = 1
            LEFT JOIN inventario_sucursal s2 ON p.id = s2.producto_id AND s2.sucursal_id = 2
            LEFT JOIN inventario_sucursal s3 ON p.id = s3.producto_id AND s3.sucursal_id = 3
            LEFT JOIN inventario_sucursal s4 ON p.id = s4.producto_id AND s4.sucursal_id = 4
            LEFT JOIN inventario_sucursal s5 ON p.id = s5.producto_id AND s5.sucursal_id = 5
            WHERE {$whereClause}
        ";
        $totalsStmt = $pdo->prepare($totalsSql);
        foreach ($params as $key => $val) {
            $totalsStmt->bindValue($key, $val, PDO::PARAM_STR);
        }
        $totalsStmt->execute();
        $totalsRow = $totalsStmt->fetch(PDO::FETCH_ASSOC);
        if ($totalsRow) {
            $grand_total_stock = (int)$totalsRow['total_stock'];
            $grand_total_stock_f = (int)$totalsRow['total_stock_f'];
            $grand_total_stock_nf = (int)$totalsRow['total_stock_nf'];
            $grand_total_valorizado = (float)$totalsRow['total_valorizado'];
            $grand_total_valorizado_f = (float)$totalsRow['total_valorizado_f'];
            $grand_total_valorizado_nf = (float)$totalsRow['total_valorizado_nf'];
        }
    } else {
        $totalsSql = "
            SELECT 
                SUM(COALESCE(s.stock_total, 0)) as total_stock,
                SUM(COALESCE(s.stock_facturado, 0)) as total_stock_f,
                SUM(COALESCE(s.stock_no_facturado, 0)) as total_stock_nf,
                
                SUM(COALESCE(s.stock_total, 0) * COALESCE(s.costo_promedio_local, pcp.costo_promedio_unidad_base, 0)) as total_valorizado,
                SUM(COALESCE(s.stock_facturado, 0) * COALESCE(s.costo_promedio_local, pcp.costo_promedio_unidad_base, 0)) as total_valorizado_f,
                SUM(COALESCE(s.stock_no_facturado, 0) * COALESCE(s.costo_promedio_local, pcp.costo_promedio_unidad_base, 0)) as total_valorizado_nf
            FROM productos p
            LEFT JOIN productos_costo_promedio pcp ON p.id = pcp.producto_id
            LEFT JOIN inventario_sucursal s ON p.id = s.producto_id AND s.sucursal_id = :sucursal_id
            WHERE {$whereClause}
        ";
        $totalsStmt = $pdo->prepare($totalsSql);
        $totalsStmt->bindValue(':sucursal_id', $sucursal_id, PDO::PARAM_INT);
        foreach ($params as $key => $val) {
            $totalsStmt->bindValue($key, $val, PDO::PARAM_STR);
        }
        $totalsStmt->execute();
        $totalsRow = $totalsStmt->fetch(PDO::FETCH_ASSOC);
        if ($totalsRow) {
            $grand_total_stock = (int)$totalsRow['total_stock'];
            $grand_total_stock_f = (int)$totalsRow['total_stock_f'];
            $grand_total_stock_nf = (int)$totalsRow['total_stock_nf'];
            $grand_total_valorizado = (float)$totalsRow['total_valorizado'];
            $grand_total_valorizado_f = (float)$totalsRow['total_valorizado_f'];
            $grand_total_valorizado_nf = (float)$totalsRow['total_valorizado_nf'];
        }
    }

    // 3. Ejecutar consulta de datos según el filtro de sucursal
    $products = [];
    if ($sucursal_id === 0) {
        // Vista Consolidada (Todas las sucursales principales 1 a 5)
        $sql = "
            SELECT 
                p.id,
                COALESCE(p.CodigoInterno, '') as codigo,
                COALESCE(p.CodigoBarra, '') as codigo_barra,
                COALESCE(p.NombreComercial, 'Sin Nombre') as nombre,
                COALESCE(p.NombreGenerico, '') as nombre_generico,
                COALESCE(p.laboratorio, 'Genérico') as laboratorio,
                COALESCE(pcp.costo_promedio_unidad_base, 0) as costo_promedio,
                
                COALESCE(s1.stock_total, 0) as stock_suc_1,
                COALESCE(s1.stock_facturado, 0) as stock_f_suc_1,
                COALESCE(s1.stock_no_facturado, 0) as stock_nf_suc_1,
                s1.last_updated as last_updated_suc_1,
                
                COALESCE(s2.stock_total, 0) as stock_suc_2,
                COALESCE(s2.stock_facturado, 0) as stock_f_suc_2,
                COALESCE(s2.stock_no_facturado, 0) as stock_nf_suc_2,
                s2.last_updated as last_updated_suc_2,
                
                COALESCE(s3.stock_total, 0) as stock_suc_3,
                COALESCE(s3.stock_facturado, 0) as stock_f_suc_3,
                COALESCE(s3.stock_no_facturado, 0) as stock_nf_suc_3,
                s3.last_updated as last_updated_suc_3,
                
                COALESCE(s4.stock_total, 0) as stock_suc_4,
                COALESCE(s4.stock_facturado, 0) as stock_f_suc_4,
                COALESCE(s4.stock_no_facturado, 0) as stock_nf_suc_4,
                s4.last_updated as last_updated_suc_4,
                
                COALESCE(s5.stock_total, 0) as stock_suc_5,
                COALESCE(s5.stock_facturado, 0) as stock_f_suc_5,
                COALESCE(s5.stock_no_facturado, 0) as stock_nf_suc_5,
                s5.last_updated as last_updated_suc_5
            FROM productos p
            LEFT JOIN productos_costo_promedio pcp ON p.id = pcp.producto_id
            LEFT JOIN inventario_sucursal s1 ON p.id = s1.producto_id AND s1.sucursal_id = 1
            LEFT JOIN inventario_sucursal s2 ON p.id = s2.producto_id AND s2.sucursal_id = 2
            LEFT JOIN inventario_sucursal s3 ON p.id = s3.producto_id AND s3.sucursal_id = 3
            LEFT JOIN inventario_sucursal s4 ON p.id = s4.producto_id AND s4.sucursal_id = 4
            LEFT JOIN inventario_sucursal s5 ON p.id = s5.producto_id AND s5.sucursal_id = 5
            WHERE {$whereClause}
        ";
        if ($solo_existencias === 1) {
            $sql .= " AND (COALESCE(s1.stock_total, 0) + COALESCE(s2.stock_total, 0) + COALESCE(s3.stock_total, 0) + COALESCE(s4.stock_total, 0) + COALESCE(s5.stock_total, 0)) > 0";
        }
        $sql .= "
            ORDER BY p.NombreComercial ASC
            LIMIT :limit OFFSET :offset
        ";
        
        $stmt = $pdo->prepare($sql);
        $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
        $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
        foreach ($params as $key => $val) {
            $stmt->bindValue($key, $val, PDO::PARAM_STR);
        }
        $stmt->execute();
        $products = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Obtener ids de productos cargados y consultar sus vencimientos en todas las sucursales
        $productIds = array_column($products, 'id');
        $expirations = [];
        if (!empty($productIds)) {
            $inClause = implode(',', array_fill(0, count($productIds), '?'));
            $sqlExp = "
                SELECT 
                    cd.producto_id, 
                    cd.fecha_vencimiento,
                    SUM(cd.cantidad_unidades_base) as cantidad,
                    cd.facturado,
                    suc.nombre as sucursal_nombre
                FROM compras_detalle cd
                JOIN compras c ON cd.compra_id = c.id
                JOIN inventario_movimientos m ON m.referencia_id = c.id AND m.producto_id = cd.producto_id
                JOIN sucursales suc ON m.sucursal_id = suc.id
                WHERE cd.producto_id IN ($inClause)
                  AND cd.fecha_vencimiento IS NOT NULL 
                  AND cd.fecha_vencimiento != '0000-00-00'
                GROUP BY cd.producto_id, cd.fecha_vencimiento, cd.facturado, suc.nombre
                ORDER BY cd.fecha_vencimiento ASC
            ";
            $stmtExp = $pdo->prepare($sqlExp);
            $stmtExp->execute($productIds);
            while ($rowExp = $stmtExp->fetch(PDO::FETCH_ASSOC)) {
                $type = $rowExp['facturado'] ? 'facturado' : 'no_facturado';
                $expirations[$rowExp['producto_id']][$type][] = [
                    'fecha' => $rowExp['fecha_vencimiento'],
                    'cantidad' => (int)$rowExp['cantidad'],
                    'sucursal_nombre' => $rowExp['sucursal_nombre']
                ];
            }
        }

        // Mapear existencias y costo
        foreach ($products as &$prod) {
            $prodId = (int)$prod['id'];
            $prod['vencimientos'] = isset($expirations[$prodId]) ? $expirations[$prodId] : [];

            $prod['stock_suc_1'] = (int)$prod['stock_suc_1'];
            $prod['stock_f_suc_1'] = (int)$prod['stock_f_suc_1'];
            $prod['stock_nf_suc_1'] = (int)$prod['stock_nf_suc_1'];
            
            $prod['stock_suc_2'] = (int)$prod['stock_suc_2'];
            $prod['stock_f_suc_2'] = (int)$prod['stock_f_suc_2'];
            $prod['stock_nf_suc_2'] = (int)$prod['stock_nf_suc_2'];
            
            $prod['stock_suc_3'] = (int)$prod['stock_suc_3'];
            $prod['stock_f_suc_3'] = (int)$prod['stock_f_suc_3'];
            $prod['stock_nf_suc_3'] = (int)$prod['stock_nf_suc_3'];
            
            $prod['stock_suc_4'] = (int)$prod['stock_suc_4'];
            $prod['stock_f_suc_4'] = (int)$prod['stock_f_suc_4'];
            $prod['stock_nf_suc_4'] = (int)$prod['stock_nf_suc_4'];
            
            $prod['stock_suc_5'] = (int)$prod['stock_suc_5'];
            $prod['stock_f_suc_5'] = (int)$prod['stock_f_suc_5'];
            $prod['stock_nf_suc_5'] = (int)$prod['stock_nf_suc_5'];

            $prod['stock_total_general'] = $prod['stock_suc_1'] + $prod['stock_suc_2'] + $prod['stock_suc_3'] + $prod['stock_suc_4'] + $prod['stock_suc_5'];
            $prod['stock_f_general'] = $prod['stock_f_suc_1'] + $prod['stock_f_suc_2'] + $prod['stock_f_suc_3'] + $prod['stock_f_suc_4'] + $prod['stock_f_suc_5'];
            $prod['stock_nf_general'] = $prod['stock_nf_suc_1'] + $prod['stock_nf_suc_2'] + $prod['stock_nf_suc_3'] + $prod['stock_nf_suc_4'] + $prod['stock_nf_suc_5'];

            $prod['costo_promedio'] = (float)$prod['costo_promedio'];
            $prod['valorizado_total'] = $prod['stock_total_general'] * $prod['costo_promedio'];

            // Calcular fecha de registro como la última modificación de cualquier sucursal
            $dates = array_filter([
                $prod['last_updated_suc_1'],
                $prod['last_updated_suc_2'],
                $prod['last_updated_suc_3'],
                $prod['last_updated_suc_4'],
                $prod['last_updated_suc_5']
            ], function($d) {
                return !empty($d) && $d !== '0000-00-00 00:00:00';
            });
            $prod['fecha_registro'] = !empty($dates) ? max($dates) : null;
        }
    } else {
        // Vista para Sucursal Específica
        $sql = "
            SELECT 
                p.id,
                COALESCE(p.CodigoInterno, '') as codigo,
                COALESCE(p.CodigoBarra, '') as codigo_barra,
                COALESCE(p.NombreComercial, 'Sin Nombre') as nombre,
                COALESCE(p.NombreGenerico, '') as nombre_generico,
                COALESCE(p.laboratorio, 'Genérico') as laboratorio,
                COALESCE(s.costo_promedio_local, pcp.costo_promedio_unidad_base, 0) as costo_promedio,
                COALESCE(s.stock_total, 0) as stock_total,
                COALESCE(s.stock_facturado, 0) as stock_facturado,
                COALESCE(s.stock_no_facturado, 0) as stock_no_facturado,
                s.last_updated as fecha_registro
            FROM productos p
            LEFT JOIN productos_costo_promedio pcp ON p.id = pcp.producto_id
            LEFT JOIN inventario_sucursal s ON p.id = s.producto_id AND s.sucursal_id = :sucursal_id
            WHERE {$whereClause}
        ";
        if ($solo_existencias === 1) {
            $sql .= " AND COALESCE(s.stock_total, 0) > 0";
        }
        $sql .= "
            ORDER BY p.NombreComercial ASC
            LIMIT :limit OFFSET :offset
        ";

        $stmt = $pdo->prepare($sql);
        $stmt->bindValue(':sucursal_id', $sucursal_id, PDO::PARAM_INT);
        $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
        $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
        foreach ($params as $key => $val) {
            $stmt->bindValue($key, $val, PDO::PARAM_STR);
        }
        $stmt->execute();
        $products = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Obtener ids de productos cargados
        $productIds = array_column($products, 'id');
        $expirations = [];

        if (!empty($productIds)) {
            $inClause = implode(',', array_fill(0, count($productIds), '?'));
            
            // Buscar fechas de vencimiento ingresadas para estos productos en esta sucursal (trayendo flag facturado)
            $sqlExp = "
                SELECT 
                    cd.producto_id, 
                    cd.fecha_vencimiento,
                    SUM(cd.cantidad_unidades_base) as cantidad,
                    cd.facturado
                FROM compras_detalle cd
                JOIN compras c ON cd.compra_id = c.id
                JOIN inventario_movimientos m ON m.referencia_id = c.id AND m.producto_id = cd.producto_id
                WHERE m.sucursal_id = ? 
                  AND cd.producto_id IN ($inClause)
                  AND cd.fecha_vencimiento IS NOT NULL 
                  AND cd.fecha_vencimiento != '0000-00-00'
                GROUP BY cd.producto_id, cd.fecha_vencimiento, cd.facturado
                ORDER BY cd.fecha_vencimiento ASC
            ";
            
            $stmtExp = $pdo->prepare($sqlExp);
            $paramsExp = array_merge([$sucursal_id], $productIds);
            $stmtExp->execute($paramsExp);
            while ($rowExp = $stmtExp->fetch(PDO::FETCH_ASSOC)) {
                $type = $rowExp['facturado'] ? 'facturado' : 'no_facturado';
                $expirations[$rowExp['producto_id']][$type][] = [
                    'fecha' => $rowExp['fecha_vencimiento'],
                    'cantidad' => (int)$rowExp['cantidad']
                ];
            }
        }

        // Mapear existencias, costo y fechas de vencimiento
        foreach ($products as &$prod) {
            $prodId = (int)$prod['id'];
            $prod['stock_total'] = (int)$prod['stock_total'];
            $prod['stock_facturado'] = (int)$prod['stock_facturado'];
            $prod['stock_no_facturado'] = (int)$prod['stock_no_facturado'];
            $prod['costo_promedio'] = (float)$prod['costo_promedio'];
            $prod['valorizado_total'] = $prod['stock_total'] * $prod['costo_promedio'];
            $prod['vencimientos'] = isset($expirations[$prodId]) ? $expirations[$prodId] : [];
        }
    }

    // 4. Dividir productos en filas separadas para Facturado y No Facturado
    $splitProducts = [];
    foreach ($products as $prod) {
        $hasF = false;
        $hasNf = false;
        
        if ($sucursal_id === 0) {
            $hasF = ($prod['stock_f_general'] > 0);
            $hasNf = ($prod['stock_nf_general'] > 0);
        } else {
            $hasF = ($prod['stock_facturado'] > 0);
            $hasNf = ($prod['stock_no_facturado'] > 0);
        }
        
        // Fila para Facturado
        if ($hasF) {
            $fProd = $prod;
            $fProd['tipo_inventario'] = 'facturado';
            if ($sucursal_id === 0) {
                $fProd['stock_suc_1'] = $prod['stock_f_suc_1'];
                $fProd['stock_suc_2'] = $prod['stock_f_suc_2'];
                $fProd['stock_suc_3'] = $prod['stock_f_suc_3'];
                $fProd['stock_suc_4'] = $prod['stock_f_suc_4'];
                $fProd['stock_suc_5'] = $prod['stock_f_suc_5'];
                $fProd['stock_total_general'] = $prod['stock_f_general'];
                $fProd['valorizado_total'] = $fProd['stock_total_general'] * $fProd['costo_promedio'];
                $fProd['vencimientos'] = isset($prod['vencimientos']['facturado']) ? $prod['vencimientos']['facturado'] : [];
            } else {
                $fProd['stock_total'] = $prod['stock_facturado'];
                $fProd['valorizado_total'] = $fProd['stock_total'] * $fProd['costo_promedio'];
                $fProd['vencimientos'] = isset($prod['vencimientos']['facturado']) ? $prod['vencimientos']['facturado'] : [];
            }
            $splitProducts[] = $fProd;
        }

        // Fila para No Facturado
        if ($hasNf) {
            $nfProd = $prod;
            $nfProd['tipo_inventario'] = 'no_facturado';
            if ($sucursal_id === 0) {
                $nfProd['stock_suc_1'] = $prod['stock_nf_suc_1'];
                $nfProd['stock_suc_2'] = $prod['stock_nf_suc_2'];
                $nfProd['stock_suc_3'] = $prod['stock_nf_suc_3'];
                $nfProd['stock_suc_4'] = $prod['stock_nf_suc_4'];
                $nfProd['stock_suc_5'] = $prod['stock_nf_suc_5'];
                $nfProd['stock_total_general'] = $prod['stock_nf_general'];
                $nfProd['valorizado_total'] = $nfProd['stock_total_general'] * $nfProd['costo_promedio'];
                $nfProd['vencimientos'] = isset($prod['vencimientos']['no_facturado']) ? $prod['vencimientos']['no_facturado'] : [];
            } else {
                $nfProd['stock_total'] = $prod['stock_no_facturado'];
                $nfProd['valorizado_total'] = $nfProd['stock_total'] * $nfProd['costo_promedio'];
                $nfProd['vencimientos'] = isset($prod['vencimientos']['no_facturado']) ? $prod['vencimientos']['no_facturado'] : [];
            }
            $splitProducts[] = $nfProd;
        }

        // Fila por defecto si no hay existencias en ninguna categoría (para mostrar el producto con stock 0)
        if (!$hasF && !$hasNf) {
            $fProd = $prod;
            $fProd['tipo_inventario'] = 'facturado';
            if ($sucursal_id === 0) {
                $fProd['stock_suc_1'] = 0;
                $fProd['stock_suc_2'] = 0;
                $fProd['stock_suc_3'] = 0;
                $fProd['stock_suc_4'] = 0;
                $fProd['stock_suc_5'] = 0;
                $fProd['stock_total_general'] = 0;
                $fProd['valorizado_total'] = 0.0;
                $fProd['vencimientos'] = [];
            } else {
                $fProd['stock_total'] = 0;
                $fProd['valorizado_total'] = 0.0;
                $fProd['vencimientos'] = [];
            }
            $splitProducts[] = $fProd;
        }
    }

    json_success([
        'products' => $splitProducts,
        'total' => $total,
        'grand_total_stock' => $grand_total_stock,
        'grand_total_stock_f' => $grand_total_stock_f,
        'grand_total_stock_nf' => $grand_total_stock_nf,
        'grand_total_valorizado' => $grand_total_valorizado,
        'grand_total_valorizado_f' => $grand_total_valorizado_f,
        'grand_total_valorizado_nf' => $grand_total_valorizado_nf,
        'page' => $page,
        'limit' => $limit,
        'pages' => ceil($total / $limit)
    ], 'Inventario en tiempo real obtenido correctamente');

} catch (Exception $e) {
    json_error("Error del servidor: " . $e->getMessage(), 500);
}
