<?php
error_reporting(E_ALL ^ E_NOTICE);

header("Access-Control-Allow-Methods: POST");
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);

    if (!is_array($datos) || !isset($datos[0])) {
        throw new Exception("Debe enviar el venta_id.");
    }

    $ventaId = intval($datos[0]);

    $sql = "
        SELECT
            serie,
            COALESCE(plan_venta, '') AS plan_venta,
            COALESCE(modalidad_venta, '') AS modalidad_venta,
            COALESCE(numero_celular, '') AS numero_celular,
            ABS(cantidad) AS salida,
            producto_id,
            movimiento_id,
            operacion,
            almacen_id,
            cuota_equipo,
            COALESCE(fila, 0) AS fila
        FROM public.kardex_serieprod
        WHERE movimiento_id = :venta_id
          AND operacion = 'VTA'
        ORDER BY fila, serie;
    ";

    $stmt = $conn->prepare($sql);
    $stmt->bindValue(':venta_id', $ventaId, PDO::PARAM_INT);
    $stmt->execute();

    echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC), JSON_UNESCAPED_UNICODE);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        "error" => $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
}
?>