<?php
include '../includes/auth.php';
include '../includes/db.php';

/**
 * Generate consistent colors based on category name
 * Uses HSL color space to ensure balanced, readable colors
 */
function generateCategoryColor($categoryName, $options = []) {
    // Validate input
    if (empty($categoryName) || !is_string($categoryName)) {
        $categoryName = 'Default Category';
    }
    
    $defaults = [
        'saturation_min' => 0.45,    // 45% minimum saturation (not too dull)
        'saturation_max' => 0.75,    // 75% maximum saturation (not too bright)  
        'lightness_min' => 0.35,     // 35% minimum lightness (not too dark)
        'lightness_max' => 0.65,     // 65% maximum lightness (not too bright)
        'alpha' => 1.0               // Full opacity by default
    ];
    
    $options = array_merge($defaults, $options);
    
    // Create consistent hash from category name
    $hash = hash('sha256', strtolower(trim($categoryName)));
    
    // Extract values from hash for color components
    $hue_seed = hexdec(substr($hash, 0, 8));
    $sat_seed = hexdec(substr($hash, 8, 8)); 
    $light_seed = hexdec(substr($hash, 16, 8));
    
    // Generate HSL values within specified ranges
    $hue = ($hue_seed % 360);
    
    $saturation = $options['saturation_min'] + 
        (($sat_seed % 1000) / 1000) * 
        ($options['saturation_max'] - $options['saturation_min']);
    
    $lightness = $options['lightness_min'] + 
        (($light_seed % 1000) / 1000) * 
        ($options['lightness_max'] - $options['lightness_min']);
    
    // Convert HSL to RGB
    $rgb = hslToRgb($hue, $saturation, $lightness);
    
    // Generate hex colors
    $hex = sprintf('#%02x%02x%02x', $rgb[0], $rgb[1], $rgb[2]);
    
    // Generate lighter variant for backgrounds
    $light_variant = hslToRgb($hue, $saturation * 0.6, min(0.85, $lightness + 0.25));
    $hex_light = sprintf('#%02x%02x%02x', $light_variant[0], $light_variant[1], $light_variant[2]);
    
    // Generate darker variant for borders
    $dark_variant = hslToRgb($hue, min(1.0, $saturation * 1.2), max(0.2, $lightness - 0.25));
    $hex_dark = sprintf('#%02x%02x%02x', $dark_variant[0], $dark_variant[1], $dark_variant[2]);
    
    // Determine contrasting text color
    $text_color = getContrastColor($hex);
    
    return [
        'background-color' => $hex,
        'color' => $text_color,
        'border-color' => $hex_dark,
        'background-light' => $hex_light,
        'css_class' => 'category-' . slugify($categoryName)
    ];
}

/**
 * Convert HSL to RGB
 */
function hslToRgb($h, $s, $l) {
    $h = $h / 360;
    
    if ($s == 0) {
        $r = $g = $b = $l;
    } else {
        $hue2rgb = function($p, $q, $t) {
            if ($t < 0) $t += 1;
            if ($t > 1) $t -= 1;
            if ($t < 1/6) return $p + ($q - $p) * 6 * $t;
            if ($t < 1/2) return $q;
            if ($t < 2/3) return $p + ($q - $p) * (2/3 - $t) * 6;
            return $p;
        };
        
        $q = $l < 0.5 ? $l * (1 + $s) : $l + $s - $l * $s;
        $p = 2 * $l - $q;
        
        $r = $hue2rgb($p, $q, $h + 1/3);
        $g = $hue2rgb($p, $q, $h);
        $b = $hue2rgb($p, $q, $h - 1/3);
    }
    
    return [round($r * 255), round($g * 255), round($b * 255)];
}

/**
 * Determine contrasting text color
 */
function getContrastColor($hex_color) {
    $hex_color = ltrim($hex_color, '#');
    $r = hexdec(substr($hex_color, 0, 2));
    $g = hexdec(substr($hex_color, 2, 2));
    $b = hexdec(substr($hex_color, 4, 2));
    
    $luminance = (0.299 * $r + 0.587 * $g + 0.114 * $b) / 255;
    return $luminance > 0.5 ? '#000000' : '#ffffff';
}

/**
 * Create URL-friendly slug
 */
function slugify($text) {
    $text = preg_replace('/[^a-zA-Z0-9]+/', '-', $text);
    return strtolower(trim($text, '-'));
}

$event_id = $_GET['event_id'] ?? null;
$edit_id = $_GET['edit'] ?? null;
$message = '';

if (!$event_id) {
    header('Location: events.php');
    exit;
}

// Fetch event details
$event_stmt = $pdo->prepare("SELECT * FROM events WHERE id = ?");
$event_stmt->execute([$event_id]);
$event = $event_stmt->fetch(PDO::FETCH_ASSOC);

if (!$event) {
    header('Location: events.php?msg=event_not_found');
    exit;
}

// Fetch category for editing if edit_id is provided
$edit_category = null;
if ($edit_id) {
    $edit_stmt = $pdo->prepare("SELECT * FROM event_categories WHERE id = ? AND event_id = ?");
    $edit_stmt->execute([$edit_id, $event_id]);
    $edit_category = $edit_stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$edit_category) {
        header('Location: event_categories.php?event_id=' . $event_id . '&msg=category_not_found');
        exit;
    }
}

// Handle category creation/update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['create_category']) || isset($_POST['update_category']))) {
    try {
        $category_name = trim($_POST['category_name']);
        $start_year = $_POST['start_year'] ?: null;
        $end_year = $_POST['end_year'] ?: null;
        $gender = $_POST['gender'];
        $requires_fis = isset($_POST['requires_fis']) ? 1 : 0;
        $requires_licence = isset($_POST['requires_licence']) ? 1 : 0;
        $is_main_category = isset($_POST['is_main_category']) ? 1 : 0;
        $use_for_ranking = isset($_POST['use_for_ranking']) ? 1 : 0;
        $country_rule = $_POST['country_rule'];
        $country_codes = $_POST['country_codes'] ? explode(',', str_replace(' ', '', $_POST['country_codes'])) : [];
        
        // Generate colors based on category name
        $colors = generateCategoryColor($category_name);
        $colors_json = json_encode($colors);
        
        if (isset($_POST['update_category'])) {
            // Update existing category
            $category_id = $_POST['category_id'];
            $stmt = $pdo->prepare("
                UPDATE event_categories 
                SET category_name = ?, start_year = ?, end_year = ?, gender = ?, 
                    requires_fis_number = ?, requires_licence_number = ?, 
                    is_main_category = ?, use_for_ranking = ?,
                    country_rule = ?, country_codes = ?, colors = ?, updated_at = CURRENT_TIMESTAMP
                WHERE id = ? AND event_id = ?
            ");
            
            $stmt->execute([
                $category_name, $start_year, $end_year, $gender, 
                $requires_fis, $requires_licence, $is_main_category, $use_for_ranking,
                $country_rule, json_encode($country_codes), $colors_json, $category_id, $event_id
            ]);
            
            // Redirect to prevent duplicate submission
            header("Location: event_categories.php?event_id=" . $event_id . "&msg=updated");
            exit;
        } else {
            // Create new category
            $stmt = $pdo->prepare("
                INSERT INTO event_categories 
                (event_id, category_name, start_year, end_year, gender, requires_fis_number, requires_licence_number, is_main_category, use_for_ranking, country_rule, country_codes, colors) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            
            $stmt->execute([
                $event_id, $category_name, $start_year, $end_year, $gender, 
                $requires_fis, $requires_licence, $is_main_category, $use_for_ranking,
                $country_rule, json_encode($country_codes), $colors_json
            ]);
            
            // Redirect to prevent duplicate submission
            header("Location: event_categories.php?event_id=" . $event_id . "&msg=created");
            exit;
        }
    } catch (Exception $e) {
        // Redirect with error message
        $error_type = isset($_POST['update_category']) ? 'update_error' : 'create_error';
        header("Location: event_categories.php?event_id=" . $event_id . "&msg=" . $error_type . "&error=" . urlencode($e->getMessage()));
        exit;
    }
}

// Handle category deletion
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_category'])) {
    try {
        $category_id = $_POST['category_id'];
        $stmt = $pdo->prepare("DELETE FROM event_categories WHERE id = ? AND event_id = ?");
        $stmt->execute([$category_id, $event_id]);
        
        // Redirect to prevent duplicate submission
        header("Location: event_categories.php?event_id=" . $event_id . "&msg=deleted");
        exit;
    } catch (Exception $e) {
        // Redirect with error message
        header("Location: event_categories.php?event_id=" . $event_id . "&msg=delete_error&error=" . urlencode($e->getMessage()));
        exit;
    }
}

