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

// ? CORS y Headers
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Content-Type: application/json; charset=utf-8");

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

// ? Conexion
require_once(__DIR__ . '/../config.php');
 $mysqli->set_charset("utf8mb4");

// ? JSON
 $input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
    echo json_encode(['success'=>false,'message'=>'JSON invalido']);
    exit;
}

// --- VALIDACION DE PARAMETROS ---
 $slug_tienda = isset($input['slug_tienda']) ? trim($input['slug_tienda']) : '';
 $busqueda = isset($input['busqueda']) ? trim($input['busqueda']) : '';
 $fecha_inicio = isset($input['fechaInicio']) ? trim($input['fechaInicio']) : null;
 $fecha_fin = isset($input['fechaFin']) ? trim($input['fechaFin']) : null;
 $tipo_registro = isset($input['tipo_registro']) ? trim($input['tipo_registro']) : '';

if (!$slug_tienda) {
    echo json_encode(['success' => false, 'message' => 'El slug de la tienda es requerido.']);
    exit;
}

try {
    // --- CONSTRUCCION DINAMICA DE LA CONSULTA ---
    // Usamos CONVERT para forzar la misma collation en todas las columnas de texto del UNION
    $sql = "
        SELECT * FROM (
            (SELECT 
                CONVERT('factura' USING utf8mb4) COLLATE utf8mb4_unicode_ci AS tipo_registro, 
                id, 
                CONVERT(numero_factura USING utf8mb4) COLLATE utf8mb4_unicode_ci AS numero_factura, 
                fecha, 
                CONVERT(cliente_nombre USING utf8mb4) COLLATE utf8mb4_unicode_ci AS cliente_nombre, 
                total, 
                CONVERT(estado USING utf8mb4) COLLATE utf8mb4_unicode_ci AS estado, 
                CONVERT(cajero USING utf8mb4) COLLATE utf8mb4_unicode_ci AS cajero,
                NULL AS nota_id_relacionada,
                NULL AS historial_id,
                NULL AS nota_credito_id,
                NULL AS reversion_id,
                NULL AS fecha_anulacion,
                NULL AS fecha_reversion,
                NULL AS cajero_anulacion,
                NULL AS cajero_reversion
             FROM facturas
             WHERE slug_tienda = ?)

            UNION ALL

            (SELECT 
                CONVERT('anulacion' USING utf8mb4) COLLATE utf8mb4_unicode_ci AS tipo_registro, 
                id, 
                CONVERT(numero_factura USING utf8mb4) COLLATE utf8mb4_unicode_ci AS numero_factura, 
                fecha_anulacion AS fecha, 
                CONVERT(cliente_nombre USING utf8mb4) COLLATE utf8mb4_unicode_ci AS cliente_nombre, 
                total, 
                CONVERT('cancelada' USING utf8mb4) COLLATE utf8mb4_unicode_ci AS estado, 
                CONVERT(cajero_anulacion USING utf8mb4) COLLATE utf8mb4_unicode_ci AS cajero,
                id AS historial_id,
                NULL AS nota_id_relacionada,
                NULL AS nota_credito_id,
                NULL AS reversion_id,
                fecha_anulacion,
                NULL AS fecha_reversion,
                cajero_anulacion,
                NULL AS cajero_reversion
             FROM historial_facturas_anuladas
             WHERE slug_tienda = ?)

            UNION ALL

            (SELECT 
                CONVERT('nota_credito' USING utf8mb4) COLLATE utf8mb4_unicode_ci AS tipo_registro, 
                nc.id, 
                CONVERT(nc.numero_nota_credito USING utf8mb4) COLLATE utf8mb4_unicode_ci AS numero_factura, 
                nc.fecha, 
                CONVERT(f.cliente_nombre USING utf8mb4) COLLATE utf8mb4_unicode_ci AS cliente_nombre, 
                nc.total, 
                CONVERT(nc.estado USING utf8mb4) COLLATE utf8mb4_unicode_ci AS estado, 
                CONVERT(nc.cajero USING utf8mb4) COLLATE utf8mb4_unicode_ci AS cajero,
                NULL AS historial_id,
                nc.factura_id_relacionada AS nota_id_relacionada,
                nc.id AS nota_credito_id,
                NULL AS reversion_id,
                NULL AS fecha_anulacion,
                NULL AS fecha_reversion,
                NULL AS cajero_anulacion,
                NULL AS cajero_reversion
             FROM notas_credito nc
             JOIN facturas f ON nc.factura_id_relacionada = f.id
             WHERE f.slug_tienda = ?)

            UNION ALL

            (SELECT 
                CONVERT('reversion_nota_credito' USING utf8mb4) COLLATE utf8mb4_unicode_ci AS tipo_registro, 
                r.id AS id, 
                CONVERT(nc.numero_nota_credito USING utf8mb4) COLLATE utf8mb4_unicode_ci AS numero_factura, 
                r.fecha_reversion AS fecha,
                CONVERT(f.cliente_nombre USING utf8mb4) COLLATE utf8mb4_unicode_ci AS cliente_nombre,
                nc.total AS total,
                CONVERT('reversada' USING utf8mb4) COLLATE utf8mb4_unicode_ci AS estado,
                CONVERT(r.cajero_reversion USING utf8mb4) COLLATE utf8mb4_unicode_ci AS cajero,
                NULL AS historial_id,
                NULL AS nota_id_relacionada,
                r.nota_credito_id AS nota_credito_id,
                r.id AS reversion_id,
                NULL AS fecha_anulacion,
                r.fecha_reversion AS fecha_reversion,
                NULL AS cajero_anulacion,
                r.cajero_reversion AS cajero_reversion
             FROM reversiones_notas_credito r
             JOIN notas_credito nc ON r.nota_credito_id = nc.id
             JOIN facturas f ON nc.factura_id_relacionada = f.id
             WHERE f.slug_tienda = ?)
        ) AS reportes_combinados
        WHERE 1=1
    ";

    // --- FILTROS DINAMICOS ---
    $params = [$slug_tienda, $slug_tienda, $slug_tienda, $slug_tienda];
    $types = 'ssss'; // 's' por cada slug_tienda

    if (!empty($tipo_registro)) {
        $sql .= " AND tipo_registro = ?";
        $params[] = $tipo_registro;
        $types .= 's';
    }

    if (!empty($busqueda)) {
        $sql .= " AND (numero_factura LIKE ? OR cliente_nombre LIKE ?)";
        $param_busqueda = '%' . $busqueda . '%';
        $params[] = $param_busqueda;
        $params[] = $param_busqueda;
        $types .= 'ss';
    }

    if (!empty($fecha_inicio)) {
        $sql .= " AND fecha >= ?";
        $params[] = $fecha_inicio;
        $types .= 's';
    }

    if (!empty($fecha_fin)) {
        $sql .= " AND fecha <= ?";
        $params[] = $fecha_fin . ' 23:59:59';
        $types .= 's';
    }

    // --- EJECUCIÓN Y RESPUESTA ---
    $stmt = $mysqli->prepare($sql);
    
    if (!$stmt) {
        throw new Exception("Error al preparar la consulta de reportes: " . $mysqli->error);
    }
    
    if (!empty($params)) {
        $stmt->bind_param($types, ...$params);
    }
    
    if (!$stmt->execute()) {
        throw new Exception("Error al ejecutar la consulta de reportes: " . $stmt->error);
    }
    
    $result = $stmt->get_result();
    $reportes = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    
    echo json_encode([
        'success' => true, 
        'reportes' => $reportes
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
} finally {
    if (isset($mysqli) && $mysqli) { $mysqli->close(); }
}
?>