<?php
// Script to assign random profile pictures and facts to participants
include '../includes/db.php';

// Profile picture files
$male_pictures = [
    'uploads/profile_stills/m.png',
    'uploads/profile_stills/m_1.png',
    'uploads/profile_stills/m_2.png',
    'uploads/profile_stills/m_3.png',
    'uploads/profile_stills/m_4.png',
    'uploads/profile_stills/m_5.png',
    'uploads/profile_stills/m_6.png',
    'uploads/profile_stills/m_7.png'
];

$female_pictures = [
    'uploads/profile_stills/f.png',
    'uploads/profile_stills/f_1.png',
    'uploads/profile_stills/f_2.png',
    'uploads/profile_stills/f_3.png',
    'uploads/profile_stills/f_4.png',
    'uploads/profile_stills/f_5.png',
    'uploads/profile_stills/f_6.png',
    'uploads/profile_stills/f_7.png'
];

// Random facts templates
$fact_templates = [
    // Achievements
    ['title' => 'Championship Record', 'facts' => [
        'Won national championship in 2023',
        'Regional champion for 3 consecutive years',
        'Set new junior record in 2022',
        'Placed 1st in international competition',
        'Undefeated in local competitions this season'
    ]],
    
    // Specialties
    ['title' => 'Specialty Move', 'facts' => [
        'Masters the double backflip with perfect landing',
        'Known for innovative rail combinations',
        'Signature 360-degree aerial maneuver',
        'Expert in halfpipe transitions',
        'Perfected the cork 720 technique'
    ]],
    
    // Personal Records
    ['title' => 'Personal Best', 'facts' => [
        'Highest score: 95.7 points',
        'Longest air time: 3.2 seconds',
        'Most consecutive wins: 12',
        'Fastest qualification time this season',
        'Best technical score: 48.5/50'
    ]],
    
    // Training
    ['title' => 'Training Focus', 'facts' => [
        'Trains 6 days a week year-round',
        'Specializes in morning training sessions',
        'Works with Olympic-level coaching staff',
        'Focuses on mental preparation techniques',
        'Cross-trains with skateboarding in summer'
    ]],
    
    // Background
    ['title' => 'Background', 'facts' => [
        'Started competing at age 8',
        'Comes from a family of athletes',
        'Coached by former Olympic medalist',
        'Self-taught until age 12',
        'Moved to mountain region for better training'
    ]],
    
    // Equipment
    ['title' => 'Equipment Preference', 'facts' => [
        'Uses custom-designed competition gear',
        'Sponsors: Burton and Red Bull',
        'Prefers shorter boards for technical tricks',
        'Always wears lucky competition gloves',
        'Tests new equipment before each season'
    ]],
    
    // Hobbies
    ['title' => 'Interests', 'facts' => [
        'Photography enthusiast',
        'Plays guitar in spare time',
        'Volunteers at local youth programs',
        'Studies sports psychology',
        'Collects vintage competition posters'
    ]],
    
    // Goals
    ['title' => 'Goals', 'facts' => [
        'Aiming for Olympic qualification',
        'Working towards perfect 100-point score',
        'Plans to compete internationally next year',
        'Goal to inspire next generation of athletes',
        'Wants to develop signature training program'
    ]]
];

try {
    echo "<h2>Assigning Random Profile Pictures and Facts</h2>\n";
    
    // Get all participants
    $stmt = $pdo->query("SELECT id, first_name, last_name, gender FROM participants WHERE photo IS NULL OR photo = ''");
    $participants = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo "<p>Found " . count($participants) . " participants without photos.</p>\n";
    
    $updated_count = 0;
    $facts_added = 0;
    
    foreach ($participants as $participant) {
        $participant_id = $participant['id'];
        $gender = strtoupper($participant['gender']);
        $name = $participant['first_name'] . ' ' . $participant['last_name'];
        
        // Assign profile picture based on gender
        $photo_path = null;
        if ($gender === 'M') {
            $photo_path = $male_pictures[array_rand($male_pictures)];
        } elseif ($gender === 'F') {
            $photo_path = $female_pictures[array_rand($female_pictures)];
        } else {
            // For unknown gender, randomly pick from either
            $all_pictures = array_merge($male_pictures, $female_pictures);
            $photo_path = $all_pictures[array_rand($all_pictures)];
        }
        
        // Update participant with photo
        if ($photo_path) {
            $update_stmt = $pdo->prepare("UPDATE participants SET photo = ? WHERE id = ?");
            $update_stmt->execute([$photo_path, $participant_id]);
            echo "<p>✓ Assigned photo to {$name} (ID: {$participant_id}): {$photo_path}</p>\n";
            $updated_count++;
        }
        
        // 70% chance to add facts (not all participants will have facts)
        if (rand(1, 100) <= 70) {
            // Randomly add 1-3 facts per participant
            $num_facts = rand(1, 3);
            
            // Get random fact templates
            $selected_templates = array_rand($fact_templates, min($num_facts, count($fact_templates)));
            if (!is_array($selected_templates)) {
                $selected_templates = [$selected_templates];
            }
            
            foreach ($selected_templates as $template_index) {
                $template = $fact_templates[$template_index];
                $title = $template['title'];
                $fact_text = $template['facts'][array_rand($template['facts'])];
                
                // Insert fact
                $fact_stmt = $pdo->prepare("INSERT INTO participant_facts (participant_id, title, fact, sort_order) VALUES (?, ?, ?, ?)");
                $sort_order = $facts_added + 1;
                $fact_stmt->execute([$participant_id, $title, $fact_text, $sort_order]);
                
                echo "<p>  → Added fact: \"{$title}\" - {$fact_text}</p>\n";
                $facts_added++;
            }
        }
        
        // Add a small delay to make output readable
        if ($updated_count % 10 == 0) {
            echo "<p><em>Processed {$updated_count} participants...</em></p>\n";
            flush();
        }
    }
    
    echo "\n<hr>\n";
    echo "<h3>Summary:</h3>\n";
    echo "<p>✓ Updated {$updated_count} participants with profile pictures</p>\n";
    echo "<p>✓ Added {$facts_added} random facts to participants</p>\n";
    
    // Show some statistics
    $stats_stmt = $pdo->query("
        SELECT 
            COUNT(*) as total_participants,
            COUNT(photo) as participants_with_photos,
            (SELECT COUNT(*) FROM participant_facts) as total_facts
        FROM participants
    ");
    $stats = $stats_stmt->fetch(PDO::FETCH_ASSOC);
    
    echo "<h3>Database Statistics:</h3>\n";
    echo "<ul>\n";
    echo "<li>Total participants: {$stats['total_participants']}</li>\n";
    echo "<li>Participants with photos: {$stats['participants_with_photos']}</li>\n";
    echo "<li>Total facts in database: {$stats['total_facts']}</li>\n";
    echo "</ul>\n";
    
    echo "\n<p><strong>Script completed successfully!</strong></p>\n";
    
} catch (Exception $e) {
    echo "<p style='color: red;'>Error: " . $e->getMessage() . "</p>\n";
}
?>
