<?php
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');

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

// Include database connection directly without auth for API access
// Note: In production, you might want to add API key authentication
try {
    include '../includes/db.php';
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Database connection failed: ' . $e->getMessage(),
        'meta' => [
            'generated_at' => date('Y-m-d H:i:s'),
            'api_version' => '1.0'
        ]
    ]);
    exit;
}

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 0); // Don't display errors in JSON response

try {
    $event_id = $_GET['event_id'] ?? null;
    $filter_type = $_GET['type'] ?? 'all'; // all, start_list, summary_table
    $format = $_GET['format'] ?? 'json'; // json, array (for internal use)
    
    if (!$event_id) {
        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)) {
        http_response_code(400);
        echo json_encode(['error' => 'Invalid type filter. Allowed: ' . implode(', ', $valid_types)]);
        exit;
    }

    // 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;
    }

    // Fetch report configurations - using the same query as event_dashboard.php
    $config_stmt = $pdo->prepare("
        SELECT id, name, view_type, heat_number, category, status, display_order, created_at, 
               created_at as updated_at
        FROM result_configurations 
        {$where_clause} AND status = 'active'
        ORDER BY view_type, heat_number, display_order ASC, name ASC
    ");
    $config_stmt->execute($params);
    $report_configurations = $config_stmt->fetchAll(PDO::FETCH_ASSOC);

    // 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']);

    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'
        ]
    ];

    // Return response based on format
    if ($format === 'array') {
        return $response;
    } else {
        echo json_encode($response, JSON_PRETTY_PRINT);
    }

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Database error: ' . $e->getMessage(),
        'meta' => [
            'generated_at' => date('Y-m-d H:i:s'),
            'api_version' => '1.0'
        ]
    ]);
}
?>
