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

try {
    $event_id = $_GET['event_id'] ?? null;
    $filter_type = $_GET['type'] ?? 'all';
    
    if (!$event_id) {
        http_response_code(400);
        echo json_encode(['error' => 'Event ID is required']);
        exit;
    }

    // Mock data for testing - replace with real database query later
    $mock_reports = [
        [
            'id' => 1,
            'name' => 'Heat 1 Start List',
            'type' => 'start_list',
            'category' => 'Men\'s Open',
            'heat_number' => 1,
            'heat_badge' => 'Heat 1',
            'type_info' => [
                'label' => 'Start List',
                'icon' => 'fa-list-ul',
                'color' => 'success'
            ],
            'urls' => [
                'pdf' => "http://localhost/v2/api/start_list_api.php?event_id=$event_id&config_id=1&format=pdf",
                'html' => "http://localhost/v2/api/start_list_api.php?event_id=$event_id&config_id=1&format=html",
                'csv' => "http://localhost/v2/api/start_list_api.php?event_id=$event_id&config_id=1&format=csv",
                'json' => "http://localhost/v2/api/start_list_api.php?event_id=$event_id&config_id=1&format=json"
            ],
            'created_at' => '2025-08-20 10:00:00',
            'updated_at' => '2025-08-20 10:00:00'
        ],
        [
            'id' => 2,
            'name' => 'Heat 2 Start List',
            'type' => 'start_list',
            'category' => 'Women\'s Open',
            'heat_number' => 2,
            'heat_badge' => 'Heat 2',
            'type_info' => [
                'label' => 'Start List',
                'icon' => 'fa-list-ul',
                'color' => 'success'
            ],
            'urls' => [
                'pdf' => "http://localhost/v2/api/start_list_api.php?event_id=$event_id&config_id=2&format=pdf",
                'html' => "http://localhost/v2/api/start_list_api.php?event_id=$event_id&config_id=2&format=html",
                'csv' => "http://localhost/v2/api/start_list_api.php?event_id=$event_id&config_id=2&format=csv",
                'json' => "http://localhost/v2/api/start_list_api.php?event_id=$event_id&config_id=2&format=json"
            ],
            'created_at' => '2025-08-20 11:00:00',
            'updated_at' => '2025-08-20 11:00:00'
        ],
        [
            'id' => 3,
            'name' => 'Results Summary',
            'type' => 'summary_table',
            'category' => 'Overall',
            'heat_number' => null,
            'heat_badge' => 'Results',
            'type_info' => [
                'label' => 'Summary Table',
                'icon' => 'fa-table',
                'color' => 'info'
            ],
            'urls' => [
                'pdf' => "http://localhost/v2/api/summary_table_api.php?config_id=3&config_name=Results%20Summary&format=pdf",
                'html' => "http://localhost/v2/api/summary_table_api.php?config_id=3&config_name=Results%20Summary&format=html",
                'csv' => "http://localhost/v2/api/summary_table_api.php?config_id=3&config_name=Results%20Summary&format=csv",
                'json' => "http://localhost/v2/api/summary_table_api.php?config_id=3&config_name=Results%20Summary&format=json"
            ],
            'created_at' => '2025-08-20 12:00:00',
            'updated_at' => '2025-08-20 12:00:00'
        ]
    ];

    // Filter reports based on type
    $filtered_reports = [];
    if ($filter_type === 'all') {
        $filtered_reports = $mock_reports;
    } else {
        foreach ($mock_reports as $report) {
            if ($report['type'] === $filter_type) {
                $filtered_reports[] = $report;
            }
        }
    }

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

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

    // Generate statistics
    $stats = [
        'total_reports' => count($filtered_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' => $filtered_reports,
        'grouped_reports' => $grouped_reports,
        'meta' => [
            'total_count' => count($filtered_reports),
            'has_data' => !empty($filtered_reports),
            'generated_at' => date('Y-m-d H:i:s'),
            'api_version' => '1.0-mock',
            'note' => 'This is mock data for testing. Database connection needs to be fixed.'
        ]
    ];

    echo json_encode($response, JSON_PRETTY_PRINT);

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