<?php
header('Content-Type: application/json');
include '../includes/auth.php';
include '../includes/db.php';

try {
    $event_id = $_GET['event_id'] ?? null;
    $heat_number = $_GET['heat_number'] ?? null;
    
    if (!$event_id) {
        echo json_encode(['success' => false, 'message' => 'Event ID is required']);
        exit;
    }
    
    $categories = [];
    
    if ($heat_number) {
        // Get heat-specific categories from event_heat_settings.categories column
        $stmt = $pdo->prepare("
            SELECT categories 
            FROM event_heat_settings 
            WHERE event_id = ? AND heat_number = ? 
            LIMIT 1
        ");
        $stmt->execute([$event_id, $heat_number]);
        $heat_categories_json = $stmt->fetchColumn();
        
        if ($heat_categories_json) {
            $heat_categories = json_decode($heat_categories_json, true);
            if (is_array($heat_categories)) {
                foreach ($heat_categories as $cat) {
                    $categories[] = ['category_name' => $cat];
                }
            }
        }
        
        // If no categories found through heat settings, fall back to participants in the heat
        if (empty($categories)) {
            $stmt = $pdo->prepare("
                SELECT DISTINCT ep.category as category_name
                FROM event_participants ep
                WHERE ep.event_id = ? AND ep.heat_number = ? AND ep.category IS NOT NULL
                ORDER BY ep.category
            ");
            $stmt->execute([$event_id, $heat_number]);
            $participant_categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            if ($participant_categories) {
                $categories = $participant_categories;
            }
        }
    } else {
        // If no heat selected, get all main + ranking categories for the event
        $stmt = $pdo->prepare("
            SELECT category_name, is_main_category
            FROM event_categories 
            WHERE event_id = ? 
            ORDER BY is_main_category DESC, category_name
        ");
        $stmt->execute([$event_id]);
        $event_categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        if ($event_categories) {
            $categories = $event_categories;
        }
        
        // Also get legacy categories for backward compatibility
        $stmt = $pdo->prepare("
            SELECT DISTINCT category as category_name
            FROM event_participants 
            WHERE event_id = ? AND category IS NOT NULL 
            ORDER BY category
        ");
        $stmt->execute([$event_id]);
        $participant_categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Add legacy categories that aren't already in the list
        foreach ($participant_categories as $cat) {
            if (!in_array($cat['category_name'], array_column($categories, 'category_name'))) {
                $categories[] = ['category_name' => $cat['category_name'], 'is_main_category' => 0];
            }
        }
    }
    
    echo json_encode([
        'success' => true, 
        'categories' => $categories,
        'heat_number' => $heat_number,
        'event_id' => $event_id
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false, 
        'message' => 'Error fetching categories: ' . $e->getMessage()
    ]);
}
?>
