<?php
// Debug version of reports API
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);

echo "Debug: Starting reports API...\n";

// Set headers first
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

echo "Debug: Headers set...\n";

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    echo "Debug: OPTIONS request handled\n";
    http_response_code(200);
    exit;
}

echo "Debug: Not an OPTIONS request...\n";

try {
    echo "Debug: About to include auth.php...\n";
    include '../includes/auth.php';
    echo "Debug: Auth included...\n";
    
    echo "Debug: About to include db.php...\n";
    include '../includes/db.php';
    echo "Debug: DB included...\n";
    
    $event_id = $_GET['event_id'] ?? null;
    $filter_type = $_GET['type'] ?? 'all';
    $format = $_GET['format'] ?? 'json';
    
    echo "Debug: Parameters - event_id: $event_id, type: $filter_type, format: $format\n";
    
    if (!$event_id) {
        echo "Debug: No event_id provided\n";
        http_response_code(400);
        echo json_encode(['error' => 'Event ID is required']);
        exit;
    }

    // Validate filter type
    $valid_types = ['all', 'start_list', 'summary_table'];
    if (!in_array($filter_type, $valid_types)) {
        echo "Debug: Invalid filter type\n";
        http_response_code(400);
        echo json_encode(['error' => 'Invalid type filter. Allowed: ' . implode(', ', $valid_types)]);
        exit;
    }

    echo "Debug: About to check database connection...\n";
    if (!isset($pdo)) {
        throw new Exception("Database connection not available");
    }
    echo "Debug: Database connection OK...\n";

    // Build query with optional type filter
    $where_clause = "WHERE event_id = ?";
    $params = [$event_id];
    
    if ($filter_type !== 'all') {
        $where_clause .= " AND view_type = ?";
        $params[] = $filter_type;
    }

    echo "Debug: About to prepare database query...\n";
    
    // Check if table exists first
    $table_check = $pdo->query("SHOW TABLES LIKE 'report_configurations'");
    if ($table_check->rowCount() == 0) {
        throw new Exception("Table 'report_configurations' does not exist");
    }
    echo "Debug: Table exists...\n";

    // Fetch report configurations
    $sql = "
        SELECT id, name, view_type, category, heat_number, 
               created_at, updated_at
        FROM report_configurations 
        {$where_clause}
        ORDER BY view_type, name
    ";
    
    echo "Debug: SQL Query: $sql\n";
    echo "Debug: Parameters: " . print_r($params, true) . "\n";
    
    $config_stmt = $pdo->prepare($sql);
    $config_stmt->execute($params);
    $report_configurations = $config_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo "Debug: Found " . count($report_configurations) . " configurations\n";

    // Build response data
    $reports = [];
    $base_url = dirname($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
    $base_api_url = "{$protocol}://{$_SERVER['HTTP_HOST']}" . dirname($_SERVER['REQUEST_URI']);

    echo "Debug: Base API URL: $base_api_url\n";

    foreach ($report_configurations as $config) {
        $report_data = [
            'id' => (int)$config['id'],
            'name' => $config['name'],
            'type' => $config['view_type'],
            'category' => $config['category'],
            'heat_number' => $config['heat_number'] ? (int)$config['heat_number'] : null,
            'heat_badge' => $config['heat_number'] ? "Heat {$config['heat_number']}" : ($config['view_type'] === 'summary_table' ? 'Results' : 'General'),
            'type_info' => [
                'label' => $config['view_type'] === 'start_list' ? 'Start List' : 'Summary Table',
                'icon' => $config['view_type'] === 'start_list' ? 'fa-list-ul' : 'fa-table',
                'color' => $config['view_type'] === 'start_list' ? 'success' : 'info'
            ],
            'created_at' => $config['created_at'],
            'updated_at' => $config['updated_at']
        ];

        // Generate URLs based on report type
        if ($config['view_type'] === 'start_list') {
            $base_params = "event_id={$event_id}&config_id={$config['id']}";
            if ($config['heat_number']) {
                $base_params .= "&heat_number={$config['heat_number']}";
            }
            
            $report_data['urls'] = [
                'pdf' => "{$base_api_url}/start_list_api.php?{$base_params}&format=pdf",
                'html' => "{$base_api_url}/start_list_api.php?{$base_params}&format=html",
                'csv' => "{$base_api_url}/start_list_api.php?{$base_params}&format=csv",
                'json' => "{$base_api_url}/start_list_api.php?{$base_params}&format=json"
            ];
        } else {
            $base_params = "config_id={$config['id']}&config_name=" . urlencode($config['name']);
            
            $report_data['urls'] = [
                'pdf' => "{$base_api_url}/summary_table_api.php?{$base_params}&format=pdf",
                'html' => "{$base_api_url}/summary_table_api.php?{$base_params}&format=html",
                'csv' => "{$base_api_url}/summary_table_api.php?{$base_params}&format=csv",
                'json' => "{$base_api_url}/summary_table_api.php?{$base_params}&format=json"
            ];
        }

        $reports[] = $report_data;
    }

    // Group reports by type for easier consumption
    $grouped_reports = [
        'start_list' => [],
        'summary_table' => []
    ];

    foreach ($reports as $report) {
        $grouped_reports[$report['type']][] = $report;
    }

    // Generate statistics
    $stats = [
        'total_reports' => count($reports),
        'start_list_count' => count($grouped_reports['start_list']),
        'summary_table_count' => count($grouped_reports['summary_table']),
        'filter_applied' => $filter_type,
        'event_id' => (int)$event_id
    ];

    // Prepare response
    $response = [
        'success' => true,
        'event_id' => (int)$event_id,
        'filter_type' => $filter_type,
        'stats' => $stats,
        'reports' => $reports,
        'grouped_reports' => $grouped_reports,
        'meta' => [
            'total_count' => count($reports),
            'has_data' => !empty($reports),
            'generated_at' => date('Y-m-d H:i:s'),
            'api_version' => '1.0'
        ]
    ];

    echo "Debug: Response prepared successfully\n";
    echo "Debug: About to output JSON...\n";

    // Return response based on format
    if ($format === 'array') {
        return $response;
    } else {
        // Clear any debug output for JSON response
        if (ob_get_level()) {
            ob_clean();
        }
        header('Content-Type: application/json');
        echo json_encode($response, JSON_PRETTY_PRINT);
    }

} catch (Exception $e) {
    echo "Debug: Exception caught: " . $e->getMessage() . "\n";
    echo "Debug: Stack trace: " . $e->getTraceAsString() . "\n";
    
    // Clear any output for error response
    if (ob_get_level()) {
        ob_clean();
    }
    
    http_response_code(500);
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'error' => 'Database error: ' . $e->getMessage(),
        'debug_info' => [
            'file' => $e->getFile(),
            'line' => $e->getLine(),
            'trace' => $e->getTraceAsString()
        ],
        'meta' => [
            'generated_at' => date('Y-m-d H:i:s'),
            'api_version' => '1.0'
        ]
    ]);
}
?>
