<?php
// ✅ Errores
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// ✅ CORS
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Content-Type: application/json; charset=utf-8");
header("Access-Control-Max-Age: 86400");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

// ✅ Conexión
require_once(__DIR__ . '/../config.php');
 $mysqli->set_charset("utf8mb4");

 $factura_id = isset($_GET['factura_id']) ? (int)$_GET['factura_id'] : 0;
 $slug_tienda = isset($_GET['slug_tienda']) ? trim($_GET['slug_tienda']) : '';

if ($factura_id <= 0 || $slug_tienda === "") {
    echo json_encode(['success'=>false,'message'=>'factura_id y slug_tienda son requeridos']);
    exit;
}

try {
    // Obtener datos de la factura
    $stmt = $mysqli->prepare("SELECT * FROM facturas WHERE id = ? AND slug_tienda = ?");
    $stmt->bind_param("is", $factura_id, $slug_tienda);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        throw new Exception("Factura no encontrada");
    }
    
    $factura = $result->fetch_assoc();
    $stmt->close();

    // Obtener detalles de la factura
    $stmt = $mysqli->prepare("SELECT fd.*, a.titulo, a.descripcion 
                              FROM factura_detalles fd
                              LEFT JOIN articulos a ON fd.articulo_id = a.id
                              WHERE fd.factura_id = ?");
    $stmt->bind_param("i", $factura_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $detalles = [];
    while ($row = $result->fetch_assoc()) {
        $detalles[] = $row;
    }
    $stmt->close();

    $mysqli->close();

    echo json_encode([
        'success' => true,
        'factura' => $factura,
        'detalles' => $detalles
    ]);
    
} catch (Exception $e) {
    echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
    $mysqli->close();
}