<?php
/**
 * API: Reimprimir Factura FEL Guardada
 * Adaptado para RENOVADO2026 (MySQLi)
 */

header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../../config/db_connection.php';

try {
    $venta_id = isset($_GET['venta_id']) ? (int)$_GET['venta_id'] : 0;
    if (!$venta_id) {
        throw new Exception("ID de venta inválido.");
    }

    $stmt = $conn->prepare("SELECT datos_json FROM fel_facturas WHERE venta_id = ? ORDER BY id ASC");
    $stmt->bind_param("i", $venta_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $facturas = [];
    while ($row = $result->fetch_assoc()) {
        $facturas[] = json_decode($row['datos_json'], true);
    }
    $stmt->close();

    if (count($facturas) === 0) {
        throw new Exception("Esta venta no tiene facturas electrónicas guardadas para re-imprimir.");
    }

    echo json_encode(['success' => true, 'facturas' => $facturas], JSON_UNESCAPED_UNICODE);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()], JSON_UNESCAPED_UNICODE);
}

$conn->close();
?>
