<?php
error_reporting(E_ALL ^ E_NOTICE);
header("Content-Type: application/json; charset=utf-8");

include_once '../conexion.php';
include_once '../clases/TokenValidator.php';

$usuarioId = TokenValidator::validar($conn);

try {
    $body  = file_get_contents("php://input");
    $datos = json_decode($body, true);
    // Espera: [empresa_id, sucursal_id, producto_id, almacen_id?]
    if (!isset($datos[0], $datos[1], $datos[2])) {
        throw new Exception("Parámetros inválidos.");
    }

    $e   = (int)$datos[0];
    $s   = (int)$datos[1];
    $pid = (int)$datos[2];
    $alm = isset($datos[3]) ? (int)$datos[3] : 0;

    $sql = "SELECT * FROM public.get_stock_actual_producto(:e,:s,:p,:a)";
    $st  = $conn->prepare($sql);
    $st->execute([':e'=>$e, ':s'=>$s, ':p'=>$pid, ':a'=>$alm]);

    $row = $st->fetch(PDO::FETCH_ASSOC);
    echo json_encode(["ok"=>true, "data"=>$row ?: null], JSON_UNESCAPED_UNICODE);

} catch (Exception $ex) {
    http_response_code(500);
    echo json_encode(["ok"=>false, "error"=>$ex->getMessage()], JSON_UNESCAPED_UNICODE);
} finally {
    unset($st); $conn = null;
}