<?php
// Debug script to test the API functionality
error_reporting(E_ALL);
ini_set('display_errors', 1);

try {
    include 'includes/db.php';
    echo "Database connection: OK\n";
    
    // Test if participant_facts table exists
    $stmt = $pdo->query("SHOW TABLES LIKE 'participant_facts'");
    if ($stmt->rowCount() > 0) {
        echo "participant_facts table: EXISTS\n";
        
        // Check if there are any facts
        $count_stmt = $pdo->query("SELECT COUNT(*) FROM participant_facts");
        $count = $count_stmt->fetchColumn();
        echo "Number of facts in database: $count\n";
    } else {
        echo "participant_facts table: DOES NOT EXIST\n";
    }
    
    // Test if participants table has photo column
    $stmt = $pdo->query("SHOW COLUMNS FROM participants LIKE 'photo'");
    if ($stmt->rowCount() > 0) {
        echo "participants.photo column: EXISTS\n";
    } else {
        echo "participants.photo column: DOES NOT EXIST\n";
    }
    
    // Test participant query
    $participant_stmt = $pdo->prepare("
        SELECT p.id, p.first_name, p.last_name, p.photo, p.club, p.country,
               ep.bib_number, ep.category_id,
               ec.category_name as category
        FROM event_participants ep
        JOIN participants p ON ep.participant_id = p.id
        LEFT JOIN event_categories ec ON ep.category_id = ec.id
        WHERE ep.event_id = ? AND ep.bib_number = ?
        LIMIT 1
    ");
    $participant_stmt->execute([3, 1]);
    $participant = $participant_stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($participant) {
        echo "Found participant: " . $participant['first_name'] . " " . $participant['last_name'] . "\n";
        echo "Photo: " . ($participant['photo'] ?: 'None') . "\n";
        
        // Get participant facts
        if ($participant['id']) {
            $facts_stmt = $pdo->prepare("
                SELECT id, title, fact, sort_order
                FROM participant_facts
                WHERE participant_id = ?
                ORDER BY sort_order, id
            ");
            $facts_stmt->execute([$participant['id']]);
            $facts = $facts_stmt->fetchAll(PDO::FETCH_ASSOC);
            
            echo "Number of facts: " . count($facts) . "\n";
            if (count($facts) > 0) {
                foreach ($facts as $fact) {
                    echo "- " . $fact['title'] . ": " . $fact['fact'] . "\n";
                }
            }
        }
    } else {
        echo "No participant found with BIB 1 in event 3\n";
    }
    
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
    echo "File: " . $e->getFile() . "\n";
    echo "Line: " . $e->getLine() . "\n";
}
?>