// Handle color regeneration
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['regenerate_color'])) {
    try {
        $category_id = $_POST['category_id'];
        
        // Get category name for color generation
        $category_stmt = $pdo->prepare("SELECT category_name FROM event_categories WHERE id = ? AND event_id = ?");
        $category_stmt->execute([$category_id, $event_id]);
        $category_data = $category_stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($category_data) {
            // Generate new colors
            $colors = generateCategoryColor($category_data['category_name']);
            $colors_json = json_encode($colors);
            
            // Update colors in database
            $update_stmt = $pdo->prepare("UPDATE event_categories SET colors = ? WHERE id = ? AND event_id = ?");
            $update_stmt->execute([$colors_json, $category_id, $event_id]);
            
            // Redirect with success message
            header("Location: event_categories.php?event_id=" . $event_id . "&msg=color_regenerated");
            exit;
        } else {
            header("Location: event_categories.php?event_id=" . $event_id . "&msg=category_not_found");
            exit;
        }
    } catch (Exception $e) {
        header("Location: event_categories.php?event_id=" . $event_id . "&msg=color_error&error=" . urlencode($e->getMessage()));
        exit;
    }
}

// Handle auto-assignment
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['auto_assign'])) {
    try {
        $assignments_made = 0;
        $assignment_log = [];
        $summary_stats = [
            'total_participants' => 0,
            'assigned' => 0,
            'reassigned' => 0,
            'unmatched' => 0,
            'already_assigned' => 0,
            'category_counts' => []
        ];
        
        // Get all participants for this event
        $participants_stmt = $pdo->prepare("
            SELECT p.*, ep.id as event_participant_id, ep.category as current_category
            FROM participants p 
            INNER JOIN event_participants ep ON p.id = ep.participant_id 
            WHERE ep.event_id = ?
        ");
        $participants_stmt->execute([$event_id]);
        $participants = $participants_stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Get ALL categories for this event, not just main ones
        $categories_stmt = $pdo->prepare("SELECT * FROM event_categories WHERE event_id = ? ORDER BY is_main_category DESC, category_name");
        $categories_stmt->execute([$event_id]);
        $categories = $categories_stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Get only MAIN categories for matching primary category
        $main_categories = array_filter($categories, function($cat) {
            return $cat['is_main_category'] == 1;
        });
        
        if (empty($main_categories)) {
            header("Location: event_categories.php?event_id=" . $event_id . "&msg=auto_assign_no_main_categories");
            exit;
        }
        
        if (empty($participants)) {
            header("Location: event_categories.php?event_id=" . $event_id . "&msg=auto_assign_no_participants");
            exit;
        }
        
        $summary_stats['total_participants'] = count($participants);
        
        foreach ($participants as $participant) {
            $matched_main_category = null;
            $matched_main_score = -1;
            $match_reasons = [];
            $all_matching_category_ids = []; // Track ALL matching category IDs
            
            // First pass: Find the best matching MAIN category (for the 'category' column)
            foreach ($main_categories as $category) {
                $current_match_score = 0;
                $category_matches = true;
                $reasons = [];
                
                // Check birth year restrictions
                if ($category['start_year'] || $category['end_year']) {
                    $birth_year = null;
                    if ($participant['date_of_birth']) {
                        $birth_year = date('Y', strtotime($participant['date_of_birth']));
                    } elseif (isset($participant['birth_year']) && $participant['birth_year']) {
                        $birth_year = $participant['birth_year'];
                    }
                    
                    if ($birth_year) {
                        if ($category['start_year'] && $birth_year < $category['start_year']) {
                            $category_matches = false;
                            $reasons[] = "Too old (born {$birth_year}, need >= {$category['start_year']})";
                        }
                        if ($category['end_year'] && $birth_year > $category['end_year']) {
                            $category_matches = false;
                            $reasons[] = "Too young (born {$birth_year}, need <= {$category['end_year']})";
                        }
                        if ($category_matches) {
                            $current_match_score += 20;
                            $reasons[] = "Age match ({$birth_year})";
                        }
                    } else {
                        $current_match_score -= 10;
                        $reasons[] = "No birth year data";
                    }
                }
                
                // Check gender restrictions
                if ($category['gender'] !== 'open') {
                    $participant_gender = strtoupper(substr($participant['gender'] ?? '', 0, 1));
                    if ($participant_gender && $category['gender'] === $participant_gender) {
                        $current_match_score += 15;
                        $reasons[] = "Gender match ({$participant_gender})";
                    } else {
                        $category_matches = false;
                        $reasons[] = "Gender mismatch (need {$category['gender']}, got {$participant_gender})";
                    }
                } else {
                    $current_match_score += 5;
                    $reasons[] = "Open gender";
                }
                
                // Check FIS number requirement
                if ($category['requires_fis_number']) {
                    if (!empty($participant['fis_code'])) {
                        $current_match_score += 10;
                        $reasons[] = "Has FIS: {$participant['fis_code']}";
                    } else {
                        $category_matches = false;
                        $reasons[] = "Missing required FIS number";
                    }
                }
                
                // Check licence requirement
                if ($category['requires_licence_number']) {
                    if (!empty($participant['licence_number'])) {
                        $current_match_score += 10;
                        $reasons[] = "Has licence: {$participant['licence_number']}";
                    } else {
                        $category_matches = false;
                        $reasons[] = "Missing required licence number";
                    }
                }
                
                // Check country restrictions
                if ($category['country_rule'] !== 'all') {
                    $country_codes = json_decode($category['country_codes'] ?: '[]', true);
                    $participant_country = strtoupper($participant['country'] ?? '');
                    
                    if ($category['country_rule'] === 'include') {
                        if (in_array($participant_country, $country_codes)) {
                            $current_match_score += 10;
                            $reasons[] = "Country included ({$participant_country})";
                        } else {
                            $category_matches = false;
                            $reasons[] = "Country not in allowed list ({$participant_country})";
                        }
                    } elseif ($category['country_rule'] === 'exclude') {
                        if (in_array($participant_country, $country_codes)) {
                            $category_matches = false;
                            $reasons[] = "Country excluded ({$participant_country})";
                        } else {
                            $current_match_score += 5;
                            $reasons[] = "Country allowed ({$participant_country})";
                        }
                    }
                }
                
                // If this category matches and has a higher score, select it as the main category
                if ($category_matches && $current_match_score > $matched_main_score) {
                    $matched_main_category = $category;
                    $matched_main_score = $current_match_score;
                    $match_reasons = $reasons;
                }
            }
            
            // Second pass: Find ALL matching categories (for the 'category_id' JSON array)
            foreach ($categories as $category) {
                $category_matches = true;
                
                // Check birth year restrictions
                if ($category['start_year'] || $category['end_year']) {
                    $birth_year = null;
                    if ($participant['date_of_birth']) {
                        $birth_year = date('Y', strtotime($participant['date_of_birth']));
                    } elseif (isset($participant['birth_year']) && $participant['birth_year']) {
                        $birth_year = $participant['birth_year'];
                    }
                    
                    if ($birth_year) {
                        if ($category['start_year'] && $birth_year < $category['start_year']) {
                            $category_matches = false;
                        }
                        if ($category['end_year'] && $birth_year > $category['end_year']) {
                            $category_matches = false;
                        }
                    }
                }
                
                // Check gender restrictions
                if ($category['gender'] !== 'open') {
                    $participant_gender = strtoupper(substr($participant['gender'] ?? '', 0, 1));
                    if (!($participant_gender && $category['gender'] === $participant_gender)) {
                        $category_matches = false;
                    }
                }
                
                // Check FIS number requirement
                if ($category['requires_fis_number'] && empty($participant['fis_code'])) {
                    $category_matches = false;
                }
                
                // Check licence requirement
                if ($category['requires_licence_number'] && empty($participant['licence_number'])) {
                    $category_matches = false;
                }
                
                // Check country restrictions
                if ($category['country_rule'] !== 'all') {
                    $country_codes = json_decode($category['country_codes'] ?: '[]', true);
                    $participant_country = strtoupper($participant['country'] ?? '');
                    
                    if ($category['country_rule'] === 'include') {
                        if (!in_array($participant_country, $country_codes)) {
                            $category_matches = false;
                        }
                    } elseif ($category['country_rule'] === 'exclude') {
                        if (in_array($participant_country, $country_codes)) {
                            $category_matches = false;
                        }
                    }
                }
                
                // If this category matches, add its ID to the matching list
                if ($category_matches) {
                    $all_matching_category_ids[] = (int)$category['id'];
                }
            }
            
            // Process the assignment result
            $participant_name = $participant['first_name'] . ' ' . $participant['last_name'];
            $current_category = $participant['current_category'];
            
            if ($matched_main_category) {
                $new_category = $matched_main_category['category_name'];
                
                // Initialize category count if not exists
                if (!isset($summary_stats['category_counts'][$new_category])) {
                    $summary_stats['category_counts'][$new_category] = 0;
                }
                
                // Store all matching category IDs as JSON in a separate column
                $category_ids_json = json_encode($all_matching_category_ids);
                
                if ($current_category !== $new_category) {
                    // Update the participant's category AND category_id (use the main category's ID)
                    $update_stmt = $pdo->prepare("
                        UPDATE event_participants 
                        SET category = ?, category_id = ?, matching_category_ids = ?
                        WHERE id = ?
                    ");
                    $update_stmt->execute([
                        $new_category, 
                        $matched_main_category['id'],  // Use single ID for foreign key
                        $category_ids_json,            // Store full array in separate column
                        $participant['event_participant_id']
                    ]);
                    
                    $assignments_made++;
                    $summary_stats['category_counts'][$new_category]++;
                    
                    if ($current_category) {
                        $summary_stats['reassigned']++;
                        $action = 'REASSIGNED';
                    } else {
                        $summary_stats['assigned']++;
                        $action = 'ASSIGNED';
                    }
                    
                    $assignment_log[] = [
                        'name' => $participant_name,
                        'from' => $current_category ?: 'Unassigned',
                        'to' => $new_category,
                        'action' => $action,
                        'score' => $matched_main_score,
                        'reasons' => $match_reasons,
                        'country' => $participant['country'] ?? '',
                        'gender' => $participant['gender'] ?? '',
                        'birth_year' => $participant['date_of_birth'] ? date('Y', strtotime($participant['date_of_birth'])) : ($participant['birth_year'] ?? ''),
                        'matching_categories' => count($all_matching_category_ids)
                    ];
                } else {
                    // Already in correct main category, but update category_id anyway
                    $update_stmt = $pdo->prepare("
                        UPDATE event_participants 
                        SET category_id = ?, matching_category_ids = ?
                        WHERE id = ?
                    ");
                    $update_stmt->execute([
                        $matched_main_category['id'],  // Use single ID for foreign key
                        $category_ids_json,            // Store full array in separate column
                        $participant['event_participant_id']
                    ]);
                    
                    $summary_stats['already_assigned']++;
                    $summary_stats['category_counts'][$new_category]++;
                    
                    $assignment_log[] = [
                        'name' => $participant_name,
                        'from' => $current_category,
                        'to' => $new_category,
                        'action' => 'ALREADY_ASSIGNED',
                        'score' => $matched_main_score,
                        'reasons' => $match_reasons,
                        'country' => $participant['country'] ?? '',
                        'gender' => $participant['gender'] ?? '',
                        'birth_year' => $participant['date_of_birth'] ? date('Y', strtotime($participant['date_of_birth'])) : ($participant['birth_year'] ?? ''),
                        'matching_categories' => count($all_matching_category_ids)
                    ];
                }
            } else {
                // No matching main category found
                if (!empty($all_matching_category_ids)) {
                    // We have non-main categories but no main category
                    // Choose the first matching category as the foreign key reference
                    $first_category_id = $all_matching_category_ids[0];
                    $category_ids_json = json_encode($all_matching_category_ids);
                    
                    $update_stmt = $pdo->prepare("
                        UPDATE event_participants 
                        SET category_id = ?, matching_category_ids = ?, category = NULL
                        WHERE id = ?
                    ");
                    $update_stmt->execute([
                        $first_category_id,       // Use single ID for foreign key
                        $category_ids_json,       // Store full array in separate column
                        $participant['event_participant_id']
                    ]);
                    
                    $assignment_log[] = [
                        'name' => $participant_name,
                        'from' => $current_category ?: 'Unassigned',
                        'to' => 'NO MAIN MATCH (But matches other categories)',
                        'action' => 'PARTIAL_MATCH',
                        'score' => 0,
                        'reasons' => ['Matches ' . count($all_matching_category_ids) . ' non-main categories'],
                        'country' => $participant['country'] ?? '',
                        'gender' => $participant['gender'] ?? '',
                        'birth_year' => $participant['date_of_birth'] ? date('Y', strtotime($participant['date_of_birth'])) : ($participant['birth_year'] ?? ''),
                        'matching_categories' => count($all_matching_category_ids)
                    ];
                } else {
                    // No matching category found at all
                    $update_stmt = $pdo->prepare("
                        UPDATE event_participants 
                        SET category_id = NULL, category = NULL, matching_category_ids = NULL
                        WHERE id = ?
                    ");
                    $update_stmt->execute([$participant['event_participant_id']]);
                    
                    $assignment_log[] = [
                        'name' => $participant_name,
                        'from' => $current_category ?: 'Unassigned',
                        'to' => 'NO MATCH FOUND',
                        'action' => 'UNMATCHED',
                        'score' => 0,
                        'reasons' => ['No category matches participant criteria'],
                        'country' => $participant['country'] ?? '',
                        'gender' => $participant['gender'] ?? '',
                        'birth_year' => $participant['date_of_birth'] ? date('Y', strtotime($participant['date_of_birth'])) : ($participant['birth_year'] ?? ''),
                        'matching_categories' => 0
                    ];
                }
            }
        }
        
        // Store comprehensive assignment data in session
        session_start();
        $_SESSION['assignment_log'] = $assignment_log;
        $_SESSION['assignments_made'] = $assignments_made;
        $_SESSION['summary_stats'] = $summary_stats;
        
        // Redirect with success message
        header("Location: event_categories.php?event_id=" . $event_id . "&msg=auto_assigned");
        exit;
    } catch (Exception $e) {
        // Redirect with error message
        header("Location: event_categories.php?event_id=" . $event_id . "&msg=auto_assign_error&error=" . urlencode($e->getMessage()));
        exit;
    }
}

// Handle GET messages after redirect
$message = '';
if (isset($_GET['msg'])) {
    $error_detail = isset($_GET['error']) ? htmlspecialchars($_GET['error']) : '';
    
    switch ($_GET['msg']) {
        case 'created':
            $message = '<div class="alert alert-success alert alert-dismissible fade show">
                <i class="fas fa-check-circle me-2"></i>Category created successfully!
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>';
            break;
        case 'updated':
            $message = '<div class="alert alert-success alert alert-dismissible fade show">
                <i class="fas fa-check-circle me-2"></i>Category updated successfully!
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>';
            break;
        case 'deleted':
            $message = '<div class="alert alert-warning alert alert-dismissible fade show">
                <i class="fas fa-trash me-2"></i>Category deleted successfully!
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>';
            break;

        case 'create_error':
            $message = '<div class="alert alert-danger alert alert-dismissible fade show">
                <i class="fas fa-exclamation-triangle me-2"></i>Error creating category' . ($error_detail ? ': ' . $error_detail : '') . '
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>';
            break;
        case 'update_error':
            $message = '<div class="alert alert-danger alert alert-dismissible fade show">
                <i class="fas fa-exclamation-triangle me-2"></i>Error updating category' . ($error_detail ? ': ' . $error_detail : '') . '
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>';
            break;
        case 'delete_error':
            $message = '<div class="alert alert-danger alert alert-dismissible fade show">
                <i class="fas fa-exclamation-triangle me-2"></i>Error deleting category' . ($error_detail ? ': ' . $error_detail : '') . '
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>';
            break;
        case 'auto_assign_error':
            $message = '<div class="alert alert-danger alert alert-dismissible fade show">
                <i class="fas fa-exclamation-triangle me-2"></i>Error during auto-assignment' . ($error_detail ? ': ' . $error_detail : '') . '
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>';
            break;
        case 'category_not_found':
            $message = '<div class="alert alert-warning alert alert-dismissible fade show">
                <i class="fas fa-exclamation-triangle me-2"></i>Category not found or does not belong to this event.
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>';
            break;
             case 'auto_assign_no_categories':
            $message = '<div class="alert alert-warning alert alert-dismissible fade show">
                <i class="fas fa-exclamation-triangle me-2"></i>Cannot run auto-assignment: No categories have been created yet.
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>';
            break;
        case 'auto_assign_no_main_categories':
            $message = '<div class="alert alert-warning alert alert-dismissible fade show">
                <i class="fas fa-exclamation-triangle me-2"></i>Cannot run auto-assignment: No main categories have been created yet. Please mark at least one category as "Main Category".
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>';
            break;
        case 'auto_assigned':
            //session_start();
            $assignments_made = $_SESSION['assignments_made'] ?? 0;
            $assignment_log = $_SESSION['assignment_log'] ?? [];
            $summary_stats = $_SESSION['summary_stats'] ?? [];
            
            $message = '<div class="alert alert-info alert alert-dismissible fade show">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <h5 class="mb-3"><i class="fas fa-robot me-2"></i>Auto-Assignment Complete!</h5>
                        
                        <!-- Summary Statistics -->
                        <div class="row mb-3">
                            <div class="col-md-12">
                                <div class="row text-center">
                                    <div class="col">
                                        <div class="bg-primary text-white rounded p-2 mb-1">
                                            <strong>' . ($summary_stats['total_participants'] ?? 0) . '</strong>
                                        </div>
                                        <small>Total Participants</small>
                                    </div>
                                    <div class="col">
                                        <div class="bg-success text-white rounded p-2 mb-1">
                                            <strong>' . ($summary_stats['assigned'] ?? 0) . '</strong>
                                        </div>
                                        <small>Newly Assigned</small>
                                    </div>
                                    <div class="col">
                                        <div class="bg-warning rounded p-2 mb-1">
                                            <strong>' . ($summary_stats['reassigned'] ?? 0) . '</strong>
                                        </div>
                                        <small>Reassigned</small>
                                    </div>
                                    <div class="col">
                                        <div class="bg-info text-white rounded p-2 mb-1">
                                            <strong>' . ($summary_stats['already_assigned'] ?? 0) . '</strong>
                                        </div>
                                        <small>Already Correct</small>
                                    </div>
                                    <div class="col">
                                        <div class="bg-danger text-white rounded p-2 mb-1">
                                            <strong>' . ($summary_stats['unmatched'] ?? 0) . '</strong>
                                        </div>
                                        <small>No Match</small>
                                    </div>
                                </div>
                            </div>
                        </div>';
            
            // Category Distribution
            if (!empty($summary_stats['category_counts'])) {
                $message .= '<div class="mb-3">
                    <h6><i class="fas fa-chart-pie me-2"></i>Category Distribution:</h6>
                    <div class="row">';
                
                foreach ($summary_stats['category_counts'] as $category_name => $count) {
                    $message .= '<div class="col-auto mb-1">
                        <span class="badge bg-secondary">' . htmlspecialchars($category_name) . ': <strong>' . $count . '</strong></span>
                    </div>';
                }
                
                $message .= '</div></div>';
            }
            
            $message .= '</div>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>';
            
            // Detailed Assignment Log
            if (!empty($assignment_log)) {
                $message .= '<div class="mt-3">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <h6 class="mb-0"><i class="fas fa-list me-2"></i>Assignment Details</h6>
                        <div class="btn-group btn-group-sm" role="group">
                            <button type="button" class="btn btn-outline-secondary" onclick="filterAssignments(\'all\')">All</button>
                            <button type="button" class="btn btn-outline-success" onclick="filterAssignments(\'ASSIGNED\')">Assigned</button>
                            <button type="button" class="btn btn-outline-warning" onclick="filterAssignments(\'REASSIGNED\')">Reassigned</button>
                            <button type="button" class="btn btn-outline-danger" onclick="filterAssignments(\'UNMATCHED\')">Unmatched</button>
                        </div>
                    </div>
                    
                    <div id="assignmentDetails" style="max-height: 400px; overflow-y: auto; font-size: 0.9em;" class="border rounded p-2">';
                
                foreach ($assignment_log as $index => $log) {
                    $action_colors = [
                        'ASSIGNED' => 'success',
                        'REASSIGNED' => 'warning',
                        'ALREADY_ASSIGNED' => 'info',
                        'UNMATCHED' => 'danger'
                    ];
                    
                    $action_color = $action_colors[$log['action']] ?? 'secondary';
                    $to_color = $log['to'] === 'NO MATCH FOUND' ? 'danger' : 'success';
                    
                    $message .= '<div class="assignment-row border-bottom py-2" data-action="' . $log['action'] . '">
                        <div class="d-flex justify-content-between align-items-start">
                            <div class="flex-grow-1">
                                <div class="d-flex align-items-center mb-1">
                                    <strong>' . htmlspecialchars($log['name']) . '</strong>
                                    <span class="badge bg-' . $action_color . ' ms-2">' . $log['action'] . '</span>
                                    <span class="badge bg-secondary ms-1">Score: ' . $log['score'] . '</span>
                                </div>
                                
                                <div class="mb-1">
                                    <span class="badge bg-light text-dark me-1">' . htmlspecialchars($log['from']) . '</span>
                                    <i class="fas fa-arrow-right mx-1 text-muted"></i>
                                    <span class="badge bg-' . $to_color . '">' . htmlspecialchars($log['to']) . '</span>
                                </div>
                                
                                <div class="small text-muted mb-1">
                                    <i class="fas fa-user me-1"></i>' . htmlspecialchars($log['gender']) . ' • 
                                    <i class="fas fa-flag me-1"></i>' . htmlspecialchars($log['country']) . ' • 
                                    <i class="fas fa-birthday-cake me-1"></i>' . htmlspecialchars($log['birth_year'] ?: 'Unknown') . '
                                </div>';
                    
                    if (!empty($log['reasons'])) {
                        $message .= '<div class="small">
                            <strong>Matching details:</strong> ' . implode(', ', array_map('htmlspecialchars', $log['reasons'])) . '
                        </div>';
                    }
                    
                    $message .= '</div>
                        </div>
                    </div>';
                }
                
                $message .= '</div></div>';
            }
            
            $message .= '</div>';
            
            // Clear session data
            unset($_SESSION['assignment_log']);
            unset($_SESSION['assignments_made']);
            unset($_SESSION['summary_stats']);
            break;
            
        case 'auto_assign_no_participants':
            $message = '<div class="alert alert-warning alert alert-dismissible fade show">
                <i class="fas fa-exclamation-triangle me-2"></i>Cannot run auto-assignment: No participants found for this event.
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>';
            break;    
        case 'auto_assign_no_categories':
            $message = '<div class="alert alert-warning alert alert-dismissible fade show">
                <i class="fas fa-exclamation-triangle me-2"></i>Cannot run auto-assignment: No categories have been created yet.
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>';
            break;
        case 'color_regenerated':
            $message = '<div class="alert alert-success alert alert-dismissible fade show">
                <i class="fas fa-palette me-2"></i>Category color regenerated successfully!
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>';
            break;
        case 'color_error':
            $message = '<div class="alert alert-danger alert alert-dismissible fade show">
                <i class="fas fa-exclamation-triangle me-2"></i>Error regenerating color' . ($error_detail ? ': ' . $error_detail : '') . '
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>';
            break;    
    }
}

// Fetch existing categories
$categories_stmt = $pdo->prepare("SELECT *, colors FROM event_categories WHERE event_id = ? ORDER BY category_name");
$categories_stmt->execute([$event_id]);
$categories_raw = $categories_stmt->fetchAll(PDO::FETCH_ASSOC);

// Remove any potential duplicates based on ID
$categories = [];
$seen_ids = [];
foreach ($categories_raw as $category) {
    if (!in_array($category['id'], $seen_ids)) {
        $categories[] = $category;
        $seen_ids[] = $category['id'];
    }
}

// Generate colors for categories that don't have them
$updated_categories = [];
foreach ($categories as $category) {
    try {
        if (empty($category['colors'])) {
            $colors = generateCategoryColor($category['category_name']);
            $colors_json = json_encode($colors);
            
            // Update the database with generated colors
            $update_stmt = $pdo->prepare("UPDATE event_categories SET colors = ? WHERE id = ?");
            $update_stmt->execute([$colors_json, $category['id']]);
            
            // Update the category with new colors
            $category['colors'] = $colors_json;
        }
        $updated_categories[] = $category;
    } catch (Exception $e) {
        // If color generation fails, use the category without colors
        error_log("Color generation failed for category " . $category['category_name'] . ": " . $e->getMessage());
        $updated_categories[] = $category;
    }
}
$categories = $updated_categories;

// Load country codes from file
$country_codes = [];
if (file_exists('../data/country_codes.json')) {
    $country_codes = json_decode(file_get_contents('../data/country_codes.json'), true);
}

// Parse country codes for edit mode
$edit_country_codes_string = '';
if ($edit_category && $edit_category['country_codes']) {
    $edit_country_codes_array = json_decode($edit_category['country_codes'], true);
    $edit_country_codes_string = implode(', ', $edit_country_codes_array);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Event Categories - <?= htmlspecialchars($event['name']) ?></title>
    <?php include_once '../includes/stylesheets.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet">
    <style>
        .card {
            border: none;
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
            border-radius: 0.5rem;
        }
        
        .card-header {
            background: transparent;
            border-bottom: 1px solid rgba(0,0,0,.125);
            font-weight: 600;
        }
        
        .category-item {
            border: 1px solid #dee2e6;
            border-radius: 0.375rem;
            padding: 0.5rem;
            margin-bottom: 0.375rem;
            background: #ffffff;
            transition: all 0.15s ease-in-out;
        }
        
        .category-item:hover {
            border-color: #0d6efd;
            box-shadow: 0 0.125rem 0.25rem rgba(13, 110, 253, 0.1);
        }
        
        .category-item.editing {
            border-color: #ffc107;
            background: #fff3cd;
        }
        
        .auto-assign-card {
            background: linear-gradient(135deg, #198754 0%, #20c997 100%);
            color: white;
            border: none;
        }
        
        .form-section {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 0.375rem;
            padding: 0.75rem;
            margin-bottom: 0.5rem;
        }
        
        .section-title {
            color: #495057;
            font-weight: 600;
            margin-bottom: 0.5rem;
            padding-bottom: 0.25rem;
            border-bottom: 2px solid #0d6efd;
            font-size: 0.8rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .empty-state {
            text-align: center;
            padding: 3rem 1rem;
            color: #6c757d;
        }
        
        .edit-indicator {
            background: linear-gradient(135deg, #ffc107 0%, #ffca2c 100%);
            color: #212529;
            padding: 0.5rem 1rem;
            border-radius: 0.375rem 0.375rem 0 0;
            font-weight: 600;
            border-bottom: 1px solid rgba(0,0,0,.125);
        }
        
        .assignment-row {
            border-bottom: 1px solid #e9ecef;
            padding: 0.75rem 0;
        }
        
        .assignment-row:last-child {
            border-bottom: none;
        }
        
        .btn {
            border-radius: 0.375rem;
            font-weight: 500;
        }
        
        .btn-group-sm > .btn {
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
        }
        
        .badge {
            font-weight: 500;
        }
        
        .color-preview {
            transition: all 0.2s ease-in-out;
            cursor: pointer;
        }
        
        .color-preview:hover {
            transform: scale(1.1);
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }
        
        .category-item:hover .color-preview {
            box-shadow: 0 2px 4px rgba(0,0,0,0.15);
        }
        
        .color-info-badge {
            font-family: 'Courier New', monospace;
            font-size: 10px;
            border: 1px solid rgba(0,0,0,0.1);
        }
        
        .form-check-input:checked {
            background-color: #0d6efd;
            border-color: #0d6efd;
        }
        
        .text-primary {
            color: #0d6efd !important;
        }
        
        .bg-primary {
            background-color: #0d6efd !important;
        }
        
        .btn-primary {
            background-color: #0d6efd;
            border-color: #0d6efd;
        }
        
        .btn-primary:hover {
            background-color: #0b5ed7;
            border-color: #0a58ca;
        }
        
        .alert {
            border: none;
            border-radius: 0.5rem;
        }
        
        .progress {
            height: 0.25rem;
            border-radius: 0.25rem;
        }
        
        .card-body {
            padding: 0.75rem;
        }
        
        @media (max-width: 768px) {
            .btn-group-vertical {
                flex-direction: row;
            }
            
            .category-item {
                padding: 0.375rem;
            }
            
            .form-section {
                padding: 0.5rem;
                margin-bottom: 0.375rem;
            }
        }
    </style>
</head>
<body class="body-bg-aurora-bright">
    <?php include '../menu.php'; ?>
    
    <div class="container-fluid container-StyleScore p-4">
            <!-- event action menu. -->
<div class="row mb-2">
    <div class="col-12">
        <?php       
        $use_localStorage = true;
        $show_header = false;
        //$show_public_view = false;
        include 'event_actions_menu.php'; 
        ?>
    </div>
</div>
        <!-- Event Header -->
        <div class="bg-primary text-white p-3 rounded mb-3">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <h5 class="mb-1">
                        <i class="fas fa-tags me-2"></i>
                        Sport Categories
                    </h5>
                    <p class="mb-0 small">
                        <i class="fas fa-trophy me-1"></i><?= htmlspecialchars($event['name']) ?>
                        <span class="mx-2">•</span>
                        <i class="fas fa-calendar me-1"></i><?= date('M d, Y', strtotime($event['date'])) ?>
                    </p>
                </div>
                <div class="col-md-4 text-md-end">
                    <a href="event_dashboard.php?event_id=<?= $event_id ?>" class="btn btn-light btn-sm">
                        <i class="fas fa-arrow-left me-1"></i>Back to Dashboard
                    </a>
                </div>
            </div>
        </div>

        <?php if (!empty($message)) echo $message; ?>

        <div class="row g-2">
            <!-- Left Column: Create/Edit Category -->
            <div class="col-lg-6">
                <div class="border-0 shadow-none card h-100 <?= $edit_category ? 'border-warning' : '' ?>">
                    <?php if ($edit_category): ?>
                        <div class="edit-indicator">
                            <i class="fas fa-edit me-2"></i>Editing Category: <?= htmlspecialchars($edit_category['category_name']) ?>
                        </div>
                    <?php endif; ?>
                    <div class="border-0 shadow-none card-header <?= $edit_category ? 'bg-warning bg-opacity-10' : 'bg-primary bg-opacity-10' ?> py-2">
                        <div class="d-flex justify-content-between align-items-center">
                            <h6 class="mb-0 <?= $edit_category ? 'text-warning' : 'text-primary' ?>">
                                <i class="fas <?= $edit_category ? 'fa-edit' : 'fa-plus-circle' ?> me-2"></i>
                                <?= $edit_category ? 'Edit Category' : 'Create New Category' ?>
                            </h6>
                            <?php if ($edit_category): ?>
                                <a href="event_categories.php?event_id=<?= $event_id ?>" class="btn btn-outline-secondary btn-sm">
                                    <i class="fas fa-times me-1"></i>Cancel
                                </a>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="border-0 shadow-none card-body p-3">
                        <form method="post">
                            <input type="hidden" name="<?= $edit_category ? 'update_category' : 'create_category' ?>" value="1">
                            <?php if ($edit_category): ?>
                                <input type="hidden" name="category_id" value="<?= $edit_category['id'] ?>">
                            <?php endif; ?>
                            
                            <!-- Basic Information -->
                            <div class="form-section">
                                <h6 class="section-title">Basic Information</h6>
                                
                                <div class="mb-2">
                                    <label class="form-label fw-semibold">Category Name</label>
                                    <input type="text" class="form-control" name="category_name" required 
                                           value="<?= $edit_category ? htmlspecialchars($edit_category['category_name']) : '' ?>"
                                           placeholder="e.g., Men's Pro, Women's Amateur, Youth Open">
                                </div>
                            </div>

                            <!-- Age Restrictions -->
                            <div class="form-section">
                                <h6 class="section-title">Age Restrictions</h6>
                                
                                <div class="row">
                                    <div class="col-sm-6 mb-2">
                                        <label class="form-label fw-semibold">Start Year (Born From)</label>
                                        <input type="number" class="form-control" name="start_year" 
                                               min="1900" max="2030" placeholder="e.g., 1990"
                                               value="<?= $edit_category ? $edit_category['start_year'] : '' ?>">
                                        <div class="form-text">Leave empty for no restriction</div>
                                    </div>
                                    <div class="col-sm-6 mb-2">
                                        <label class="form-label fw-semibold">End Year (Born Until)</label>
                                        <input type="number" class="form-control" name="end_year" 
                                               min="1900" max="2030" placeholder="e.g., 2005"
                                               value="<?= $edit_category ? $edit_category['end_year'] : '' ?>">
                                        <div class="form-text">Leave empty for no restriction</div>
                                    </div>
                                </div>
                            </div>

                            <!-- Gender -->
                            <div class="form-section">
                                <h6 class="section-title">Gender Requirements</h6>
                                
                                <div class="row">
                                    <div class="col-12">
                                        <div class="form-check form-check-inline">
                                            <input class="form-check-input" type="radio" name="gender" value="M" id="gender_male"
                                                   <?= ($edit_category && $edit_category['gender'] === 'M') ? 'checked' : '' ?>>
                                            <label class="form-check-label" for="gender_male">
                                                <span class="badge bg-info">
                                                    <i class="fas fa-mars me-1"></i>Male Only
                                                </span>
                                            </label>
                                        </div>
                                        <div class="form-check form-check-inline">
                                            <input class="form-check-input" type="radio" name="gender" value="F" id="gender_female"
                                                   <?= ($edit_category && $edit_category['gender'] === 'F') ? 'checked' : '' ?>>
                                            <label class="form-check-label" for="gender_female">
                                                <span class="badge bg-danger">
                                                    <i class="fas fa-venus me-1"></i>Female Only
                                                </span>
                                            </label>
                                        </div>
                                        <div class="form-check form-check-inline">
                                            <input class="form-check-input" type="radio" name="gender" value="open" id="gender_open" 
                                                   <?= (!$edit_category || $edit_category['gender'] === 'open') ? 'checked' : '' ?>>
                                            <label class="form-check-label" for="gender_open">
                                                <span class="badge bg-success">
                                                    <i class="fas fa-venus-mars me-1"></i>Open (All Genders)
                                                </span>
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Requirements -->
                            <div class="form-section">
                                <h6 class="section-title">Additional Requirements</h6>
                                
                                <div class="form-check mb-2">
                                    <input class="form-check-input" type="checkbox" name="requires_fis" id="requires_fis"
                                           <?= ($edit_category && $edit_category['requires_fis_number']) ? 'checked' : '' ?>>
                                    <label class="form-check-label fw-semibold" for="requires_fis">
                                        <i class="fas fa-id-card text-primary me-2"></i>
                                        Requires FIS Number
                                    </label>
                                </div>
                                
                                <div class="form-check mb-2">
                                    <input class="form-check-input" type="checkbox" name="requires_licence" id="requires_licence"
                                           <?= ($edit_category && $edit_category['requires_licence_number']) ? 'checked' : '' ?>>
                                    <label class="form-check-label fw-semibold" for="requires_licence">
                                        <i class="fas fa-certificate text-warning me-2"></i>
                                        Requires Licence Number
                                    </label>
                                </div>
                            </div>

                            <!-- Category Classification -->
                            <div class="form-section">
                                <h6 class="section-title">Category Classification</h6>
                                
                                <div class="form-check mb-2">
                                    <input class="form-check-input" type="checkbox" name="is_main_category" id="is_main_category"
                                           <?= ($edit_category && $edit_category['is_main_category']) ? 'checked' : '' ?>>
                                    <label class="form-check-label fw-semibold" for="is_main_category">
                                        <i class="fas fa-star text-warning me-2"></i>
                                        Main Category
                                    </label>
                                    <div class="form-text">
                                        Mark this as a primary/main category for the event
                                    </div>
                                </div>
                                
                                <div class="form-check mb-2">
                                    <input class="form-check-input" type="checkbox" name="use_for_ranking" id="use_for_ranking"
                                           <?= ($edit_category && $edit_category['use_for_ranking']) ? 'checked' : '' ?>>
                                    <label class="form-check-label fw-semibold" for="use_for_ranking">
                                        <i class="fas fa-trophy text-success me-2"></i>
                                        Use for Ranking
                                    </label>
                                    <div class="form-text">
                                        Include this category in ranking calculations and results
                                    </div>
                                </div>
                                
                                <div class="alert alert-info mb-0">
                                    <small>
                                        <i class="fas fa-info-circle me-1"></i>
                                        <strong>Main Categories:</strong> Used for primary event organization and featured prominently in results.<br>
                                        <strong>Ranking Categories:</strong> Included in official rankings, leaderboards, and competition results.
                                    </small>
                                </div>
                            </div>

                            <!-- Country Restrictions -->
                            <div class="form-section">
                                <h6 class="section-title">Country Restrictions</h6>
                                
                                <div class="mb-3">
                                    <div class="form-check form-check-inline">
                                        <input class="form-check-input" type="radio" name="country_rule" value="all" id="country_all" 
                                               <?= (!$edit_category || $edit_category['country_rule'] === 'all') ? 'checked' : '' ?>>
                                        <label class="form-check-label" for="country_all">
                                            <span class="badge bg-secondary">All Countries</span>
                                        </label>
                                    </div>
                                    <div class="form-check form-check-inline">
                                        <input class="form-check-input" type="radio" name="country_rule" value="include" id="country_include"
                                               <?= ($edit_category && $edit_category['country_rule'] === 'include') ? 'checked' : '' ?>>
                                        <label class="form-check-label" for="country_include">
                                            <span class="badge bg-success">Only Selected</span>
                                        </label>
                                    </div>
                                    <div class="form-check form-check-inline">
                                        <input class="form-check-input" type="radio" name="country_rule" value="exclude" id="country_exclude"
                                               <?= ($edit_category && $edit_category['country_rule'] === 'exclude') ? 'checked' : '' ?>>
                                        <label class="form-check-label" for="country_exclude">
                                            <span class="badge bg-danger">Exclude Selected</span>
                                        </label>
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label fw-semibold">Country Codes</label>
                                    <input type="text" class="form-control" name="country_codes" 
                                           placeholder="e.g., USA, CAN, GER, FRA"
                                           value="<?= $edit_country_codes_string ?>">
                                    <div class="form-text">Comma separated. Only needed if using 'Only Selected' or 'Exclude Selected'</div>
                                </div>
                            </div>

                            <div class="d-grid">
                                <button type="submit" class="btn <?= $edit_category ? 'btn-warning' : 'btn-primary' ?>">
                                    <i class="fas <?= $edit_category ? 'fa-save' : 'fa-plus' ?> me-2"></i>
                                    <?= $edit_category ? 'Update Category' : 'Create Category' ?>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Right Column: Existing Categories -->
            <div class="col-lg-6">
                <!-- Auto Assignment Card -->
                <div class="auto-assign-card card text-white mb-3">
                    <div class="border-0 shadow-none card-body p-3">
                        <h6 class="card-title">
                            <i class="fas fa-robot me-2"></i>Auto-Assignment
                        </h6>
                        <p class="card-text mb-2 small">Automatically assign participants to <strong>main categories</strong> based on their profile data</p>
                        
                        <?php 
                        $main_categories = array_filter($categories, function($cat) { return $cat['is_main_category']; });
                        ?>
                        <?php if (empty($main_categories)): ?>
                            <div class="alert alert-warning text-dark mb-2">
                                <i class="fas fa-exclamation-triangle me-1"></i>
                                Create at least one main category before running auto-assignment.
                            </div>
                        <?php else: ?>
                            <div class="mb-2">
                                <div class="row g-1 text-center">
                                    <div class="col-4">
                                        <small class="d-block"><i class="fas fa-check me-1"></i> Age ranges</small>
                                    </div>
                                    <div class="col-4">
                                        <small class="d-block"><i class="fas fa-check me-1"></i> Gender rules</small>
                                    </div>
                                    <div class="col-4">
                                        <small class="d-block"><i class="fas fa-check me-1"></i> FIS numbers</small>
                                    </div>
                                    <div class="col-4">
                                        <small class="d-block"><i class="fas fa-check me-1"></i> Licences</small>
                                    </div>
                                    <div class="col-4">
                                        <small class="d-block"><i class="fas fa-check me-1"></i> Countries</small>
                                    </div>
                                    <div class="col-4">
                                        <small class="d-block"><i class="fas fa-check me-1"></i> Main only</small>
                                    </div>
                                </div>
                            </div>
                        <?php endif; ?>
                        
                        <form method="post" class="d-inline" id="autoAssignForm">
                            <input type="hidden" name="auto_assign" value="1">
                            <button type="submit" class="btn btn-light" <?= empty($main_categories) ? 'disabled' : '' ?>
                                    onclick="return confirm('This will automatically assign all participants to matching MAIN categories only. Current assignments may be changed. Continue?')">
                                <i class="fas fa-magic me-2"></i>Run Auto-Assignment
                            </button>
                        </form>
                    </div>
                </div>

                <!-- Existing Categories -->
                <div class="border-0 shadow-none card">
                    <div class="border-0 shadow-none card-header bg-light py-2">
                        <h6 class="mb-0 text-dark">
                            <i class="fas fa-list me-2"></i>
                            Current Categories (<?= count($categories) ?>)
                        </h6>
                    </div>
                    <div class="border-0 shadow-none card-body p-3">
                        <?php if (empty($categories)): ?>
                            <div class="empty-state">
                                <i class="fas fa-tags fa-2x mb-2 text-muted"></i>
                                <h6 class="text-muted">No Categories Yet</h6>
                                <p class="text-muted small">Create your first category to start organizing participants.</p>
                            </div>
                        <?php else: ?>
                            <?php foreach ($categories as $category): ?>
                                <?php 
                                // Parse colors from JSON
                                $colors = json_decode($category['colors'] ?? '{}', true);
                                $bg_color = $colors['background-color'] ?? '#6c757d';
                                $text_color = $colors['color'] ?? '#ffffff';
                                $border_color = $colors['border-color'] ?? '#495057';
                                $bg_light = $colors['background-light'] ?? '#e9ecef';
                                ?>
                                <div class="category-item <?= ($edit_category && $edit_category['id'] == $category['id']) ? 'editing' : '' ?>">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div class="flex-grow-1">
                                            <div class="d-flex align-items-center mb-2">
                                                <!-- Color Preview -->
                                                <div class="me-2" style="min-width: 40px;">
                                                    <div class="color-preview" style="
                                                        width: 32px; 
                                                        height: 32px; 
                                                        background-color: <?= htmlspecialchars($bg_color) ?>; 
                                                        border: 2px solid <?= htmlspecialchars($border_color) ?>;
                                                        border-radius: 6px;
                                                        display: flex;
                                                        align-items: center;
                                                        justify-content: center;
                                                        color: <?= htmlspecialchars($text_color) ?>;
                                                        font-weight: bold;
                                                        font-size: 12px;
                                                        text-shadow: 0 1px 2px rgba(0,0,0,0.1);
                                                    " title="Category Color: <?= htmlspecialchars($bg_color) ?>&#10;Text Color: <?= htmlspecialchars($text_color) ?>&#10;Border Color: <?= htmlspecialchars($border_color) ?>">
                                                        <?= strtoupper(substr($category['category_name'], 0, 2)) ?>
                                                    </div>
                                                </div>
                                                
                                                <div class="flex-grow-1">
                                                    <h6 class="mb-0 me-2">
                                                        <i class="fas fa-tag text-primary me-1"></i>
                                                        <?= htmlspecialchars($category['category_name']) ?>
                                                    </h6>
                                                    
                                                    <!-- Color Info Badge -->
                                                    <small class="text-muted d-block mt-1">
                                                        <i class="fas fa-palette me-1"></i>
                                                        <span class="color-info-badge" style="background-color: <?= htmlspecialchars($bg_light) ?>; color: <?= htmlspecialchars($border_color) ?>; padding: 2px 6px; border-radius: 4px;">
                                                            <?= htmlspecialchars($bg_color) ?>
                                                        </span>
                                                    </small>
                                                </div>
                                                
                                                <!-- Main Category Badge -->
                                                <?php if ($category['is_main_category']): ?>
                                                    <span class="badge bg-warning me-1">
                                                        <i class="fas fa-star me-1"></i>Main
                                                    </span>
                                                <?php endif; ?>
                                                
                                                <!-- Ranking Badge -->
                                                <?php if ($category['use_for_ranking']): ?>
                                                    <span class="badge bg-success me-1">
                                                        <i class="fas fa-trophy me-1"></i>Ranking
                                                    </span>
                                                <?php endif; ?>
                                                
                                                <?php if ($edit_category && $edit_category['id'] == $category['id']): ?>
                                                    <span class="badge bg-warning">
                                                        <i class="fas fa-edit me-1"></i>Editing
                                                    </span>
                                                <?php endif; ?>
                                            </div>
                                            
                                            <!-- Age Range -->
                                            <?php if ($category['start_year'] || $category['end_year']): ?>
                                                <div class="mb-2">
                                                    <small class="text-muted">
                                                        <i class="fas fa-birthday-cake me-1"></i>
                                                        Born: <?= $category['start_year'] ?: 'Any' ?> - <?= $category['end_year'] ?: 'Any' ?>
                                                    </small>
                                                </div>
                                            <?php endif; ?>
                                            
                                            <!-- Gender -->
                                            <div class="mb-2">
                                                <?php
                                                $gender_config = [
                                                    'M' => ['color' => 'info', 'icon' => 'fa-mars', 'text' => 'Male Only'],
                                                    'F' => ['color' => 'danger', 'icon' => 'fa-venus', 'text' => 'Female Only'],
                                                    'open' => ['color' => 'success', 'icon' => 'fa-venus-mars', 'text' => 'Open']
                                                ];
                                                $gender_info = $gender_config[$category['gender']] ?? $gender_config['open'];
                                                ?>
                                                <span class="badge bg-<?= $gender_info['color'] ?> me-1">
                                                    <i class="fas <?= $gender_info['icon'] ?> me-1"></i>
                                                    <?= $gender_info['text'] ?>
                                                </span>
                                                
                                                <!-- Requirements -->
                                                <?php if ($category['requires_fis_number']): ?>
                                                    <span class="badge bg-primary me-1">
                                                        <i class="fas fa-id-card me-1"></i>FIS
                                                    </span>
                                                <?php endif; ?>
                                                <?php if ($category['requires_licence_number']): ?>
                                                    <span class="badge bg-warning me-1">
                                                        <i class="fas fa-certificate me-1"></i>Licence
                                                    </span>
                                                <?php endif; ?>
                                            </div>
                                            
                                            <!-- Country Rules -->
                                            <?php if ($category['country_rule'] !== 'all'): ?>
                                                <div class="mb-1">
                                                    <?php
                                                    $country_colors = [
                                                        'include' => 'success',
                                                        'exclude' => 'danger'
                                                    ];
                                                    $country_texts = [
                                                        'include' => 'Only',
                                                        'exclude' => 'Exclude'
                                                    ];
                                                    ?>
                                                    <span class="badge bg-<?= $country_colors[$category['country_rule']] ?>">
                                                        <i class="fas fa-flag me-1"></i>
                                                        <?= $country_texts[$category['country_rule']] ?>: 
                                                        <?= implode(', ', json_decode($category['country_codes'] ?: '[]')) ?>
                                                    </span>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                        
                                        <div class="text-end ms-3">
                                            <div class="btn-group btn-group-sm">
                                                <a href="event_categories.php?event_id=<?= $event_id ?>&edit=<?= $category['id'] ?>" 
                                                   class="btn btn-outline-warning" title="Edit Category">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                <form method="post" class="d-inline">
                                                    <input type="hidden" name="delete_category" value="1">
                                                    <input type="hidden" name="category_id" value="<?= $category['id'] ?>">
                                                    <button type="submit" class="btn btn-outline-danger btn-sm" 
                                                            onclick="return confirm('Delete category \'<?= htmlspecialchars($category['category_name']) ?>\'?')"
                                                            title="Delete Category">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </form>
                                                <form method="post" class="d-inline">
                                                    <input type="hidden" name="regenerate_color" value="1">
                                                    <input type="hidden" name="category_id" value="<?= $category['id'] ?>">
                                                    <button type="submit" class="btn btn-outline-info btn-sm" 
                                                            title="Regenerate Color">
                                                        <i class="fas fa-palette"></i>
                                                    </button>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script>
        // Modern form validation and UX
        document.addEventListener('DOMContentLoaded', function() {
            // Prevent double submission
            const forms = document.querySelectorAll('form');
            
            forms.forEach(form => {
                form.addEventListener('submit', function(e) {
                    const submitButton = form.querySelector('button[type="submit"]');
                    
                    if (submitButton && !submitButton.disabled) {
                        submitButton.disabled = true;
                        const originalHtml = submitButton.innerHTML;
                        submitButton.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Processing...';
                        
                        // Re-enable after timeout as failsafe
                        setTimeout(() => {
                            submitButton.disabled = false;
                            submitButton.innerHTML = originalHtml;
                        }, 5000);
                    }
                });
            });

            // Country code input enhancement
            const countryRules = document.querySelectorAll('input[name="country_rule"]');
            const countryCodesInput = document.querySelector('input[name="country_codes"]');
            
            function toggleCountryInput() {
                const selectedRule = document.querySelector('input[name="country_rule"]:checked')?.value;
                if (countryCodesInput) {
                    countryCodesInput.disabled = selectedRule === 'all';
                    countryCodesInput.parentElement.style.opacity = selectedRule === 'all' ? '0.6' : '1';
                }
            }
            
            countryRules.forEach(radio => {
                radio.addEventListener('change', toggleCountryInput);
            });
            
            toggleCountryInput(); // Initial state

            // Enhanced visual feedback for category classification
            const isMainCheckbox = document.getElementById('is_main_category');
            const useForRankingCheckbox = document.getElementById('use_for_ranking');
            
            function updateFormSectionVisuals() {
                const formSection = document.querySelector('.form-section:has(#is_main_category)');
                if (!formSection) return;
                
                const isMain = isMainCheckbox?.checked;
                const isRanking = useForRankingCheckbox?.checked;
                
                // Reset styles
                formSection.style.borderLeft = '';
                formSection.style.borderRight = '';
                formSection.style.background = '#f8f9fa';
                
                if (isMain && isRanking) {
                    formSection.style.background = 'linear-gradient(135deg, #fff3cd 0%, #d1ecf1 100%)';
                    formSection.style.borderLeft = '4px solid #ffc107';
                    formSection.style.borderRight = '4px solid #28a745';
                } else if (isMain) {
                    formSection.style.background = 'linear-gradient(135deg, #fff3cd 0%, #fefcf3 100%)';
                    formSection.style.borderLeft = '4px solid #ffc107';
                } else if (isRanking) {
                    formSection.style.borderRight = '4px solid #28a745';
                }
            }
            
            if (isMainCheckbox) {
                isMainCheckbox.addEventListener('change', updateFormSectionVisuals);
            }
            if (useForRankingCheckbox) {
                useForRankingCheckbox.addEventListener('change', updateFormSectionVisuals);
            }
            
            updateFormSectionVisuals(); // Initial state
        });

        // Auto-assignment form handling
        document.getElementById('autoAssignForm')?.addEventListener('submit', function(e) {
            const button = this.querySelector('button[type="submit"]');
            button.disabled = true;
            button.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Analyzing participants...';
            
            // Show progress indicator
            const progressDiv = document.createElement('div');
            progressDiv.className = 'mt-3';
            progressDiv.innerHTML = `
                <div class="progress" style="height: 6px;">
                    <div class="progress-bar progress-bar-striped progress-bar-animated bg-light" 
                         role="progressbar" style="width: 100%"></div>
                </div>
                <small class="text-light d-block mt-2">
                    <i class="fas fa-cogs me-1"></i>Processing participant assignments...
                </small>
            `;
            this.appendChild(progressDiv);
        });

        // Assignment details filtering
        function filterAssignments(action) {
            const rows = document.querySelectorAll('.assignment-row');
            const buttons = document.querySelectorAll('[onclick^="filterAssignments"]');
            
            // Update active button state
            buttons.forEach(btn => {
                btn.classList.remove('active');
                if (btn.textContent.trim() === action || (action === 'all' && btn.textContent.trim() === 'All')) {
                    btn.classList.add('active');
                }
            });
            
            // Filter rows with smooth transition
            rows.forEach(row => {
                if (action === 'all' || row.getAttribute('data-action') === action) {
                    row.style.display = 'block';
                    row.style.opacity = '1';
                } else {
                    row.style.opacity = '0';
                    setTimeout(() => {
                        if (row.style.opacity === '0') {
                            row.style.display = 'none';
                        }
                    }, 150);
                }
            });
        }

        // Enhanced form validation
        function validateCategoryForm() {
            const categoryName = document.querySelector('input[name="category_name"]')?.value.trim();
            
            if (!categoryName) {
                // Create modern alert
                const alert = document.createElement('div');
                alert.className = 'alert alert-danger alert-dismissible fade show position-fixed';
                alert.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
                alert.innerHTML = `
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    Category name is required.
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                `;
                document.body.appendChild(alert);
                
                // Auto-remove after 5 seconds
                setTimeout(() => {
                    if (alert.parentElement) {
                        alert.remove();
                    }
                }, 5000);
                
                return false;
            }
            
            return true;
        }

        // Scroll to editing form
        <?php if ($edit_category): ?>
        document.addEventListener('DOMContentLoaded', function() {
            const editCard = document.querySelector('.card.border-warning');
            if (editCard) {
                editCard.scrollIntoView({ 
                    behavior: 'smooth', 
                    block: 'start' 
                });
            }
        });
        <?php endif; ?>

        // Clear URL parameters after showing message
        if (window.location.search.includes('msg=')) {
            setTimeout(() => {
                const url = new URL(window.location);
                url.searchParams.delete('msg');
                url.searchParams.delete('error');
                window.history.replaceState({}, document.title, url.toString());
            }, 8000);
        }

        // Enhanced tooltips for better UX
        document.addEventListener('DOMContentLoaded', function() {
            // Initialize Bootstrap tooltips if available
            if (typeof bootstrap !== 'undefined' && bootstrap.Tooltip) {
                const tooltipTriggerList = [].slice.call(document.querySelectorAll('[title]'));
                tooltipTriggerList.map(function (tooltipTriggerEl) {
                    return new bootstrap.Tooltip(tooltipTriggerEl, {
                        delay: { show: 500, hide: 100 }
                    });
                });
            }
        });

        // Auto-hide success/info alerts
        document.addEventListener('DOMContentLoaded', function() {
            const successAlerts = document.querySelectorAll('.alert-success, .alert-info');
            successAlerts.forEach(alert => {
                setTimeout(() => {
                    if (alert && alert.parentElement) {
                        const bsAlert = new bootstrap.Alert(alert);
                        bsAlert.close();
                    }
                }, 6000);
            });
        });
    </script>

    <?php include 'footer.php'; ?>
</body>
</html>