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

$message = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['toggle_format'])) {
        $formatId = $_POST['format_id'];
        $isActive = (int)$_POST['is_active'];
        
        $stmt = $pdo->prepare("UPDATE scoring_formats SET is_active = ? WHERE format_id = ?");
        if ($stmt->execute([$isActive, $formatId])) {
            $message = '<div class="alert alert-success">Format status updated successfully.</div>';
        } else {
            $message = '<div class="alert alert-danger">Error updating format status.</div>';
        }
    }
    
    // Handle duplicate format
    if (isset($_POST['duplicate_format'])) {
        $sourceFormatId = $_POST['format_id'];
        
        try {
            $pdo->beginTransaction();
            
            // Get source format data
            $stmt = $pdo->prepare("SELECT * FROM scoring_formats WHERE format_id = ?");
            $stmt->execute([$sourceFormatId]);
            $sourceFormat = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$sourceFormat) {
                throw new Exception("Source format not found");
            }
            
            // Create new format_id (copy of original with timestamp)
            $newFormatId = $sourceFormat['format_id'] . '_copy_' . time();
            $newName = $sourceFormat['name'] . ' (Copy)';
            
            // Insert new format
            $insertFormat = $pdo->prepare("
                INSERT INTO scoring_formats (format_id, name, sport, mode, is_active, created_at, updated_at)
                VALUES (?, ?, ?, ?, 0, NOW(), NOW())
            ");
            $insertFormat->execute([
                $newFormatId,
                $newName,
                $sourceFormat['sport'],
                $sourceFormat['mode']
            ]);
            
            // Copy scoring_format_judges
            $judgesStmt = $pdo->prepare("SELECT * FROM scoring_format_judges WHERE format_id = ?");
            $judgesStmt->execute([$sourceFormatId]);
            $judges = $judgesStmt->fetch(PDO::FETCH_ASSOC);
            
            if ($judges) {
                $insertJudges = $pdo->prepare("
                    INSERT INTO scoring_format_judges 
                    (format_id, min_judges, max_judges, scale_min, scale_max, scale_type, scale_custom, precision_decimal, drop_rule)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
                ");
                $insertJudges->execute([
                    $newFormatId,
                    $judges['min_judges'],
                    $judges['max_judges'],
                    $judges['scale_min'],
                    $judges['scale_max'],
                    $judges['scale_type'],
                    $judges['scale_custom'],
                    $judges['precision_decimal'],
                    $judges['drop_rule']
                ]);
            }
            
            // Copy scoring_format_criteria
            $criteriaStmt = $pdo->prepare("SELECT * FROM scoring_format_criteria WHERE format_id = ? ORDER BY sort_order");
            $criteriaStmt->execute([$sourceFormatId]);
            $criteriaList = $criteriaStmt->fetchAll(PDO::FETCH_ASSOC);
            
            if ($criteriaList) {
                $insertCriteria = $pdo->prepare("
                    INSERT INTO scoring_format_criteria 
                    (format_id, criteria_name, criteria_type, sort_order)
                    VALUES (?, ?, ?, ?)
                ");
                foreach ($criteriaList as $criteria) {
                    $insertCriteria->execute([
                        $newFormatId,
                        $criteria['criteria_name'],
                        $criteria['criteria_type'],
                        $criteria['sort_order']
                    ]);
                }
            }
            
            // Copy scoring_format_results
            $resultsStmt = $pdo->prepare("SELECT * FROM scoring_format_results WHERE format_id = ? ORDER BY sort_order");
            $resultsStmt->execute([$sourceFormatId]);
            $resultsList = $resultsStmt->fetchAll(PDO::FETCH_ASSOC);
            
            if ($resultsList) {
                $insertResults = $pdo->prepare("
                    INSERT INTO scoring_format_results 
                    (format_id, header_name, sort_order)
                    VALUES (?, ?, ?)
                ");
                foreach ($resultsList as $result) {
                    $insertResults->execute([
                        $newFormatId,
                        $result['header_name'],
                        $result['sort_order']
                    ]);
                }
            }
            
            // Copy scoring_format_diversity_rules (if table exists)
            try {
                $diversityStmt = $pdo->prepare("SELECT * FROM scoring_format_diversity_rules WHERE format_id = ? ORDER BY sort_order");
                $diversityStmt->execute([$sourceFormatId]);
                $diversityList = $diversityStmt->fetchAll(PDO::FETCH_ASSOC);
                
                if ($diversityList) {
                    $insertDiversity = $pdo->prepare("
                        INSERT INTO scoring_format_diversity_rules 
                        (format_id, rule_type, category, min_unique, max_repeats, scope, sort_order)
                        VALUES (?, ?, ?, ?, ?, ?, ?)
                    ");
                    foreach ($diversityList as $rule) {
                        $insertDiversity->execute([
                            $newFormatId,
                            $rule['rule_type'],
                            $rule['category'],
                            $rule['min_unique'],
                            $rule['max_repeats'],
                            $rule['scope'],
                            $rule['sort_order']
                        ]);
                    }
                }
            } catch (PDOException $e) {
                // Table might not exist, skip
            }
            
            // Copy scoring_format_tiebreak (if table exists)
            try {
                $tiebreakStmt = $pdo->prepare("SELECT * FROM scoring_format_tiebreak WHERE format_id = ? ORDER BY sort_order");
                $tiebreakStmt->execute([$sourceFormatId]);
                $tiebreakList = $tiebreakStmt->fetchAll(PDO::FETCH_ASSOC);
                
                if ($tiebreakList) {
                    $insertTiebreak = $pdo->prepare("
                        INSERT INTO scoring_format_tiebreak 
                        (format_id, tiebreak_rule, sort_order)
                        VALUES (?, ?, ?)
                    ");
                    foreach ($tiebreakList as $tiebreak) {
                        $insertTiebreak->execute([
                            $newFormatId,
                            $tiebreak['tiebreak_rule'],
                            $tiebreak['sort_order']
                        ]);
                    }
                }
            } catch (PDOException $e) {
                // Table might not exist, skip
            }
            
            // Copy scoring_format_rounds (if table exists)
            try {
                $roundsStmt = $pdo->prepare("SELECT * FROM scoring_format_rounds WHERE format_id = ? ORDER BY sort_order");
                $roundsStmt->execute([$sourceFormatId]);
                $roundsList = $roundsStmt->fetchAll(PDO::FETCH_ASSOC);
                
                if ($roundsList) {
                    $insertRounds = $pdo->prepare("
                        INSERT INTO scoring_format_rounds 
                        (format_id, round_name, runs, aggregation, sort_order)
                        VALUES (?, ?, ?, ?, ?)
                    ");
                    foreach ($roundsList as $round) {
                        $insertRounds->execute([
                            $newFormatId,
                            $round['round_name'],
                            $round['runs'],
                            $round['aggregation'],
                            $round['sort_order']
                        ]);
                    }
                }
            } catch (PDOException $e) {
                // Table might not exist, skip
            }
            
            // Copy scoring_format_mode_config (if table exists)
            try {
                $modeConfigStmt = $pdo->prepare("SELECT * FROM scoring_format_mode_config WHERE format_id = ? ORDER BY config_type, config_key");
                $modeConfigStmt->execute([$sourceFormatId]);
                $modeConfigList = $modeConfigStmt->fetchAll(PDO::FETCH_ASSOC);
                
                if ($modeConfigList) {
                    $insertModeConfig = $pdo->prepare("
                        INSERT INTO scoring_format_mode_config 
                        (format_id, config_type, config_key, config_value)
                        VALUES (?, ?, ?, ?)
                    ");
                    foreach ($modeConfigList as $config) {
                        $insertModeConfig->execute([
                            $newFormatId,
                            $config['config_type'],
                            $config['config_key'],
                            $config['config_value']
                        ]);
                    }
                }
            } catch (PDOException $e) {
                // Table might not exist, skip
            }
            
            $pdo->commit();
            $message = '<div class="alert alert-success">Format duplicated successfully! New format ID: <strong>' . htmlspecialchars($newFormatId) . '</strong></div>';
            
        } catch (Exception $e) {
            $pdo->rollBack();
            $message = '<div class="alert alert-danger">Error duplicating format: ' . htmlspecialchars($e->getMessage()) . '</div>';
        }
    }
}

// Load scoring formats with judge info and sport icons
$formats = $pdo->query("
    SELECT sf.*, 
           sfj.min_judges, sfj.max_judges, sfj.scale_min, sfj.scale_max, 
           sfj.scale_type, sfj.scale_custom, sfj.drop_rule,
           fsd.icon_path, fsd.slug, fsd.brand_color_hex,
           COUNT(DISTINCT sfc.id) as criteria_count,
           COUNT(DISTINCT sfr.id) as results_count
    FROM scoring_formats sf
    LEFT JOIN scoring_format_judges sfj ON sf.format_id = sfj.format_id
    LEFT JOIN scoring_format_criteria sfc ON sf.format_id = sfc.format_id
    LEFT JOIN scoring_format_results sfr ON sf.format_id = sfr.format_id
    LEFT JOIN figure_sports fs ON LOWER(sf.sport) = LOWER(fs.sport_name)
    LEFT JOIN figure_sport_details fsd ON fs.id = fsd.sport_id
    GROUP BY sf.format_id
    ORDER BY sf.sport, sf.name
")->fetchAll(PDO::FETCH_ASSOC);

// Group formats by sport
$formatsBySport = [];
foreach ($formats as $format) {
    $formatsBySport[$format['sport']][] = $format;
}

// Determine which sports have figures (categories or items) to flag formats using figures
$figureSupport = [];
try {
    $figStmt = $pdo->query("SELECT fs.sport_name,
                                   COUNT(DISTINCT fc.id) AS cat_count,
                                   COUNT(DISTINCT fi.id) AS item_count
                              FROM figure_sports fs
                         LEFT JOIN figure_categories fc ON fc.sport_name = fs.sport_name AND fc.is_active = 1
                         LEFT JOIN figure_items fi ON fi.sport_name = fs.sport_name AND fi.is_active = 1
                          GROUP BY fs.sport_name");
    $figRows = $figStmt->fetchAll(PDO::FETCH_ASSOC);
    foreach ($figRows as $row) {
        $figureSupport[strtolower($row['sport_name'])] = ((int)$row['cat_count'] > 0 || (int)$row['item_count'] > 0);
    }
} catch (Exception $e) {
    // Fallback: no figure info available
}

// Function to get SVG content with brand color fill
function getSvgWithColor($iconPath, $brandColor, $sportSlug, $size = 24) {
    if (empty($iconPath) || !file_exists('../' . $iconPath)) {
        return "<i class=\"fas fa-medal me-2\" style=\"color: $brandColor;\"></i>";
    }
    
    $svgContent = file_get_contents('../' . $iconPath);
    if ($svgContent === false) {
        return "<i class=\"fas fa-medal me-2\" style=\"color: $brandColor;\"></i>";
    }
    
    // Create unique class name from sport slug
    $uniqueClass = 'sport-' . preg_replace('/[^a-z0-9\-]/', '', strtolower($sportSlug ?? 'default'));
    
    // Add brand color, size, and unique class to SVG
    $svgContent = preg_replace('/(<svg[^>]*)(>)/', '$1 width="' . $size . '" height="' . $size . '" class="me-2 ' . $uniqueClass . '"$2', $svgContent);
    
    // Remove any existing fill attributes from all elements
    $svgContent = preg_replace('/fill="[^"]*"/', '', $svgContent);
    
    // Remove existing CSS styles and classes that might conflict
    $svgContent = preg_replace('/<style[^>]*>.*?<\/style>/s', '', $svgContent);
    $svgContent = preg_replace('/class="[^"]*"(?![^<]*class="me-2)/', '', $svgContent);
    
    return $svgContent;
}

// Function to generate subtle background color from brand color
function generateSubtleBg($brandColorHex) {
    if (empty($brandColorHex)) {
        return 'background: linear-gradient(175deg, rgba(13, 110, 253, 0.14) 0%, rgba(13, 110, 253, 0.56) 100%);'; // Default primary
    }
    
    // Remove # if present
    $hex = ltrim($brandColorHex, '#');
    
    // Convert hex to RGB
    if (strlen($hex) === 6) {
        $r = hexdec(substr($hex, 0, 2));
        $g = hexdec(substr($hex, 2, 2));
        $b = hexdec(substr($hex, 4, 2));
    } else {
        // Fallback to default
        return 'background: linear-gradient(175deg, rgba(13, 110, 253, 0.14) 0%, rgba(13, 110, 253, 0.56) 100%);';
    }
    
    // Create subtle gradient background with new style
    return "background: linear-gradient(175deg, rgb($r $g $b / 14%) 0%, rgb($r $g $b / 56%) 100%);";
}

// Function to get border color from brand color
function getBorderColor($brandColorHex) {
    if (empty($brandColorHex)) {
        return '#0d6efd'; // Default primary
    }
    return $brandColorHex;
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Scoring Formats Management</title>
    <?php include_once '../includes/stylesheets.php'; ?>
    <style>
        .card-hover {
            transition: transform 0.2s ease, box-shadow 0.2s ease;
        }
        .card-hover:hover {
            transform: translateY(-3px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        .fade-in {
            animation: fadeIn 0.5s ease-in;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
    /* Compact + Light theme */
    .format-card { border: 1px solid #dee2e6; background: #ffffff; color: #212529; }
    .format-card .card-header, .format-card .card-body, .format-card .card-footer { background: transparent; border: 0; padding: .5rem .75rem; }
    .format-card .card-title { color: #212529; }
    .format-card code.small { color: #6c757d; }
    .format-card:hover { transform: translateY(-2px); box-shadow: 0 8px 18px rgba(0,0,0,.12); }
    .stat-badges { display:flex; flex-wrap: wrap; gap: .2rem; }
    .badge-contrast { background: #f8f9fa; color: #212529; border: 1px solid #dee2e6; font-weight: 600; padding: .25rem .5rem; font-size: .7rem; }
        
        .format-icon {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 70px;
        height: 70px;
        border-radius: 50%;
        background: linear-gradient(180deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
        padding: 8px;
    }
    .format-icon img {
        width: 54px;
        height: 54px;
        object-fit: contain;
        filter: brightness(0) invert(1);
    }
.format-stats {
    display: flex;
    justify-content: center;
    align-content: center;
    width: 100%;
    gap: 0.5em;
}
    </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">
            <!-- Help Button -->
            <div class="d-flex justify-content-end mb-2">
                <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>
            </div>
        <!-- Page Header -->
        <div class="row mb-3">
            <div class="col-12">
                <div class="border-0 shadow-none card border-0 shadow-sm bg-primary text-white">
                    <div class="border-0 shadow-none card-body text-center py-3">
                        <h3 class="fw-bold mb-2">
                            <i class="fas fa-trophy me-2"></i>Scoring Format Management
                        </h3>
                        <p class="mb-0 small">Configure and manage scoring formats for different sports and competitions</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Quick Actions -->
        <div class="row mb-3">
            <div class="col-12">
                <div class="border-0 shadow-none card border-0 shadow-sm">
                    <div class="border-0 shadow-none card-body py-2">
                        <h6 class="card-title mb-2">
                            <i class="fas fa-bolt me-1 text-warning"></i>Quick Actions
                        </h6>
                       
                        <div class="d-flex flex-wrap gap-1">
                            <a href="scoring_format_create.php" class="btn btn-success btn-sm">
                                <i class="fas fa-plus me-1"></i>Create New
                            </a>
                            <a href="scoring_formats_seeder.php" class="btn btn-warning btn-sm">
                                <i class="fas fa-database me-1"></i>Seed Defaults
                            </a>
                            <a href="figures_management.php" class="btn btn-info btn-sm">
                                <i class="fas fa-shapes me-1"></i>Manage Figures
                            </a>
                            <a href="figures_viewer.php" class="btn btn-primary btn-sm">
                                <i class="fas fa-book me-1"></i>Figures Dictionary
                            </a>
                            <button class="btn btn-outline-primary btn-sm" onclick="exportAllFormats()">
                                <i class="fas fa-download me-1"></i>Export All
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        

        <?= $message ?>

        <?php if (empty($formats)): ?>
            <div class="border-0 shadow-none card border-0 shadow-sm text-center py-5">
                <div class="border-0 shadow-none card-body">
                    <div class="display-1 text-muted mb-3">📊</div>
                    <h4 class="mb-3">No Scoring Formats Found</h4>
                    <p class="text-muted mb-4">Get started by seeding the default formats or creating a new one!</p>
                    <div class="d-flex gap-2 justify-content-center flex-wrap">
                        <a href="scoring_formats_seeder.php" class="btn btn-primary btn-lg">
                            <i class="fas fa-database me-2"></i>Seed Default Formats
                        </a>
                        <a href="scoring_format_create.php" class="btn btn-outline-primary btn-lg">
                            <i class="fas fa-plus me-2"></i>Create New Format
                        </a>
                    </div>
                </div>
            </div>
        <?php else: ?>
            <!-- Summary Cards -->
            <div class="row g-2 mb-3">
                <div class="col-md-3">
                    <div class="border-0 shadow-none card border-primary h-100">
                        <div class="border-0 shadow-none card-body text-center p-2 format-stats">
                        <div class="fs-4 mb-1 text-primary">
                            <i class="fas fa-list"></i>
                        </div>
                        <div class="summary-card-title">
                            <h4 class="mb-0 text-primary"><?= count($formats) ?></h4>
                            <small class="text-muted">Total Formats</small>
                        </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="border-0 shadow-none card border-success h-100">
                        <div class="border-0 shadow-none card-body text-center p-2 format-stats">
                            <div class="fs-4 mb-1 text-success">
                            <i class="fas fa-check-circle"></i>
                        </div>
                         <div class="summary-card-title">
                            <h4 class="mb-0 text-success"><?= count(array_filter($formats, fn($f) => $f['is_active'])) ?></h4>
                            <small class="text-muted">Active Formats</small>
        </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="border-0 shadow-none card border-info h-100">
                        <div class="border-0 shadow-none card-body text-center p-2 format-stats">
                            <div class="fs-4 mb-1 text-info">
                            <i class="fas fa-running"></i>
                        </div>
                         <div class="summary-card-title">
                            <h4 class="mb-0 text-info"><?= count($formatsBySport) ?></h4>
                            <small class="text-muted">Sports Covered</small>
        </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="border-0 shadow-none card border-warning h-100">
                        <div class="border-0 shadow-none card-body text-center p-2 format-stats">
                             <div class="fs-4 mb-1 text-warning">
                            <i class="fas fa-cogs"></i>
                        </div>
                         <div class="summary-card-title">
                            <h4 class="mb-0 text-warning"><?= count(array_unique(array_column($formats, 'mode'))) ?></h4>
                            <small class="text-muted">Scoring Modes</small>
        </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Formats by Sport -->
            <?php foreach ($formatsBySport as $sport => $sportFormats): ?>
                <?php 
                // Get the first format's icon data for this sport
                $sportIcon = null;
                $brandColor = null;
                $sportSlug = null;
                foreach ($sportFormats as $format) {
                    if (!empty($format['icon_path'])) {
                        $sportIcon = $format['icon_path'];
                    }
                    if (!empty($format['brand_color_hex'])) {
                        $brandColor = $format['brand_color_hex'];
                    }
                    if (!empty($format['slug'])) {
                        $sportSlug = $format['slug'];
                    }
                    if ($sportIcon && $brandColor && $sportSlug) break;
                }
                
                $subtleBackground = generateSubtleBg($brandColor);
                $borderColor = getBorderColor($brandColor);
                
                // Generate unique CSS class for this sport
                $uniqueClass = 'sport-' . preg_replace('/[^a-z0-9\-]/', '', strtolower($sportSlug ?? $sport));
                ?>
                
                <?php
                // Generate dynamic styles for this sport
                                        if (!empty($brandColor)):
                                            
                                        ?>
                                        <style>
                                            .<?= $uniqueClass ?>-bg {
                                                background: linear-gradient(135deg, <?= $brandColor ?>15 0%, <?= $brandColor ?>08 100%);
                                                border-left: 0px solid <?= $brandColor ?>60;
                                            }
                                            .<?= $uniqueClass ?>-active {
                                                background: linear-gradient(135deg, <?= $brandColor ?>25 0%, <?= $brandColor ?>15 100%);
                                                border-left: 0px solid <?= $brandColor ?>;
                                            }
                                            .<?= $uniqueClass ?>-text {
                                                color: <?= $brandColor ?> !important;
                                            }
                                            .<?= $uniqueClass ?>-icon svg {
                                                fill: <?= $brandColor ?> !important;
                                            }
                                        </style>
                                        <?php endif; ?>
                <div class="mb-3">
                    <div class="border-0 shadow-none card border <?= $uniqueClass ?>-active" style="border-left: 0px solid <?= $borderColor ?> !important; ">
                        <div class="border-0 shadow-none card-header bg-light py-2  <?= $uniqueClass ?>-bg">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h6 class="mb-0 <?= $uniqueClass ?>-text <?= $uniqueClass ?>-icon fw-bold">
                                        <?= getSvgWithColor($sportIcon, $borderColor, $sportSlug, 20) ?>
                                        <?= ucfirst($sport) ?> Formats
                                    </h6>
                                    <small class="mb-0 text-muted">
                                        <?= count($sportFormats) ?> formats • <?= count(array_filter($sportFormats, fn($f) => $f['is_active'])) ?> active
                                    </small>
                                </div>
                                <div class="d-flex gap-1">
                                    <a href="./figures_management.php?sport=<?= $sport ?>&edit=sport" class="btn btn-sm btn-outline-primary <?= $uniqueClass ?>-text fw-bold" title="Edit Sport Details">
                                                        <i class="fas fa-edit"></i>
                                                    </a>
                                    <button class="btn btn-sm btn-outline-secondary" onclick="exportSport('<?= $sport ?>')">
                                        <i class="fas fa-download"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                        
                        <div class="border-0 shadow-none card-body  <?= $uniqueClass ?>- p-2">
                            <div class="row g-2">
                                <?php foreach ($sportFormats as $format): ?>
                            <div class="col-lg-6 col-xl-4">
                                <?php
                                    $fidSlug = strtolower(trim($format['format_id']));
                                    $iconRel = "../assets/img/SVG/{$fidSlug}.svg";
                                    $iconAbs = __DIR__ . "/../assets/img/SVG/{$fidSlug}.svg";
                                    $iconAbsUpper = __DIR__ . "/../assets/img/SVG/{$fidSlug}.SVG";
                                    if (!file_exists($iconAbs) && file_exists($iconAbsUpper)) { $iconRel = "../assets/img/SVG/{$fidSlug}.SVG"; $iconAbs = $iconAbsUpper; }
                                    $hasIcon = file_exists($iconAbs);
                                ?>
                                <div class="border-0 shadow-none card h-100 border card-hover format-card <?= $format['is_active'] ? 'format-active' : 'format-inactive' ?>">
                                    <div class="border-0 shadow-none card-header bg-light py-1">
                                        <div class="d-flex justify-content-between align-items-start">
                                            <div class="d-flex align-items-center gap-2 flex-grow-1">
                                                <?php if ($hasIcon): ?>
                                                    <span class="format-icon me-1">
                                                        <img src="<?= $iconRel ?>" alt="<?= htmlspecialchars($format['format_id']) ?>">
                                                    </span>
                                                <?php endif; ?>
                                                <div>
                                                    <h6 class="card-title mb-0 fw-bold">
                                                        <?= htmlspecialchars($format['name']) ?>
                                                    </h6>
                                                    <code class="small"><?= $format['format_id'] ?></code>
                                                </div>
                                            </div>
                                            <div>
                                                <?php if ($format['is_active']): ?>
                                                    <span class="badge bg-success badge-sm">
                                                        <i class="fas fa-check-circle me-1"></i>Active
                                                    </span>
                                                <?php else: ?>
                                                    <span class="badge bg-secondary badge-sm">
                                                        <i class="fas fa-pause-circle me-1"></i>Inactive
                                                    </span>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="border-0 shadow-none card-body p-2">
                                        <div class="stat-badges">
                                            <span class="btn badge-contrast btn-sm"><i class="fas fa-sliders-h me-1"></i><?= str_replace('_', ' ', ucwords($format['mode'])) ?></span>
                                            <span class="btn badge-contrast btn-sm"><i class="fas fa-users me-1"></i><?= $format['min_judges'] ?><?= $format['max_judges'] && $format['max_judges'] != $format['min_judges'] ? '-' . $format['max_judges'] : '' ?> judges</span>
                                            <?php if (!empty($format['sport']) && ($figureSupport[strtolower($format['sport'])] ?? false)): ?>
                                                <span class="btn badge-contrast btn-sm" title="This format uses figures"><i class="fas fa-shapes me-1"></i>Figures</span>
                                            <?php endif; ?>
                                            <?php if ($format['scale_type'] === 'numeric'): ?>
                                                <span class="btn badge-contrast btn-sm"><i class="fas fa-ruler me-1"></i><?= $format['scale_min'] ?>–<?= $format['scale_max'] ?></span>
                                            <?php else: ?>
                                                <span class="btn badge-contrast btn-sm"><i class="fas fa-ruler me-1"></i><?= htmlspecialchars($format['scale_custom']) ?></span>
                                            <?php endif; ?>
                                            <?php if ($format['drop_rule'] !== 'none'): ?>
                                                <span class="btn badge-contrast btn-sm"><i class="fas fa-arrow-down-a-z me-1"></i>Drop: <?= htmlspecialchars($format['drop_rule']) ?></span>
                                            <?php endif; ?>
                                            <span class="btn badge-contrast btn-sm"><i class="fas fa-list-check me-1"></i><?= $format['criteria_count'] ?> criteria</span>
                                            <span class="btn badge-contrast btn-sm"><i class="fas fa-table me-1"></i><?= $format['results_count'] ?> results</span>
                                        </div>
                                    </div>
                                    <div class="border-0 shadow-none card-footer py-2">
                                        <div class="d-grid gap-1">
                                            <div class="btn-group" role="group">
                                                <a href="scoring_format_edit.php?id=<?= $format['format_id'] ?>" 
                                                   class="btn btn-outline-primary btn-sm">
                                                    <i class="fas fa-edit me-1"></i>Edit
                                                </a>
                                                <a href="scoring_format_view.php?id=<?= $format['format_id'] ?>" 
                                                   class="btn btn-outline-info btn-sm">
                                                    <i class="fas fa-eye me-1"></i>View
                                                </a>
                                            </div>
                                            
                                            <!-- Duplicate Format -->
                                            <form method="POST" class="d-inline" onsubmit="return confirm('Duplicate this scoring format? A copy will be created with \'(Copy)\' added to the name.');">
                                                <input type="hidden" name="format_id" value="<?= $format['format_id'] ?>">
                                                <button type="submit" name="duplicate_format" 
                                                        class="btn btn-sm w-100 btn-outline-secondary">
                                                    <i class="fas fa-copy me-1"></i>Duplicate
                                                </button>
                                            </form>
                                            
                                            <!-- Toggle Active Status -->
                                            <form method="POST" class="d-inline">
                                                <input type="hidden" name="format_id" value="<?= $format['format_id'] ?>">
                                                <input type="hidden" name="is_active" value="<?= $format['is_active'] ? 0 : 1 ?>">
                                                <button type="submit" name="toggle_format" 
                                                        class="btn btn-sm w-100 <?= $format['is_active'] ? 'btn-outline-warning' : 'btn-outline-success' ?>">
                                                    <i class="fas fa-<?= $format['is_active'] ? 'pause' : 'play' ?> me-1"></i>
                                                    <?= $format['is_active'] ? 'Deactivate' : 'Activate' ?>
                                                </button>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div></div>
                </div>
            </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </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>Scoring Formats 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/scoring_formats_help.html" style="width:100%;height:100%;border:0;" title="Scoring Formats Help"></iframe>
                    </div>
                </div>
            </div>
        </div>

        <!-- Toast Container for Notifications -->
        <div class="toast-container"></div>

    <script>
        // Simple interactive functions
        function exportSport(sport) {
            alert(`Exporting ${sport} formats...`);
            // Implementation would go here
        }
        
        function exportAllFormats() {
            alert('Exporting all formats...');
            // Implementation would go here
        }
        
        // Add fade-in animation on load
        document.addEventListener('DOMContentLoaded', function() {
            const cards = document.querySelectorAll('.card');
            cards.forEach((card, index) => {
                setTimeout(() => {
                    card.classList.add('fade-in');
                }, index * 100);
            });
        });
    </script>

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