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

$message = '';

// Functions for SVG and styling
function getSvgWithColor($iconPath, $color, $uniqueClass = '') {
    if (!file_exists($iconPath)) {
        return '';
    }
    
    $svgContent = file_get_contents($iconPath);
    
    // Create a unique class for this SVG to avoid conflicts
    $svgClass = !empty($uniqueClass) ? $uniqueClass . '-svg' : 'svg-' . substr(md5($iconPath . $color), 0, 8);
    
    // Add class to SVG element
    $svgContent = str_replace('<svg', '<svg class="' . $svgClass . '"', $svgContent);
    
    return $svgContent;
}

function generateSubtleBg($color) {
    return "background: linear-gradient(135deg, {$color}15 0%, {$color}08 100%);";
}

function getBorderColor($color) {
    return $color . '60';
}

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['add_sport'])) {
        $sportName = trim($_POST['sport_name']);
        if (!empty($sportName)) {
            $stmt = $pdo->prepare("INSERT IGNORE INTO figure_sports (sport_name) VALUES (?)");
            if ($stmt->execute([$sportName])) {
                $message = '<div class="alert alert-success">Sport added successfully.</div>';
            } else {
                $message = '<div class="alert alert-danger">Error adding sport.</div>';
            }
        }
    }
    
    if (isset($_POST['update_sport_details'])) {
        $sportId = $_POST['sport_id'];
        $sportName = $_POST['sport_name'];
        
        try {
            $pdo->beginTransaction();
            
            // Handle file uploads
            $uploadDir = '../uploads/sports/';
            if (!file_exists($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }
            
            $iconPath = null;
            $mascotPaths = [
                'neutral' => null,
                'happy' => null,
                'sad' => null,
                'asking' => null
            ];
            
            // Handle icon upload
            if (isset($_FILES['icon_file']) && $_FILES['icon_file']['error'] === UPLOAD_ERR_OK) {
                $iconName = 'icon_' . $sportId . '_' . time() . '.' . pathinfo($_FILES['icon_file']['name'], PATHINFO_EXTENSION);
                if (move_uploaded_file($_FILES['icon_file']['tmp_name'], $uploadDir . $iconName)) {
                    $iconPath = 'uploads/sports/' . $iconName;
                }
            }
            
            // Handle mascot uploads
            foreach (['neutral', 'happy', 'sad', 'asking'] as $emotion) {
                $fieldName = 'mascot_' . $emotion;
                if (isset($_FILES[$fieldName]) && $_FILES[$fieldName]['error'] === UPLOAD_ERR_OK) {
                    $mascotName = 'mascot_' . $emotion . '_' . $sportId . '_' . time() . '.' . pathinfo($_FILES[$fieldName]['name'], PATHINFO_EXTENSION);
                    if (move_uploaded_file($_FILES[$fieldName]['tmp_name'], $uploadDir . $mascotName)) {
                        $mascotPaths[$emotion] = 'uploads/sports/' . $mascotName;
                    }
                }
            }
            
            // Update basic sport info
            $updateSport = $pdo->prepare("UPDATE figure_sports SET sport_name = ? WHERE id = ?");
            $updateSport->execute([$sportName, $sportId]);
            
            // Update or insert sport details
            $sqlFields = [
                'sport_id', 'slug', 'short_name', 'description', 'family', 'environment', 'team_mode', 
                'judged', 'time_based', 'distance_based', 'primary_metric', 'course_notes', 'risk_level', 
                'min_age', 'max_age', 'supported_genders', 'sanctioning_bodies', 'rulebook_url', 
                'brand_color_hex', 'seo_title', 'seo_description', 'display_order', 'required_equipment', 'protective_gear_required'
            ];
            
            $sqlValues = [];
            $updateClauses = [];
            
            // Add file fields if they have values
            if ($iconPath) {
                $sqlFields[] = 'icon_path';
                $sqlValues[] = $iconPath;
                $updateClauses[] = 'icon_path = VALUES(icon_path)';
            }
            
            foreach ($mascotPaths as $emotion => $path) {
                if ($path) {
                    $field = 'mascot_' . $emotion;
                    $sqlFields[] = $field;
                    $sqlValues[] = $path;
                    $updateClauses[] = "$field = VALUES($field)";
                }
            }
            
            $placeholders = str_repeat('?,', count($sqlFields));
            $placeholders = rtrim($placeholders, ',');
            
            $baseUpdateClauses = [
                'slug = VALUES(slug)', 'short_name = VALUES(short_name)', 'description = VALUES(description)',
                'family = VALUES(family)', 'environment = VALUES(environment)', 'team_mode = VALUES(team_mode)',
                'judged = VALUES(judged)', 'time_based = VALUES(time_based)', 'distance_based = VALUES(distance_based)',
                'primary_metric = VALUES(primary_metric)', 'course_notes = VALUES(course_notes)', 
                'risk_level = VALUES(risk_level)', 'min_age = VALUES(min_age)', 'max_age = VALUES(max_age)',
                'supported_genders = VALUES(supported_genders)', 'sanctioning_bodies = VALUES(sanctioning_bodies)', 
                'rulebook_url = VALUES(rulebook_url)', 'brand_color_hex = VALUES(brand_color_hex)', 
                'seo_title = VALUES(seo_title)', 'seo_description = VALUES(seo_description)', 
                'display_order = VALUES(display_order)', 'required_equipment = VALUES(required_equipment)', 
                'protective_gear_required = VALUES(protective_gear_required)'
            ];
            
            $allUpdateClauses = array_merge($baseUpdateClauses, $updateClauses);
            
            $updateDetails = $pdo->prepare("
                INSERT INTO figure_sport_details (" . implode(', ', $sqlFields) . ")
                VALUES ($placeholders)
                ON DUPLICATE KEY UPDATE " . implode(', ', $allUpdateClauses) . "
            ");
            
            // Prepare JSON arrays
            $sanctioningBodies = !empty($_POST['sanctioning_bodies']) ? 
                json_encode(array_filter(explode(',', $_POST['sanctioning_bodies']))) : null;
            
            $supportedGenders = !empty($_POST['supported_genders']) ? 
                implode(',', $_POST['supported_genders']) : 'Open';
            
            $environment = !empty($_POST['environment']) ? 
                implode(',', $_POST['environment']) : 'outdoor';
                
            // Handle equipment JSON arrays
            $requiredEquipment = !empty($_POST['required_equipment']) ? 
                json_encode(array_filter(explode(',', $_POST['required_equipment']))) : null;
                
            $protectiveGear = !empty($_POST['protective_gear_required']) ? 
                json_encode(array_filter(explode(',', $_POST['protective_gear_required']))) : null;
            
            $baseValues = [
                $sportId,
                $_POST['slug'] ?: $sportName,
                $_POST['short_name'] ?: ucfirst($sportName),
                $_POST['description'],
                $_POST['family'],
                $environment,
                $_POST['team_mode'],
                isset($_POST['judged']) ? 1 : 0,
                isset($_POST['time_based']) ? 1 : 0,
                isset($_POST['distance_based']) ? 1 : 0,
                $_POST['primary_metric'],
                $_POST['course_notes'],
                $_POST['risk_level'],
                !empty($_POST['min_age']) ? (int)$_POST['min_age'] : null,
                !empty($_POST['max_age']) ? (int)$_POST['max_age'] : null,
                $supportedGenders,
                $sanctioningBodies,
                $_POST['rulebook_url'],
                $_POST['brand_color_hex'],
                $_POST['seo_title'],
                $_POST['seo_description'],
                (int)$_POST['display_order'],
                $requiredEquipment,
                $protectiveGear
            ];
            
            $executeValues = array_merge($baseValues, $sqlValues);
            $updateDetails->execute($executeValues);
            
            $pdo->commit();
            $message = '<div class="alert alert-success">Sport details updated successfully.</div>';
        } catch (PDOException $e) {
            $pdo->rollback();
            $message = '<div class="alert alert-danger">Error updating sport details: ' . $e->getMessage() . '</div>';
        }
    }
    
    if (isset($_POST['add_category'])) {
        $sportName = $_POST['sport_name'];
        $categoryName = trim($_POST['category_name']);
        if (!empty($categoryName)) {
            $stmt = $pdo->prepare("INSERT IGNORE INTO figure_categories (sport_name, category_name) VALUES (?, ?)");
            if ($stmt->execute([$sportName, $categoryName])) {
                $message = '<div class="alert alert-success">Category added successfully.</div>';
            } else {
                $message = '<div class="alert alert-danger">Error adding category.</div>';
            }
        }
    }
    
    if (isset($_POST['add_item'])) {
        $sportName = $_POST['sport_name'];
        $categoryName = $_POST['category_name'];
        $itemName = trim($_POST['item_name']);
        if (!empty($itemName)) {
            $stmt = $pdo->prepare("INSERT INTO figure_items (sport_name, category_name, item_name) VALUES (?, ?, ?)");
            if ($stmt->execute([$sportName, $categoryName, $itemName])) {
                $message = '<div class="alert alert-success">Figure item added successfully.</div>';
            } else {
                $message = '<div class="alert alert-danger">Error adding figure item.</div>';
            }
        }
    }
    
    if (isset($_POST['toggle_sport'])) {
        $sportName = $_POST['sport_name'];
        $isActive = (int)$_POST['is_active'];
        $stmt = $pdo->prepare("UPDATE figure_sports SET is_active = ? WHERE sport_name = ?");
        $stmt->execute([$isActive, $sportName]);
        $message = '<div class="alert alert-success">Sport status updated.</div>';
    }
    
    if (isset($_POST['delete_item'])) {
        $itemId = $_POST['item_id'];
        $stmt = $pdo->prepare("DELETE FROM figure_items WHERE id = ?");
        if ($stmt->execute([$itemId])) {
            $message = '<div class="alert alert-success">Figure item deleted successfully.</div>';
        }
    }
}

// Load sports with their categories, items, and details
$sports = $pdo->query("
    SELECT fs.*, fsd.*, 
           COUNT(DISTINCT fc.id) as category_count,
           COUNT(fi.id) as item_count
    FROM figure_sports fs
    LEFT JOIN figure_sport_details fsd ON fs.id = fsd.sport_id
    LEFT JOIN figure_categories fc ON fs.sport_name = fc.sport_name
    LEFT JOIN figure_items fi ON fs.sport_name = fi.sport_name
    GROUP BY fs.id
    ORDER BY COALESCE(fsd.display_order, fs.id * 10), fs.sport_name
")->fetchAll(PDO::FETCH_ASSOC);

$selectedSport = $_GET['sport'] ?? ($sports[0]['sport_name'] ?? '');
$editMode = isset($_GET['edit']) && $_GET['edit'] == 'sport';
$editSportData = null;

// If in edit mode, get the sport data for editing
if ($editMode && $selectedSport) {
    $editStmt = $pdo->prepare("
        SELECT fs.*, fsd.*
        FROM figure_sports fs
        LEFT JOIN figure_sport_details fsd ON fs.id = fsd.sport_id
        WHERE fs.sport_name = ?
    ");
    $editStmt->execute([$selectedSport]);
    $editSportData = $editStmt->fetch(PDO::FETCH_ASSOC);
}

// Load categories for selected sport
$categories = [];
$figures = [];
if ($selectedSport) {
    $categories = $pdo->prepare("
        SELECT fc.*, COUNT(fi.id) as item_count
        FROM figure_categories fc
        LEFT JOIN figure_items fi ON fc.sport_name = fi.sport_name AND fc.category_name = fi.category_name
        WHERE fc.sport_name = ?
        GROUP BY fc.id
        ORDER BY fc.sort_order, fc.category_name
    ");
    $categories->execute([$selectedSport]);
    $categories = $categories->fetchAll(PDO::FETCH_ASSOC);
    
    // Load all figures for selected sport
    $figures = $pdo->prepare("
        SELECT fi.*, fc.sort_order as cat_sort_order
        FROM figure_items fi
        JOIN figure_categories fc ON fi.sport_name = fc.sport_name AND fi.category_name = fc.category_name
        WHERE fi.sport_name = ?
        ORDER BY fc.sort_order, fi.category_name, fi.sort_order, fi.item_name
    ");
    $figures->execute([$selectedSport]);
    $figuresByCategory = [];
    foreach ($figures->fetchAll(PDO::FETCH_ASSOC) as $figure) {
        $figuresByCategory[$figure['category_name']][] = $figure;
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Figures Management - Style Score Admin</title>
    <?php include_once '../includes/stylesheets.php'; ?>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
       
        
        .sport-card {
            transition: all 0.2s ease;
            border: none;
        }
        .sport-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        .sport-card.active {
            border-color: #0d6efd;
            background-color: rgb(13 110 253 / 68%);
        }
        .sport-card a {
            cursor: pointer;
        }
        .sport-card a:hover {
            color: inherit;
        }
        .figure-item {
            background: #f8f9fa;
            border-radius: 4px;
            padding: 0.5rem;
            margin: 0.25rem 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: transform 0.2s ease;
        }
        .figure-item:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .category-section {
            border-left: 4px solid #6f42c1;
            padding-left: 1rem;
            margin-bottom: 1.5rem;
        }
        .current-icon img {
    background: #777777;
    padding: 9px;
}
    </style>
</head>
<body class="body-bg-aurora-bright">
    <?php include '../menu.php'; ?>
    
    <div class="container-fluid container-StyleScore p-4">
        <?php       
            $use_localStorage = true;
            $show_header = false;
            include 'event_actions_menu.php'; 
            ?>
        <div class="row justify-content-center">
            <div class="col-10">
                <!-- Header -->
                <div class="border-0 shadow-none card border-0 shadow-sm mb-3">
                    <div class="border-0 shadow-none card-body py-2">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h4 class="mb-1">
                                    <i class="fas fa-shapes text-primary me-2"></i>Figures Management
                                </h4>
                                <small class="text-muted">Manage sports, categories, and figure items</small>
                            </div>
                            <div class="d-flex gap-1">
                                <button class="btn btn-outline-info btn-sm" data-bs-toggle="modal" data-bs-target="#helpModal">
                                    <i class="fas fa-question-circle me-1"></i>Help
                                </button>
                                <a href="scoring_formats.php" class="btn btn-outline-secondary btn-sm me-1">
                                    <i class="fas fa-arrow-left"></i>
                                </a>
                                <a href="figures_viewer.php" class="btn btn-primary btn-sm">
                                    <i class="fas fa-book me-1"></i>Dictionary
                                </a>
                            </div>
                        </div>
                    </div>
                </div>

                <?= $message ?>

                <div class="row g-2">
                    <!-- Sports Selection -->
                    <div class="col-lg-3">
                        <div class="border-0 shadow-none card border">
                            <div class="border-0 shadow-none card-header bg-light py-2 d-flex justify-content-between align-items-center">
                                <h6 class="mb-0">
                                    <i class="fas fa-medal me-1 text-primary"></i>Sports
                                </h6>
                                <button class="btn btn-success btn-sm" data-bs-toggle="modal" data-bs-target="#addSportModal">
                                    <i class="fas fa-plus"></i>
                                </button>
                            </div>
                            <div class="border-0 shadow-none card-body p-0">
                                <div class="list-group list-group-flush">
                                    <?php foreach ($sports as $sport): ?>
                                        <?php 
                                        $brandColor = $sport['brand_color_hex'] ?? '#6c757d';
                                        $iconPath = $sport['icon_path'] ?? '';
                                        $sportSlug = str_replace(' ', '-', strtolower($sport['sport_name']));
                                        $uniqueClass = 'sport-' . $sportSlug . '-' . substr(md5($sport['sport_name']), 0, 8);
                                        $isSelected = $sport['sport_name'] === $selectedSport;
                                        
                                        // Generate dynamic styles for this sport
                                        if (!empty($brandColor)):
                                        ?>
                                        <style>
                                            .<?= $uniqueClass ?>-bg {
                                                background: linear-gradient(135deg, <?= $brandColor ?>15 0%, <?= $brandColor ?>08 100%);
                                                border-left: 3px solid <?= $brandColor ?>60;
                                            }
                                            .<?= $uniqueClass ?>-active {
                                                background: linear-gradient(135deg, <?= $brandColor ?>25 0%, <?= $brandColor ?>15 100%);
                                                border-left: 3px solid <?= $brandColor ?>;
                                            }
                                            .<?= $uniqueClass ?>-text {
                                                color: <?= $brandColor ?> !important;
                                            }
                                            .<?= $uniqueClass ?>-icon svg {
                                                fill: <?= $brandColor ?> !important;
                                            }
                                        </style>
                                        <?php endif; ?>
                                        
                                        <div class="list-group-item <?= $isSelected ? $uniqueClass . '-active' : $uniqueClass . '-bg' ?> p-2">
                                            <div class="d-flex justify-content-between align-items-center">
                                                <a href="?sport=<?= $sport['sport_name'] ?>" class="flex-grow-1 text-decoration-none text-reset">
                                                    <div class="d-flex align-items-center">
                                                        <?php if (!empty($iconPath)): ?>
                                                            <div class="me-2 <?= $uniqueClass ?>-icon" style="width: 20px; height: 20px;">
                                                                <?= getSvgWithColor($iconPath, $brandColor, $uniqueClass) ?>
                                                            </div>
                                                        <?php else: ?>
                                                            <i class="fas fa-medal me-2 <?= $uniqueClass ?>-text"></i>
                                                        <?php endif; ?>
                                                        <div>
                                                            <div class="fw-bold <?= $uniqueClass ?>-text">
                                                                <?= htmlspecialchars(ucfirst($sport['sport_name'])) ?>
                                                            </div>
                                                            <small class="text-muted">
                                                                <?= $sport['category_count'] ?> categories • <?= $sport['item_count'] ?> items
                                                            </small>
                                                        </div>
                                                    </div>
                                                </a>
                                                <div class="d-flex align-items-center gap-1">
                                                    <?php if ($sport['is_active']): ?>
                                                        <span class="badge bg-success badge-sm">Active</span>
                                                    <?php else: ?>
                                                        <span class="badge bg-secondary badge-sm">Inactive</span>
                                                    <?php endif; ?>
                                                    
                                                    <a href="?sport=<?= $sport['sport_name'] ?>&edit=sport" 
                                                       class="btn btn-sm btn-outline-primary"
                                                       title="Edit Sport Details">
                                                        <i class="fas fa-edit"></i>
                                                    </a>
                                                    
                                                    <form method="POST" class="d-inline">
                                                        <input type="hidden" name="sport_name" value="<?= $sport['sport_name'] ?>">
                                                        <input type="hidden" name="is_active" value="<?= $sport['is_active'] ? 0 : 1 ?>">
                                                        <button type="submit" name="toggle_sport" 
                                                                class="btn btn-sm <?= $sport['is_active'] ? 'btn-outline-warning' : 'btn-outline-success' ?>"
                                                                title="<?= $sport['is_active'] ? 'Deactivate' : 'Activate' ?>">
                                                            <i class="fas <?= $sport['is_active'] ? 'fa-pause' : 'fa-play' ?>"></i>
                                                        </button>
                                                    </form>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Categories and Figures / Edit Panel -->
                    <div class="col-lg-9">
                        <?php if ($editMode && $editSportData): ?>
                            <!-- Sport Edit Panel -->
                            <div class="border-0 shadow-none card border-warning">
                                <div class="border-0 shadow-none card-header bg-warning bg-opacity-10 py-2">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <h6 class="mb-0 text-warning">
                                            <i class="fas fa-edit me-1"></i>
                                            Edit: <?= htmlspecialchars($editSportData['sport_name']) ?>
                                        </h6>
                                        <a href="?sport=<?= htmlspecialchars($selectedSport) ?>" class="btn btn-outline-secondary btn-sm">
                                            <i class="fas fa-times"></i>
                                        </a>
                                    </div>
                                </div>
                                <div class="border-0 shadow-none card-body p-3">
                                    <form method="POST" enctype="multipart/form-data">
                                        <input type="hidden" name="sport_id" value="<?= $editSportData['id'] ?>">
                                        <div class="row g-3">
                                            <!-- Basic Information -->
                                            <div class="col-md-6">
                                                <div class="border-0 shadow-none card border">
                                                    <div class="border-0 shadow-none card-header bg-light py-1">
                                                        <h6 class="mb-0 small"><i class="fas fa-info-circle me-1"></i>Basic Information</h6>
                                                    </div>
                                                    <div class="border-0 shadow-none card-body p-2">
                                                        <div class="mb-2">
                                                            <label class="form-label small fw-bold">Sport Name *</label>
                                                            <input type="text" class="form-control form-control-sm" name="sport_name" value="<?= htmlspecialchars($editSportData['sport_name'] ?? '') ?>" required>
                                                        </div>
                                                        <div class="mb-2">
                                                            <label class="form-label small fw-bold">Short Name</label>
                                                            <input type="text" class="form-control form-control-sm" name="short_name" value="<?= htmlspecialchars($editSportData['short_name'] ?? '') ?>">
                                                        </div>
                                                        <div class="mb-2">
                                                            <label class="form-label small fw-bold">Slug</label>
                                                            <input type="text" class="form-control form-control-sm" name="slug" value="<?= htmlspecialchars($editSportData['slug'] ?? '') ?>">
                                                            <div class="form-text">URL-friendly identifier</div>
                                                        </div>
                                                        <div class="mb-3">
                                                            <label class="form-label fw-bold">Description</label>
                                                            <textarea class="form-control" name="description" rows="3"><?= htmlspecialchars($editSportData['description'] ?? '') ?></textarea>
                                                        </div>
                                                        <div class="mb-3">
                                                            <label class="form-label fw-bold">Brand Color</label>
                                                            <input type="color" class="form-control form-control-color" name="brand_color_hex" value="<?= htmlspecialchars($editSportData['brand_color_hex'] ?? '#6C757D') ?>">
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>

                                            <!-- Sport Classification -->
                                            <div class="col-md-6">
                                                <div class="border-0 shadow-none card">
                                                    <div class="border-0 shadow-none card-header">
                                                        <h6 class="mb-0"><i class="fas fa-tags me-2"></i>Classification</h6>
                                                    </div>
                                                    <div class="border-0 shadow-none card-body">
                                                        <div class="mb-3">
                                                            <label class="form-label fw-bold">Family *</label>
                                                            <select class="form-select" name="family" required>
                                                                <option value="bike" <?= ($editSportData['family'] ?? '') === 'bike' ? 'selected' : '' ?>>Bike</option>
                                                                <option value="ski" <?= ($editSportData['family'] ?? '') === 'ski' ? 'selected' : '' ?>>Ski</option>
                                                                <option value="board" <?= ($editSportData['family'] ?? '') === 'board' ? 'selected' : '' ?>>Board</option>
                                                                <option value="parkour" <?= ($editSportData['family'] ?? '') === 'parkour' ? 'selected' : '' ?>>Parkour</option>
                                                                <option value="surf" <?= ($editSportData['family'] ?? '') === 'surf' ? 'selected' : '' ?>>Surf</option>
                                                                <option value="dance" <?= ($editSportData['family'] ?? '') === 'dance' ? 'selected' : '' ?>>Dance</option>
                                                                <option value="other" <?= ($editSportData['family'] ?? '') === 'other' ? 'selected' : '' ?>>Other</option>
                                                            </select>
                                                        </div>
                                                        <div class="mb-3">
                                                            <label class="form-label fw-bold">Environment *</label>
                                                            <div class="row">
                                                                <?php 
                                                                $environments = explode(',', $editSportData['environment'] ?? 'outdoor');
                                                                ?>
                                                                <div class="col-6">
                                                                    <div class="form-check">
                                                                        <input class="form-check-input" type="checkbox" name="environment[]" value="snow" <?= in_array('snow', $environments) ? 'checked' : '' ?>>
                                                                        <label class="form-check-label">Snow</label>
                                                                    </div>
                                                                    <div class="form-check">
                                                                        <input class="form-check-input" type="checkbox" name="environment[]" value="water" <?= in_array('water', $environments) ? 'checked' : '' ?>>
                                                                        <label class="form-check-label">Water</label>
                                                                    </div>
                                                                    <div class="form-check">
                                                                        <input class="form-check-input" type="checkbox" name="environment[]" value="street" <?= in_array('street', $environments) ? 'checked' : '' ?>>
                                                                        <label class="form-check-label">Street</label>
                                                                    </div>
                                                                </div>
                                                                <div class="col-6">
                                                                    <div class="form-check">
                                                                        <input class="form-check-input" type="checkbox" name="environment[]" value="park" <?= in_array('park', $environments) ? 'checked' : '' ?>>
                                                                        <label class="form-check-label">Park</label>
                                                                    </div>
                                                                    <div class="form-check">
                                                                        <input class="form-check-input" type="checkbox" name="environment[]" value="indoor" <?= in_array('indoor', $environments) ? 'checked' : '' ?>>
                                                                        <label class="form-check-label">Indoor</label>
                                                                    </div>
                                                                    <div class="form-check">
                                                                        <input class="form-check-input" type="checkbox" name="environment[]" value="outdoor" <?= in_array('outdoor', $environments) ? 'checked' : '' ?>>
                                                                        <label class="form-check-label">Outdoor</label>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div class="mb-3">
                                                            <label class="form-label fw-bold">Risk Level</label>
                                                            <select class="form-select" name="risk_level">
                                                                <option value="low" <?= ($editSportData['risk_level'] ?? '') === 'low' ? 'selected' : '' ?>>Low</option>
                                                                <option value="medium" <?= ($editSportData['risk_level'] ?? '') === 'medium' ? 'selected' : '' ?>>Medium</option>
                                                                <option value="high" <?= ($editSportData['risk_level'] ?? '') === 'high' ? 'selected' : '' ?>>High</option>
                                                            </select>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>

                                            <!-- Competition Settings -->
                                            <div class="col-md-6">
                                                <div class="border-0 shadow-none card">
                                                    <div class="border-0 shadow-none card-header">
                                                        <h6 class="mb-0"><i class="fas fa-trophy me-2"></i>Competition Settings</h6>
                                                    </div>
                                                    <div class="border-0 shadow-none card-body">
                                                        <div class="mb-3">
                                                            <label class="form-label fw-bold">Team Mode</label>
                                                            <select class="form-select" name="team_mode">
                                                                <option value="individual" <?= ($editSportData['team_mode'] ?? '') === 'individual' ? 'selected' : '' ?>>Individual</option>
                                                                <option value="team" <?= ($editSportData['team_mode'] ?? '') === 'team' ? 'selected' : '' ?>>Team</option>
                                                                <option value="both" <?= ($editSportData['team_mode'] ?? '') === 'both' ? 'selected' : '' ?>>Both</option>
                                                            </select>
                                                        </div>
                                                        <div class="mb-3">
                                                            <div class="form-check">
                                                                <input class="form-check-input" type="checkbox" name="judged" <?= ($editSportData['judged'] ?? 0) == 1 ? 'checked' : '' ?>>
                                                                <label class="form-check-label fw-bold">Judged Sport</label>
                                                            </div>
                                                        </div>
                                                        <div class="mb-3">
                                                            <div class="form-check">
                                                                <input class="form-check-input" type="checkbox" name="time_based" <?= ($editSportData['time_based'] ?? 0) == 1 ? 'checked' : '' ?>>
                                                                <label class="form-check-label fw-bold">Time Based</label>
                                                            </div>
                                                        </div>
                                                        <div class="mb-3">
                                                            <div class="form-check">
                                                                <input class="form-check-input" type="checkbox" name="distance_based" <?= ($editSportData['distance_based'] ?? 0) == 1 ? 'checked' : '' ?>>
                                                                <label class="form-check-label fw-bold">Distance Based</label>
                                                            </div>
                                                        </div>
                                                        <div class="mb-3">
                                                            <label class="form-label fw-bold">Primary Metric</label>
                                                            <select class="form-select" name="primary_metric">
                                                                <option value="score" <?= ($editSportData['primary_metric'] ?? '') === 'score' ? 'selected' : '' ?>>Score</option>
                                                                <option value="time" <?= ($editSportData['primary_metric'] ?? '') === 'time' ? 'selected' : '' ?>>Time</option>
                                                                <option value="distance" <?= ($editSportData['primary_metric'] ?? '') === 'distance' ? 'selected' : '' ?>>Distance</option>
                                                                <option value="height" <?= ($editSportData['primary_metric'] ?? '') === 'height' ? 'selected' : '' ?>>Height</option>
                                                            </select>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>

                                            <!-- Display Settings -->
                                            <div class="col-md-6">
                                                <div class="border-0 shadow-none card">
                                                    <div class="border-0 shadow-none card-header">
                                                        <h6 class="mb-0"><i class="fas fa-cog me-2"></i>Display Settings</h6>
                                                    </div>
                                                    <div class="border-0 shadow-none card-body">
                                                        <div class="mb-3">
                                                            <label class="form-label fw-bold">Display Order</label>
                                                            <input type="number" class="form-control" name="display_order" value="<?= htmlspecialchars($editSportData['display_order'] ?? '') ?>">
                                                        </div>
                                                        <div class="mb-3">
                                                            <label class="form-label fw-bold">Icon</label>
                                                            <input type="file" class="form-control" name="icon_file" accept="image/*">
                                                            <div class="form-text">Upload sport icon image (PNG, JPG, SVG recommended)</div>
                                                            <?php if (!empty($editSportData['icon_path'])): ?>
                                                                <div class="mt-2 current-icon">
                                                                    <img src="../<?= htmlspecialchars($editSportData['icon_path']) ?>" alt="Current icon" style="max-width: 80px; max-height: 80px;">
                                                                    <small class="text-muted ms-2">Current icon</small>
                                                                </div>
                                                            <?php endif; ?>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>

                                            <!-- Continue with remaining sections... -->
                                            <!-- Equipment & Requirements -->
                                            <div class="col-md-6">
                                                <div class="border-0 shadow-none card">
                                                    <div class="border-0 shadow-none card-header">
                                                        <h6 class="mb-0"><i class="fas fa-shield-alt me-2"></i>Equipment & Requirements</h6>
                                                    </div>
                                                    <div class="border-0 shadow-none card-body">
                                                        <div class="mb-3">
                                                            <label class="form-label fw-bold">Required Equipment</label>
                                                            <?php 
                                                            $requiredEquipment = '';
                                                            if (!empty($editSportData['required_equipment'])) {
                                                                $equipment = json_decode($editSportData['required_equipment'], true);
                                                                $requiredEquipment = is_array($equipment) ? implode(', ', $equipment) : $editSportData['required_equipment'];
                                                            }
                                                            ?>
                                                            <input type="text" class="form-control" name="required_equipment" value="<?= htmlspecialchars($requiredEquipment) ?>">
                                                            <div class="form-text">Comma-separated list (e.g., board, bindings, boots, helmet)</div>
                                                        </div>
                                                        <div class="mb-3">
                                                            <label class="form-label fw-bold">Protective Gear Required</label>
                                                            <?php 
                                                            $protectiveGear = '';
                                                            if (!empty($editSportData['protective_gear_required'])) {
                                                                $gear = json_decode($editSportData['protective_gear_required'], true);
                                                                $protectiveGear = is_array($gear) ? implode(', ', $gear) : $editSportData['protective_gear_required'];
                                                            }
                                                            ?>
                                                            <input type="text" class="form-control" name="protective_gear_required" value="<?= htmlspecialchars($protectiveGear) ?>">
                                                            <div class="form-text">Comma-separated list (e.g., helmet, back_protector)</div>
                                                        </div>
                                                        <div class="row">
                                                            <div class="col-6">
                                                                <div class="mb-3">
                                                                    <label class="form-label fw-bold">Min Age</label>
                                                                    <input type="number" class="form-control" name="min_age" value="<?= htmlspecialchars($editSportData['min_age'] ?? '') ?>" min="0" max="100">
                                                                </div>
                                                            </div>
                                                            <div class="col-6">
                                                                <div class="mb-3">
                                                                    <label class="form-label fw-bold">Max Age</label>
                                                                    <input type="number" class="form-control" name="max_age" value="<?= htmlspecialchars($editSportData['max_age'] ?? '') ?>" min="0" max="100">
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div class="mb-3">
                                                            <label class="form-label fw-bold">Supported Genders</label>
                                                            <?php 
                                                            $supportedGenders = explode(',', $editSportData['supported_genders'] ?? 'Open');
                                                            ?>
                                                            <div class="row">
                                                                <div class="col-6">
                                                                    <div class="form-check">
                                                                        <input class="form-check-input" type="checkbox" name="supported_genders[]" value="M" <?= in_array('M', $supportedGenders) ? 'checked' : '' ?>>
                                                                        <label class="form-check-label">Male</label>
                                                                    </div>
                                                                    <div class="form-check">
                                                                        <input class="form-check-input" type="checkbox" name="supported_genders[]" value="F" <?= in_array('F', $supportedGenders) ? 'checked' : '' ?>>
                                                                        <label class="form-check-label">Female</label>
                                                                    </div>
                                                                </div>
                                                                <div class="col-6">
                                                                    <div class="form-check">
                                                                        <input class="form-check-input" type="checkbox" name="supported_genders[]" value="Open" <?= in_array('Open', $supportedGenders) ? 'checked' : '' ?>>
                                                                        <label class="form-check-label">Open</label>
                                                                    </div>
                                                                    <div class="form-check">
                                                                        <input class="form-check-input" type="checkbox" name="supported_genders[]" value="X" <?= in_array('X', $supportedGenders) ? 'checked' : '' ?>>
                                                                        <label class="form-check-label">Non-binary</label>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>

                                            <!-- Additional Information -->
                                            <div class="col-md-6">
                                                <div class="border-0 shadow-none card">
                                                    <div class="border-0 shadow-none card-header">
                                                        <h6 class="mb-0"><i class="fas fa-info me-2"></i>Additional Information</h6>
                                                    </div>
                                                    <div class="border-0 shadow-none card-body">
                                                        <div class="mb-3">
                                                            <label class="form-label fw-bold">Course Notes</label>
                                                            <textarea class="form-control" name="course_notes" rows="2"><?= htmlspecialchars($editSportData['course_notes'] ?? '') ?></textarea>
                                                        </div>
                                                        <div class="mb-3">
                                                            <label class="form-label fw-bold">Sanctioning Bodies</label>
                                                            <?php 
                                                            $sanctioningBodies = '';
                                                            if (!empty($editSportData['sanctioning_bodies'])) {
                                                                $bodies = json_decode($editSportData['sanctioning_bodies'], true);
                                                                $sanctioningBodies = is_array($bodies) ? implode(', ', $bodies) : $editSportData['sanctioning_bodies'];
                                                            }
                                                            ?>
                                                            <input type="text" class="form-control" name="sanctioning_bodies" value="<?= htmlspecialchars($sanctioningBodies) ?>">
                                                            <div class="form-text">Comma-separated list (e.g., FIS, WSL, UCI)</div>
                                                        </div>
                                                        <div class="mb-3">
                                                            <label class="form-label fw-bold">Rulebook URL</label>
                                                            <input type="url" class="form-control" name="rulebook_url" value="<?= htmlspecialchars($editSportData['rulebook_url'] ?? '') ?>">
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>

                                            <!-- Mascot Images -->
                                            <div class="col-md-6">
                                                <div class="border-0 shadow-none card">
                                                    <div class="border-0 shadow-none card-header">
                                                        <h6 class="mb-0"><i class="fas fa-smile me-2"></i>Mascot Images</h6>
                                                    </div>
                                                    <div class="border-0 shadow-none card-body">
                                                        <div class="mb-3">
                                                            <label class="form-label fw-bold">Neutral Mascot</label>
                                                            <input type="file" class="form-control" name="mascot_neutral" accept="image/*">
                                                            <?php if (!empty($editSportData['mascot_neutral'])): ?>
                                                                <div class="mt-2">
                                                                    <img src="../<?= htmlspecialchars($editSportData['mascot_neutral']) ?>" alt="Current neutral mascot" style="max-width: 50px; max-height: 50px;">
                                                                    <small class="text-muted ms-2">Current neutral mascot</small>
                                                                </div>
                                                            <?php endif; ?>
                                                        </div>
                                                        <div class="mb-3">
                                                            <label class="form-label fw-bold">Happy Mascot</label>
                                                            <input type="file" class="form-control" name="mascot_happy" accept="image/*">
                                                            <?php if (!empty($editSportData['mascot_happy'])): ?>
                                                                <div class="mt-2">
                                                                    <img src="../<?= htmlspecialchars($editSportData['mascot_happy']) ?>" alt="Current happy mascot" style="max-width: 50px; max-height: 50px;">
                                                                    <small class="text-muted ms-2">Current happy mascot</small>
                                                                </div>
                                                            <?php endif; ?>
                                                        </div>
                                                        <div class="mb-3">
                                                            <label class="form-label fw-bold">Sad Mascot</label>
                                                            <input type="file" class="form-control" name="mascot_sad" accept="image/*">
                                                            <?php if (!empty($editSportData['mascot_sad'])): ?>
                                                                <div class="mt-2">
                                                                    <img src="../<?= htmlspecialchars($editSportData['mascot_sad']) ?>" alt="Current sad mascot" style="max-width: 50px; max-height: 50px;">
                                                                    <small class="text-muted ms-2">Current sad mascot</small>
                                                                </div>
                                                            <?php endif; ?>
                                                        </div>
                                                        <div class="mb-3">
                                                            <label class="form-label fw-bold">Asking Mascot</label>
                                                            <input type="file" class="form-control" name="mascot_asking" accept="image/*">
                                                            <?php if (!empty($editSportData['mascot_asking'])): ?>
                                                                <div class="mt-2">
                                                                    <img src="../<?= htmlspecialchars($editSportData['mascot_asking']) ?>" alt="Current asking mascot" style="max-width: 50px; max-height: 50px;">
                                                                    <small class="text-muted ms-2">Current asking mascot</small>
                                                                </div>
                                                            <?php endif; ?>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>

                                            <!-- SEO -->
                                            <div class="col-md-12">
                                                <div class="border-0 shadow-none card">
                                                    <div class="border-0 shadow-none card-header">
                                                        <h6 class="mb-0"><i class="fas fa-search me-2"></i>SEO & Meta</h6>
                                                    </div>
                                                    <div class="border-0 shadow-none card-body">
                                                        <div class="row">
                                                            <div class="col-md-6">
                                                                <div class="mb-3">
                                                                    <label class="form-label fw-bold">SEO Title</label>
                                                                    <input type="text" class="form-control" name="seo_title" value="<?= htmlspecialchars($editSportData['seo_title'] ?? '') ?>" maxlength="150">
                                                                </div>
                                                            </div>
                                                            <div class="col-md-6">
                                                                <div class="mb-3">
                                                                    <label class="form-label fw-bold">SEO Description</label>
                                                                    <textarea class="form-control" name="seo_description" rows="2" maxlength="255"><?= htmlspecialchars($editSportData['seo_description'] ?? '') ?></textarea>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="row mt-4">
                                            <div class="col-12">
                                                <div class="d-flex justify-content-end gap-2">
                                                    <a href="?sport=<?= htmlspecialchars($selectedSport) ?>" class="btn btn-secondary">
                                                        <i class="fas fa-times me-1"></i>Cancel
                                                    </a>
                                                    <button type="submit" name="update_sport_details" class="btn btn-primary">
                                                        <i class="fas fa-save me-1"></i>Save Changes
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        <?php elseif ($selectedSport): ?>
                            <?php 
                            // Get sport details for styling
                            $currentSport = array_filter($sports, function($s) use ($selectedSport) {
                                return $s['sport_name'] === $selectedSport;
                            });
                            $currentSport = reset($currentSport);
                            $brandColor = $currentSport['brand_color_hex'] ?? '#6c757d';
                            $iconPath = $currentSport['icon_path'] ?? '';
                            $sportSlug = str_replace(' ', '-', strtolower($selectedSport));
                            $uniqueClass = 'sport-' . $sportSlug . '-' . substr(md5($selectedSport), 0, 8);
                            
                            // Generate dynamic styles for this sport
                            if (!empty($brandColor)):
                            ?>
                            <style>
                                .<?= $uniqueClass ?>-bg {
                                    background: linear-gradient(135deg, <?= $brandColor ?>15 0%, <?= $brandColor ?>08 100%);
                                    border-color: <?= $brandColor ?>40;
                                }
                                .<?= $uniqueClass ?>-text {
                                    color: <?= $brandColor ?> !important;
                                }
                                .<?= $uniqueClass ?>-icon svg {
                                    fill: <?= $brandColor ?> !important;
                                }
                            </style>
                            <?php endif; ?>
                            
                            <div class="border-0 shadow-none card border <?= !empty($brandColor) ? $uniqueClass . '-bg' : '' ?>">
                                <div class="border-0 shadow-none card-header bg-light py-2 d-flex justify-content-between align-items-center">
                                    <h6 class="mb-0 d-flex align-items-center">
                                        <?php if (!empty($iconPath)): ?>
                                            <div class="me-2 <?= $uniqueClass ?>-icon" style="width: 20px; height: 20px;">
                                                <?= getSvgWithColor($iconPath, $brandColor, $uniqueClass) ?>
                                            </div>
                                        <?php else: ?>
                                            <i class="fas fa-skating me-2 <?= !empty($brandColor) ? $uniqueClass . '-text' : 'text-primary' ?>"></i>
                                        <?php endif; ?>
                                        <span class="<?= !empty($brandColor) ? $uniqueClass . '-text' : '' ?>">
                                            <?= htmlspecialchars(ucfirst($selectedSport)) ?> Figures
                                        </span>
                                    </h6>
                                    <div class="btn-group">
                                        <button class="btn btn-outline-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addCategoryModal">
                                            <i class="fas fa-plus"></i> Category
                                        </button>
                                        <button class="btn btn-outline-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addItemModal">
                                            <i class="fas fa-plus"></i> Item
                                        </button>
                                    </div>
                                </div>
                                
                                <div class="border-0 shadow-none card-body p-2">
                                    <?php if (empty($categories)): ?>
                                        <div class="text-center py-4">
                                            <i class="fas fa-info-circle fa-2x text-muted mb-2"></i>
                                            <h6>No Categories Yet</h6>
                                            <p class="text-muted small mb-2">Add categories to organize figure items for this sport.</p>
                                            <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addCategoryModal">
                                                <i class="fas fa-plus me-1"></i>Add First Category
                                            </button>
                                        </div>
                                    <?php else: ?>
                                        <?php foreach ($categories as $category): ?>
                                            <div class="category-section mb-3">
                                                <div class="d-flex justify-content-between align-items-center mb-2">
                                                    <h6 class="text-primary mb-0 d-flex align-items-center">
                                                        <i class="fas fa-layer-group me-1"></i>
                                                        <?= htmlspecialchars($category['category_name']) ?>
                                                    </h6>
                                                    <span class="badge bg-info badge-sm"><?= $category['item_count'] ?> items</span>
                                                </div>
                                                
                                                <?php if (isset($figuresByCategory[$category['category_name']])): ?>
                                                    <div class="row g-1">
                                                        <?php foreach ($figuresByCategory[$category['category_name']] as $figure): ?>
                                                            <div class="col-md-6 col-lg-4">
                                                                <div class="figure-item border rounded p-2 d-flex justify-content-between align-items-center">
                                                                    <span class="flex-grow-1 fw-medium small"><?= htmlspecialchars($figure['item_name']) ?></span>
                                                                    <form method="POST" class="d-inline">
                                                                        <input type="hidden" name="item_id" value="<?= $figure['id'] ?>">
                                                                        <button type="submit" name="delete_item" 
                                                                                class="btn btn-sm btn-outline-danger"
                                                                                onclick="return confirm('Delete this item?')"
                                                                                title="Delete">
                                                                            <i class="fas fa-trash fa-xs"></i>
                                                                        </button>
                                                                    </form>
                                                                </div>
                                                            </div>
                                                        <?php endforeach; ?>
                                                    </div>
                                                <?php else: ?>
                                                    <p class="text-muted small mb-0 ms-3">No items in this category yet.</p>
                                                <?php endif; ?>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php else: ?>
                            <div class="border-0 shadow-none card border">
                                <div class="border-0 shadow-none card-body text-center py-4">
                                    <i class="fas fa-arrow-left fa-2x text-muted mb-2"></i>
                                    <h6>Select a Sport</h6>
                                    <p class="text-muted small mb-0">Choose a sport from the sidebar to manage its figure categories and items.</p>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Add Sport Modal -->
    <div class="modal fade" id="addSportModal" tabindex="-1">
        <div class="modal-dialog modal-sm">
            <div class="modal-content">
                <div class="modal-header py-2">
                    <h6 class="modal-title">
                        <i class="fas fa-plus me-1"></i>Add New Sport
                    </h6>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <div class="modal-body py-2">
                        <div class="mb-2">
                            <label class="form-label small fw-bold">Sport Name</label>
                            <input type="text" class="form-control form-control-sm" name="sport_name" required 
                                   placeholder="e.g., snowboard, skateboard">
                            <div class="form-text small">Enter the name of the sport in lowercase</div>
                        </div>
                    </div>
                    <div class="modal-footer py-2">
                        <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" name="add_sport" class="btn btn-success btn-sm">
                            <i class="fas fa-plus me-1"></i>Add Sport
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Add Category Modal -->
    <div class="modal fade" id="addCategoryModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-layer-group me-2"></i>Add New Category
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="sport_name" value="<?= htmlspecialchars($selectedSport) ?>">
                        <div class="mb-3">
                            <label class="form-label fw-bold">Category Name</label>
                            <input type="text" class="form-control form-control-lg" name="category_name" required 
                                   placeholder="e.g., Rotation, Direction, Grab">
                            <div class="form-text">Enter a descriptive category name for organizing figures</div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" name="add_category" class="btn btn-success">
                            <i class="fas fa-plus me-1"></i>Add Category
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Add Item Modal -->
    <div class="modal fade" id="addItemModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-puzzle-piece me-2"></i>Add New Figure Item
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="sport_name" value="<?= htmlspecialchars($selectedSport) ?>">
                        <div class="mb-3">
                            <label class="form-label fw-bold">Category</label>
                            <select class="form-select form-select-lg" name="category_name" required>
                                <option value="">-- Select Category --</option>
                                <?php foreach ($categories as $category): ?>
                                    <option value="<?= htmlspecialchars($category['category_name']) ?>">
                                        <?= htmlspecialchars($category['category_name']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <div class="form-text">Choose the category this figure belongs to</div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-bold">Figure Item Name</label>
                            <input type="text" class="form-control form-control-lg" name="item_name" required 
                                   placeholder="e.g., 360, Frontside, Mute">
                            <div class="form-text">Enter the specific name of the figure or technique</div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" name="add_item" class="btn btn-success">
                            <i class="fas fa-plus me-1"></i>Add Figure Item
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

        <!-- Help Modal -->
        <div class="modal fade" id="helpModal" tabindex="-1" aria-labelledby="helpModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-xl modal-dialog-scrollable">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="helpModalLabel"><i class="fas fa-question-circle me-2"></i>Figures Management Help</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body p-0" style="height:80vh;">
                        <iframe src="../help/figures_management_help.html" style="width:100%;height:100%;border:0;" title="Figures Management Help"></iframe>
                    </div>
                </div>
            </div>
        </div>

        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

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