<?php


require_once '../includes/auth.php';
require_once '../includes/db.php';

// Get format ID
$formatId = $_GET['id'] ?? null;
if (!$formatId) {
    header('Location: scoring_formats.php');
    exit();
}

// Check if this is a form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $pdo->beginTransaction();
        
        // Update main format details
        $updateQuery = $pdo->prepare("
            UPDATE scoring_formats SET 
                name = ?, sport = ?, mode = ?, is_active = ?,
                updated_at = NOW()
            WHERE format_id = ?
        ");
        
        $updateQuery->execute([
            $_POST['name'],
            $_POST['sport'],
            $_POST['mode'],
            isset($_POST['is_active']) ? 1 : 0,
            $formatId
        ]);
        
        // Update or insert judge configuration
        $judgeQuery = $pdo->prepare("
            INSERT INTO scoring_format_judges (format_id, min_judges, max_judges, scale_type, scale_min, scale_max, scale_custom, precision_decimal, drop_rule)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE
            min_judges = VALUES(min_judges),
            max_judges = VALUES(max_judges),
            scale_type = VALUES(scale_type),
            scale_min = VALUES(scale_min),
            scale_max = VALUES(scale_max),
            scale_custom = VALUES(scale_custom),
            precision_decimal = VALUES(precision_decimal),
            drop_rule = VALUES(drop_rule)
        ");
        
        $judgeQuery->execute([
            $formatId,
            (int)$_POST['min_judges'],
            $_POST['max_judges'] ? (int)$_POST['max_judges'] : null,
            $_POST['scale_type'],
            $_POST['scale_type'] === 'numeric' ? (float)$_POST['scale_min'] : null,
            $_POST['scale_type'] === 'numeric' ? (float)$_POST['scale_max'] : null,
            $_POST['scale_type'] === 'custom' ? $_POST['scale_custom'] : null,
            (int)$_POST['precision_decimal'],
            $_POST['drop_rule']
        ]);
        
        // Update criteria
        $pdo->prepare("DELETE FROM scoring_format_criteria WHERE format_id = ?")->execute([$formatId]);
        if (!empty($_POST['criteria_type']) && !empty($_POST['criteria_name'])) {
            $criteriaStmt = $pdo->prepare("INSERT INTO scoring_format_criteria (format_id, criteria_type, criteria_name, sort_order) VALUES (?, ?, ?, ?)");
            foreach ($_POST['criteria_type'] as $index => $type) {
                if (!empty($_POST['criteria_name'][$index])) {
                    $criteriaStmt->execute([$formatId, $type, $_POST['criteria_name'][$index], $index]);
                }
            }
        }
        
        // Update rounds
        $pdo->prepare("DELETE FROM scoring_format_rounds WHERE format_id = ?")->execute([$formatId]);
        if (!empty($_POST['round_name']) && !empty($_POST['round_runs']) && !empty($_POST['round_aggregation'])) {
            $roundsStmt = $pdo->prepare("INSERT INTO scoring_format_rounds (format_id, round_name, runs, aggregation) VALUES (?, ?, ?, ?)");
            foreach ($_POST['round_name'] as $index => $name) {
                if (!empty($name) && !empty($_POST['round_runs'][$index]) && !empty($_POST['round_aggregation'][$index])) {
                    $roundsStmt->execute([$formatId, $name, (int)$_POST['round_runs'][$index], $_POST['round_aggregation'][$index]]);
                }
            }
        }
        
        // Update results headers
        $pdo->prepare("DELETE FROM scoring_format_results WHERE format_id = ?")->execute([$formatId]);
        if (!empty($_POST['result_headers'])) {
            $resultsStmt = $pdo->prepare("INSERT INTO scoring_format_results (format_id, header_name, sort_order) VALUES (?, ?, ?)");
            foreach ($_POST['result_headers'] as $index => $header) {
                if (!empty($header)) {
                    $resultsStmt->execute([$formatId, $header, $index]);
                }
            }
        }
        
        // Update flow stages
        $pdo->prepare("DELETE FROM scoring_format_flow WHERE format_id = ?")->execute([$formatId]);
        if (!empty($_POST['flow_stages'])) {
            $flowStmt = $pdo->prepare("INSERT INTO scoring_format_flow (format_id, flow_stage, sort_order) VALUES (?, ?, ?)");
            foreach ($_POST['flow_stages'] as $index => $stage) {
                if (!empty($stage)) {
                    $flowStmt->execute([$formatId, $stage, $index]);
                }
            }
        }
        
        // Update tiebreak rules
        $pdo->prepare("DELETE FROM scoring_format_tiebreak WHERE format_id = ?")->execute([$formatId]);
        if (!empty($_POST['tiebreak_rules'])) {
            $tiebreakStmt = $pdo->prepare("INSERT INTO scoring_format_tiebreak (format_id, tiebreak_rule, sort_order) VALUES (?, ?, ?)");
            foreach ($_POST['tiebreak_rules'] as $index => $rule) {
                if (!empty($rule)) {
                    $tiebreakStmt->execute([$formatId, $rule, $index]);
                }
            }
        }
        
        // Update mode configuration
        $pdo->prepare("DELETE FROM scoring_format_mode_config WHERE format_id = ?")->execute([$formatId]);
        if (!empty($_POST['config_type']) && !empty($_POST['config_key']) && !empty($_POST['config_value'])) {
            $configStmt = $pdo->prepare("INSERT INTO scoring_format_mode_config (format_id, config_type, config_key, config_value) VALUES (?, ?, ?, ?)");
            foreach ($_POST['config_type'] as $index => $type) {
                if (!empty($_POST['config_key'][$index]) && !empty($_POST['config_value'][$index])) {
                    $configStmt->execute([$formatId, $type, $_POST['config_key'][$index], $_POST['config_value'][$index]]);
                }
            }
        }
        
        // Update diversity rules
        try {
            $pdo->prepare("DELETE FROM scoring_format_diversity_rules WHERE format_id = ?")->execute([$formatId]);
            if (!empty($_POST['diversity_rule_type']) && !empty($_POST['diversity_scope']) && !empty($_POST['diversity_group_name'])) {
                $diversityStmt = $pdo->prepare("INSERT INTO scoring_format_diversity_rules (format_id, rule_type, scope, group_name, min_distinct, is_optional) VALUES (?, ?, ?, ?, ?, ?)");
                foreach ($_POST['diversity_rule_type'] as $index => $ruleType) {
                    if (!empty($ruleType) && !empty($_POST['diversity_scope'][$index]) && !empty($_POST['diversity_group_name'][$index])) {
                        $diversityStmt->execute([
                            $formatId, 
                            $ruleType, 
                            $_POST['diversity_scope'][$index], 
                            $_POST['diversity_group_name'][$index],
                            !empty($_POST['diversity_min_distinct'][$index]) ? (int)$_POST['diversity_min_distinct'][$index] : 1,
                            isset($_POST['diversity_is_optional'][$index]) ? 1 : 0
                        ]);
                    }
                }
            }
        } catch (PDOException $e) {
            // Table might not exist yet, continue without error
            error_log("Diversity rules table error during save: " . $e->getMessage());
        }
        
        $pdo->commit();
        
        $_SESSION['success_message'] = 'Scoring format updated successfully!';
        header('Location: scoring_format_view.php?id=' . $formatId);
        exit();
        
    } catch (PDOException $e) {
        $pdo->rollBack();
        $error = 'Error updating format: ' . $e->getMessage();
    }
}

// Fetch format details
try {
    $query = $pdo->prepare("SELECT * FROM scoring_formats WHERE format_id = ?");
    $query->execute([$formatId]);
    $format = $query->fetch(PDO::FETCH_ASSOC);
    
    if (!$format) {
        header('Location: scoring_formats.php');
        exit();
    }
    
    // Load judge configuration
    $judgeQuery = $pdo->prepare("
        SELECT min_judges, max_judges, scale_type, scale_min, scale_max, scale_custom, precision_decimal, drop_rule
        FROM scoring_format_judges 
        WHERE format_id = ?
    ");
    $judgeQuery->execute([$formatId]);
    $judgeConfig = $judgeQuery->fetch(PDO::FETCH_ASSOC);
    
    // Merge judge config with format data
    if ($judgeConfig) {
        $format = array_merge($format, $judgeConfig);
    }
    
    // Load related data
    // Load criteria
    $criteriaQuery = $pdo->prepare("
        SELECT criteria_type, criteria_name, sort_order 
        FROM scoring_format_criteria 
        WHERE format_id = ? 
        ORDER BY sort_order, criteria_type
    ");
    $criteriaQuery->execute([$formatId]);
    $criteria = $criteriaQuery->fetchAll(PDO::FETCH_ASSOC);
    
    // Load rounds
    $roundsQuery = $pdo->prepare("
        SELECT round_name, runs, aggregation 
        FROM scoring_format_rounds 
        WHERE format_id = ? 
        ORDER BY round_name
    ");
    $roundsQuery->execute([$formatId]);
    $rounds = $roundsQuery->fetchAll(PDO::FETCH_ASSOC);
    
    // Load results headers
    $resultsQuery = $pdo->prepare("
        SELECT header_name, sort_order 
        FROM scoring_format_results 
        WHERE format_id = ? 
        ORDER BY sort_order
    ");
    $resultsQuery->execute([$formatId]);
    $results = $resultsQuery->fetchAll(PDO::FETCH_ASSOC);
    
    // Load flow stages
    $flowQuery = $pdo->prepare("
        SELECT flow_stage, sort_order 
        FROM scoring_format_flow 
        WHERE format_id = ? 
        ORDER BY sort_order
    ");
    $flowQuery->execute([$formatId]);
    $flow = $flowQuery->fetchAll(PDO::FETCH_ASSOC);
    
    // Load tiebreak rules
    $tiebreakQuery = $pdo->prepare("
        SELECT tiebreak_rule, sort_order 
        FROM scoring_format_tiebreak 
        WHERE format_id = ? 
        ORDER BY sort_order
    ");
    $tiebreakQuery->execute([$formatId]);
    $tiebreak = $tiebreakQuery->fetchAll(PDO::FETCH_ASSOC);
    
    // Load mode configuration
    $modeConfigQuery = $pdo->prepare("
        SELECT config_type, config_key, config_value 
        FROM scoring_format_mode_config 
        WHERE format_id = ? 
        ORDER BY config_type, config_key
    ");
    $modeConfigQuery->execute([$formatId]);
    $modeConfig = $modeConfigQuery->fetchAll(PDO::FETCH_ASSOC);
    
    // Load figure groups data for diversity rules
    $figureGroups = [];
    try {
        $figureGroupsQuery = $pdo->prepare("
            SELECT DISTINCT fc.category_name, fc.sport_name
            FROM figure_categories fc
            WHERE fc.sport_name = ? AND fc.is_active = 1
            ORDER BY fc.sort_order, fc.category_name
        ");
        $figureGroupsQuery->execute([$format['sport']]);
        $figureGroups = $figureGroupsQuery->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        // Table might not exist yet, continue without figure groups
        error_log("Figure categories table error during load: " . $e->getMessage());
    }

    // Load diversity rules
    $diversityRules = [];
    try {
        $diversityQuery = $pdo->prepare("
            SELECT rule_type, scope, group_name, min_distinct, is_optional
            FROM scoring_format_diversity_rules
            WHERE format_id = ?
            ORDER BY rule_type, group_name
        ");
        $diversityQuery->execute([$formatId]);
        $diversityRules = $diversityQuery->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        // Table might not exist yet, continue without diversity rules
        error_log("Diversity rules table error during load: " . $e->getMessage());
    }
    
} catch (PDOException $e) {
    die('Error: ' . $e->getMessage());
}

$pageTitle = 'Edit Scoring Format';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit <?= htmlspecialchars($format['name']) ?> - 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>
        .form-section {
            background: #ffffff;
            border: 1px solid #e3e6f0;
            border-radius: 0.5rem;
            border-left: 4px solid #4e73df;
            box-shadow: 0 0.1rem 0.25rem rgba(0, 0, 0, 0.075);
            margin-bottom: 1rem;
        }
        
        .form-section h5 {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            margin: -1rem -1rem 1rem -1rem;
            padding: 0.75rem 1rem;
            border-radius: 0.5rem 0.5rem 0 0;
            font-size: 0.9rem;
            font-weight: 600;
        }
        
        .form-label {
            font-weight: 600;
            color: #5a5c69;
            font-size: 0.85rem;
            margin-bottom: 0.375rem;
        }
        
        .form-control, .form-select {
            border: 1px solid #d1d3e2;
            border-radius: 0.35rem;
            font-size: 0.875rem;
            padding: 0.375rem 0.75rem;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #4e73df;
            box-shadow: 0 0 0 0.2rem rgba(78, 115, 223, 0.25);
        }
        
        .compact-card {
            background: #f8f9fc;
            border: 1px solid #e3e6f0;
            border-radius: 0.5rem;
            margin-bottom: 1rem;
        }
        
        .compact-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 0.5rem 1rem;
            border-radius: 0.5rem 0.5rem 0 0;
            font-size: 0.875rem;
            font-weight: 600;
        }
        
        .compact-body {
            padding: 1rem;
        }
        
        .section-row {
            background: white;
            border: 1px solid #e3e6f0;
            border-radius: 0.375rem;
            padding: 0.5rem;
            margin-bottom: 0.5rem;
        }
        
        .btn-sm {
            padding: 0.25rem 0.5rem;
            font-size: 0.8rem;
        }
        
        .form-control-sm, .form-select-sm {
            padding: 0.25rem 0.5rem;
            font-size: 0.8rem;
        }
    </style>
</head>
<body class="body-bg-aurora-bright">
    <?php include '../menu.php'; ?>
    <div class="container-fluid py-3">
        <div class="row">
            <div class="col-12">
                <!-- Header -->
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <div>
                        <h1 class="h3 mb-1">
                            <i class="fas fa-edit text-primary me-2"></i>Edit Scoring Format
                        </h1>
                        <p class="text-muted mb-0 small">Modify scoring format configuration and settings</p>
                    </div>
                    <div>
                        <a href="scoring_format_view.php?id=<?= $formatId ?>" class="btn btn-outline-secondary btn-sm me-2">
                            <i class="fas fa-arrow-left me-1"></i>Back
                        </a>
                        <a href="scoring_formats.php" class="btn btn-outline-primary btn-sm">
                            <i class="fas fa-list me-1"></i>All Formats
                        </a>
                    </div>
                </div>

                <?php if (isset($error)): ?>
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle me-2"></i><?= htmlspecialchars($error) ?>
                    </div>
                <?php endif; ?>

            <!-- Edit Form -->
            <form method="POST" class="needs-validation" novalidate>
                <!-- Compact Top Section -->
                <div class="row g-3 mb-4">
                    <!-- Basic Information -->
                    <div class="col-lg-4">
                        <div class="card">
                            <div class="card-header d-flex justify-content-between align-items-center py-2">
                                <h6 class="mb-0 text-primary">
                                    <i class="fas fa-info-circle me-1"></i>Basic Information
                                </h6>
                            </div>
                            <div class="card-body">
                                <div class="mb-2">
                                    <label for="name" class="form-label small fw-bold">Format Name *</label>
                                    <input type="text" class="form-control form-control-sm" id="name" name="name" 
                                           value="<?= htmlspecialchars($format['name'] ?? '') ?>" required>
                                    <div class="invalid-feedback">Please provide a format name.</div>
                                </div>

                                <div class="mb-2">
                                    <label for="sport" class="form-label small fw-bold">Sport *</label>
                                    <select class="form-select form-select-sm" id="sport" name="sport" required>
                                        <option value="">Select Sport</option>
                                        <?php 
                                        $sports = ['snowboard', 'freeski', 'skateboard', 'bmx', 'inline', 'surf', 'kitesurf', 'parkour', 'breaking', 'wakeboard'];
                                        foreach ($sports as $sport): 
                                        ?>
                                            <option value="<?= $sport ?>" <?= ($format['sport'] ?? '') === $sport ? 'selected' : '' ?>>
                                                <?= ucfirst($sport) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <div class="invalid-feedback">Please select a sport.</div>
                                </div>

                                <div class="mb-2">
                                    <label for="mode" class="form-label small fw-bold">Mode *</label>
                                    <select class="form-select form-select-sm" id="mode" name="mode" required>
                                        <option value="">Select Mode</option>
                                        <?php 
                                        $modes = ['slopestyle', 'halfpipe', 'big_air', 'rail_jam', 'street', 'park', 'vert', 'freestyle', 'battle', 'jam'];
                                        foreach ($modes as $mode): 
                                        ?>
                                            <option value="<?= $mode ?>" <?= ($format['mode'] ?? '') === $mode ? 'selected' : '' ?>>
                                                <?= ucfirst(str_replace('_', ' ', $mode)) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <div class="invalid-feedback">Please select a mode.</div>
                                </div>

                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="is_active" name="is_active" 
                                           <?= ($format['is_active'] ?? 1) ? 'checked' : '' ?>>
                                    <label class="form-check-label small fw-bold" for="is_active">
                                        Active Format
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Judge Configuration -->
                    <div class="col-lg-4">
                        <div class="card">
                            <div class="card-header d-flex justify-content-between align-items-center py-2">
                                <h6 class="mb-0 text-primary">
                                    <i class="fas fa-gavel me-1"></i>Judge Configuration
                                </h6>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-6 mb-2">
                                        <label for="min_judges" class="form-label small fw-bold">Min Judges *</label>
                                        <input type="number" class="form-control form-control-sm" id="min_judges" name="min_judges" 
                                               value="<?= $format['min_judges'] ?? 3 ?>" min="1" max="20" required>
                                        <div class="invalid-feedback">Please provide a valid number.</div>
                                    </div>

                                    <div class="col-6 mb-2">
                                        <label for="max_judges" class="form-label small fw-bold">Max Judges</label>
                                        <input type="number" class="form-control form-control-sm" id="max_judges" name="max_judges" 
                                               value="<?= $format['max_judges'] ?? '' ?>" min="1" max="20">
                                    </div>
                                </div>

                                <div class="mb-2">
                                    <label for="drop_rule" class="form-label small fw-bold">Drop Rule *</label>
                                    <select class="form-select form-select-sm" id="drop_rule" name="drop_rule" required>
                                        <?php 
                                        $dropRules = [
                                            'none' => 'No Drops',
                                            'highest' => 'Drop Highest',
                                            'lowest' => 'Drop Lowest',
                                            'highest_and_lowest' => 'Drop Both',
                                            'median' => 'Use Median'
                                        ];
                                        foreach ($dropRules as $value => $label): 
                                        ?>
                                            <option value="<?= $value ?>" <?= ($format['drop_rule'] ?? 'none') === $value ? 'selected' : '' ?>>
                                                <?= $label ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <div class="invalid-feedback">Please select a drop rule.</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Scoring Scale -->
                    <div class="col-lg-4">
                        <div class="card">
                            <div class="card-header d-flex justify-content-between align-items-center py-2">
                                <h6 class="mb-0 text-primary">
                                    <i class="fas fa-ruler me-1"></i>Scoring Scale
                                </h6>
                            </div>
                            <div class="card-body">
                                <div class="mb-2">
                                    <label class="form-label small fw-bold">Scale Type</label>
                                    <div class="btn-group btn-group-sm w-100" role="group">
                                        <input type="radio" class="btn-check" name="scale_type" id="scale_numeric" value="numeric" 
                                               <?= ($format['scale_type'] ?? 'numeric') === 'numeric' ? 'checked' : '' ?>>
                                        <label class="btn btn-outline-primary" for="scale_numeric">
                                            <i class="fas fa-calculator"></i> Numeric
                                        </label>
                                        
                                        <input type="radio" class="btn-check" name="scale_type" id="scale_custom" value="custom"
                                               <?= ($format['scale_type'] ?? 'numeric') === 'custom' ? 'checked' : '' ?>>
                                        <label class="btn btn-outline-primary" for="scale_custom">
                                            <i class="fas fa-palette"></i> Custom
                                        </label>
                                    </div>
                                </div>

                                <div id="numeric-scale-compact" style="display: <?= ($format['scale_type'] ?? 'numeric') === 'numeric' ? 'block' : 'none' ?>">
                                    <div class="row">
                                        <div class="col-4 mb-2">
                                            <label for="scale_min" class="form-label small fw-bold">Min</label>
                                            <input type="number" class="form-control form-control-sm" id="scale_min" name="scale_min" 
                                                   value="<?= $format['scale_min'] ?? 0 ?>" step="0.1">
                                        </div>
                                        <div class="col-4 mb-2">
                                            <label for="scale_max" class="form-label small fw-bold">Max</label>
                                            <input type="number" class="form-control form-control-sm" id="scale_max" name="scale_max" 
                                                   value="<?= $format['scale_max'] ?? 100 ?>" step="0.1">
                                        </div>
                                        <div class="col-4 mb-2">
                                            <label for="precision_decimal" class="form-label small fw-bold">Decimals</label>
                                            <select class="form-select form-select-sm" id="precision_decimal" name="precision_decimal">
                                                <option value="0" <?= ($format['precision_decimal'] ?? 1) == 0 ? 'selected' : '' ?>>0</option>
                                                <option value="1" <?= ($format['precision_decimal'] ?? 1) == 1 ? 'selected' : '' ?>>1</option>
                                                <option value="2" <?= ($format['precision_decimal'] ?? 1) == 2 ? 'selected' : '' ?>>2</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>

                                <div id="custom-scale-compact" style="display: <?= ($format['scale_type'] ?? 'numeric') === 'custom' ? 'block' : 'none' ?>">
                                    <div class="mb-2">
                                        <label for="scale_custom" class="form-label small fw-bold">Custom Values</label>
                                        <textarea class="form-control form-control-sm" id="scale_custom" name="scale_custom" rows="2" 
                                                  placeholder="A+,A,A-,B+..."><?= htmlspecialchars($format['scale_custom'] ?? '') ?></textarea>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Detailed Sections Row -->
                <div class="row g-3">
                    <!-- Left Column -->
                    <div class="col-lg-6">
                        <!-- Scoring Criteria -->
                        <div class="card mb-4">
                            <div class="card-header d-flex justify-content-between align-items-center py-2">
                                <h6 class="mb-0"><i class="fas fa-list-check me-2"></i>Scoring Criteria</h6>
                            </div>
                            <div class="card-body">
                                <div id="criteriaContainer">
                                    <!-- Criteria will be loaded here -->
                                </div>
                                <button type="button" class="btn btn-outline-primary btn-sm" onclick="addCriterion()">
                                    <i class="fas fa-plus me-1"></i>Add Criterion
                                </button>
                            </div>
                        </div>

                        <!-- Rounds Configuration -->
                        <div class="card mb-4">
                            <div class="card-header d-flex justify-content-between align-items-center py-2">
                                <h6 class="mb-0"><i class="fas fa-layer-group me-2"></i>Rounds Configuration</h6>
                            </div>
                            <div class="card-body">
                                <div id="roundsContainer">
                                    <!-- Rounds will be loaded here -->
                                </div>
                                <button type="button" class="btn btn-outline-primary btn-sm" onclick="addRound()">
                                    <i class="fas fa-plus me-1"></i>Add Round
                                </button>
                            </div>
                        </div>

                        <!-- Competition Flow -->
                        <div class="card mb-4">
                            <div class="card-header d-flex justify-content-between align-items-center py-2">
                                <h6 class="mb-0"><i class="fas fa-route me-2"></i>Competition Flow</h6>
                            </div>
                            <div class="card-body">
                                <div id="flowContainer">
                                    <!-- Flow stages will be loaded here -->
                                </div>
                                <button type="button" class="btn btn-outline-primary btn-sm" onclick="addFlowStage()">
                                    <i class="fas fa-plus me-1"></i>Add Flow Stage
                                </button>
                            </div>
                        </div>

                        <!-- Mode Configuration -->
                        <div class="card mb-4">
                            <div class="card-header d-flex justify-content-between align-items-center py-2">
                                <h6 class="mb-0"><i class="fas fa-cogs me-2"></i>Mode Configuration</h6>
                            </div>
                            <div class="card-body">
                                <div id="modeConfigContainer">
                                    <!-- Mode config will be loaded here -->
                                </div>
                                <button type="button" class="btn btn-outline-primary btn-sm" onclick="addModeConfig()">
                                    <i class="fas fa-plus me-1"></i>Add Configuration
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Right Column -->
                    <div class="col-lg-6">
                        <!-- Results Table Headers -->
                        <div class="card mb-4">
                            <div class="card-header d-flex justify-content-between align-items-center py-2">
                                <h6 class="mb-0"><i class="fas fa-table me-2"></i>Results Table Headers</h6>
                            </div>
                            <div class="card-body">
                                <div id="resultsContainer">
                                    <!-- Results headers will be loaded here -->
                                </div>
                                <button type="button" class="btn btn-outline-primary btn-sm" onclick="addResultHeader()">
                                    <i class="fas fa-plus me-1"></i>Add Header
                                </button>
                                
                                <!-- Preview Table -->
                                <div class="mt-4">
                                    <h6>Table Preview:</h6>
                                    <div class="table-responsive">
                                        <table class="table table-bordered table-sm" id="previewTable">
                                            <thead class="table-dark">
                                                <tr id="previewHeaders">
                                                    <th>Rank</th>
                                                    <th>Competitor</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <tr>
                                                    <td>1</td>
                                                    <td>Sample Competitor</td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Tiebreak Rules -->
                        <div class="card mb-4">
                            <div class="card-header d-flex justify-content-between align-items-center py-2">
                                <h6 class="mb-0"><i class="fas fa-balance-scale me-2"></i>Tiebreak Rules</h6>
                            </div>
                            <div class="card-body">
                                <div id="tiebreakContainer">
                                    <!-- Tiebreak rules will be loaded here -->
                                </div>
                                <button type="button" class="btn btn-outline-primary btn-sm" onclick="addTiebreakRule()">
                                    <i class="fas fa-plus me-1"></i>Add Tiebreak Rule
                                </button>
                            </div>
                        </div>

                        <!-- Diversity Rules -->
                        <div class="card mb-4">
                            <div class="card-header d-flex justify-content-between align-items-center py-2">
                                <h6 class="mb-0"><i class="fas fa-shapes me-2"></i>Diversity Rules</h6>
                            </div>
                            <div class="card-body">
                                <div class="alert alert-info">
                                    <small><i class="fas fa-info-circle me-1"></i>
                                    Configure diversity rules to enforce figure variety requirements across runs or competition-wide. 
                                    Figure groups are automatically loaded from the database based on the selected sport.
                                    </small>
                                </div>
                                <div class="row mb-2 text-muted small">
                                    <div class="col-md-2"><strong>Rule Type</strong></div>
                                    <div class="col-md-2"><strong>Scope</strong></div>
                                    <div class="col-md-3"><strong>Figure Group</strong></div>
                                    <div class="col-md-2"><strong>Min Distinct</strong></div>
                                    <div class="col-md-2"><strong>Optional</strong></div>
                                    <div class="col-md-1"><strong>Action</strong></div>
                                </div>
                                <div id="diversityRulesContainer">
                                    <!-- Diversity rules will be loaded here -->
                                </div>
                                <button type="button" class="btn btn-outline-primary btn-sm" onclick="addDiversityRule()">
                                    <i class="fas fa-plus me-1"></i>Add Diversity Rule
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Save Actions Row -->
                <div class="row">
                    <!-- Save Actions -->
                    <div class="col-12">
                        <div class="d-flex justify-content-between">
                            <div>
                                <button type="button" class="btn btn-outline-danger" onclick="confirmDelete()">
                                    <i class="fas fa-trash me-2"></i>Delete Format
                                </button>
                            </div>
                            <div>
                                <button type="button" class="btn btn-secondary me-2" onclick="resetForm()">
                                    <i class="fas fa-undo me-2"></i>Reset
                                </button>
                                <button type="submit" class="btn btn-success">
                                    <i class="fas fa-save me-2"></i>Save Changes
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Scale type toggle functionality
        document.addEventListener('DOMContentLoaded', function() {
            const scaleRadios = document.querySelectorAll('input[name="scale_type"]');
            const numericScaleCompact = document.getElementById('numeric-scale-compact');
            const customScaleCompact = document.getElementById('custom-scale-compact');

            scaleRadios.forEach(radio => {
                radio.addEventListener('change', function() {
                    const type = this.value;
                    
                    // Show/hide sections
                    if (type === 'numeric') {
                        numericScaleCompact.style.display = 'block';
                        customScaleCompact.style.display = 'none';
                    } else {
                        numericScaleCompact.style.display = 'none';
                        customScaleCompact.style.display = 'block';
                    }
                });
            });

            // Form validation
            const form = document.querySelector('.needs-validation');
            form.addEventListener('submit', function(event) {
                if (!form.checkValidity()) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                form.classList.add('was-validated');
            });

            // Max judges validation
            const minJudges = document.getElementById('min_judges');
            const maxJudges = document.getElementById('max_judges');
            
            minJudges.addEventListener('input', function() {
                if (maxJudges.value && parseInt(maxJudges.value) < parseInt(this.value)) {
                    maxJudges.value = this.value;
                }
                maxJudges.min = this.value;
            });

            // Load existing data
            loadFormatData();
        });

        let criteriaCount = 0;
        let roundsCount = 0;
        let resultsCount = 0;
        let flowCount = 0;
        let tiebreakCount = 0;
        let modeConfigCount = 0;
        let diversityRulesCount = 0;

        function addCriterion() {
            criteriaCount++;
            const html = `
                <div class="row mb-2 criterion-row" id="criterion_${criteriaCount}">
                    <div class="col-md-4">
                        <select class="form-select form-select-sm" name="criteria_type[]">
                            <option value="sections">Sections</option>
                            <option value="oi">Overall Impression</option>
                            <option value="attempt">Attempt</option>
                            <option value="E">Execution (E)</option>
                            <option value="D">Difficulty (D)</option>
                            <option value="comparative">Comparative</option>
                        </select>
                    </div>
                    <div class="col-md-7">
                        <input type="text" class="form-control form-control-sm" name="criteria_name[]" placeholder="Criterion name">
                    </div>
                    <div class="col-md-1">
                        <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeCriterion(${criteriaCount})">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                </div>
            `;
            document.getElementById('criteriaContainer').insertAdjacentHTML('beforeend', html);
        }

        function removeCriterion(id) {
            document.getElementById(`criterion_${id}`).remove();
        }

        function addRound() {
            roundsCount++;
            const html = `
                <div class="row mb-2 round-row" id="round_${roundsCount}">
                    <div class="col-md-4">
                        <input type="text" class="form-control form-control-sm" name="round_name[]" placeholder="Round name">
                    </div>
                    <div class="col-md-3">
                        <input type="number" class="form-control form-control-sm" name="round_runs[]" placeholder="Runs" min="0">
                    </div>
                    <div class="col-md-4">
                        <select class="form-select form-select-sm" name="round_aggregation[]">
                            <option value="best">Best</option>
                            <option value="average">Average</option>
                            <option value="sum">Sum</option>
                            <option value="best_2_of_3">Best 2 of 3</option>
                            <option value="average_best_2">Average Best 2</option>
                        </select>
                    </div>
                    <div class="col-md-1">
                        <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeRound(${roundsCount})">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                </div>
            `;
            document.getElementById('roundsContainer').insertAdjacentHTML('beforeend', html);
        }

        function removeRound(id) {
            document.getElementById(`round_${id}`).remove();
        }

        function addResultHeader() {
            resultsCount++;
            const html = `
                <div class="row mb-2 result-row" id="result_${resultsCount}">
                    <div class="col-md-11">
                        <input type="text" class="form-control form-control-sm" name="result_headers[]" placeholder="Header name" onkeyup="updatePreview()">
                    </div>
                    <div class="col-md-1">
                        <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeResultHeader(${resultsCount})">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                </div>
            `;
            document.getElementById('resultsContainer').insertAdjacentHTML('beforeend', html);
            updatePreview();
        }

        function removeResultHeader(id) {
            document.getElementById(`result_${id}`).remove();
            updatePreview();
        }

        function addFlowStage() {
            flowCount++;
            const html = `
                <div class="row mb-2 flow-row" id="flow_${flowCount}">
                    <div class="col-md-11">
                        <input type="text" class="form-control form-control-sm" name="flow_stages[]" placeholder="Flow stage description">
                    </div>
                    <div class="col-md-1">
                        <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeFlowStage(${flowCount})">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                </div>
            `;
            document.getElementById('flowContainer').insertAdjacentHTML('beforeend', html);
        }

        function removeFlowStage(id) {
            document.getElementById(`flow_${id}`).remove();
        }

        function addTiebreakRule() {
            tiebreakCount++;
            const html = `
                <div class="row mb-2 tiebreak-row" id="tiebreak_${tiebreakCount}">
                    <div class="col-md-11">
                        <input type="text" class="form-control form-control-sm" name="tiebreak_rules[]" placeholder="Tiebreak rule description">
                    </div>
                    <div class="col-md-1">
                        <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeTiebreakRule(${tiebreakCount})">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                </div>
            `;
            document.getElementById('tiebreakContainer').insertAdjacentHTML('beforeend', html);
        }

        function removeTiebreakRule(id) {
            document.getElementById(`tiebreak_${id}`).remove();
        }

        function addModeConfig() {
            modeConfigCount++;
            const html = `
                <div class="row mb-2 mode-config-row" id="modeconfig_${modeConfigCount}">
                    <div class="col-md-3">
                        <select class="form-select form-select-sm" name="config_type[]">
                            <option value="sections">Sections</option>
                            <option value="attempts">Attempts</option>
                            <option value="runs">Runs</option>
                            <option value="tricks">Tricks</option>
                            <option value="oi">Overall Impression</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <select class="form-select form-select-sm" name="config_key[]">
                            <option value="">Select Key</option>
                            <option value="count">Count</option>
                            <option value="weight">Weight</option>
                            <option value="max">Max</option>
                            <option value="bestN">Best N</option>
                            <option value="perRound">Per Round</option>
                            <option value="attempts">Attempts</option>
                            <option value="diversity">Diversity</option>
                            <option value="multiplier">Multiplier</option>
                        </select>
                    </div>
                    <div class="col-md-5">
                        <input type="text" class="form-control form-control-sm" name="config_value[]" placeholder="Config value">
                    </div>
                    <div class="col-md-1">
                        <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeModeConfig(${modeConfigCount})">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                </div>
            `;
            document.getElementById('modeConfigContainer').insertAdjacentHTML('beforeend', html);
        }

        function removeModeConfig(id) {
            document.getElementById(`modeconfig_${id}`).remove();
        }

        function addDiversityRule() {
            diversityRulesCount++;
            
            // Build figure groups options
            let figureGroupOptions = '<option value="">Select Figure Group</option>';
            figureGroupsData.forEach(group => {
                figureGroupOptions += `<option value="${group.category_name}">${group.category_name}</option>`;
            });
            
            const html = `
                <div class="row mb-2 diversity-rule-row" id="diversityrule_${diversityRulesCount}">
                    <div class="col-md-2">
                        <select class="form-select form-select-sm" name="diversity_rule_type[]">
                            <option value="">Select Type</option>
                            <option value="requireDistinct">Require Distinct</option>
                            <option value="preventDuplicate">Prevent Duplicate</option>
                            <option value="enforceVariety">Enforce Variety</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <select class="form-select form-select-sm" name="diversity_scope[]">
                            <option value="run">Per Run</option>
                            <option value="competition">Competition-wide</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <select class="form-select form-select-sm" name="diversity_group_name[]">
                            ${figureGroupOptions}
                        </select>
                    </div>
                    <div class="col-md-2">
                        <input type="number" class="form-control form-control-sm" name="diversity_min_distinct[]" placeholder="Min distinct" min="1" max="10" value="1">
                    </div>
                    <div class="col-md-2">
                        <div class="form-check form-check-sm">
                            <input class="form-check-input" type="checkbox" name="diversity_is_optional[${diversityRulesCount}]" id="diversity_optional_${diversityRulesCount}">
                            <label class="form-check-label small" for="diversity_optional_${diversityRulesCount}">Optional</label>
                        </div>
                    </div>
                    <div class="col-md-1">
                        <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeDiversityRule(${diversityRulesCount})">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                </div>
            `;
            document.getElementById('diversityRulesContainer').insertAdjacentHTML('beforeend', html);
        }

        function removeDiversityRule(id) {
            document.getElementById(`diversityrule_${id}`).remove();
        }

        function updatePreview() {
            const headers = document.querySelectorAll('input[name="result_headers[]"]');
            const previewHeaders = document.getElementById('previewHeaders');
            
            // Clear existing headers (except Rank and Competitor)
            while (previewHeaders.children.length > 2) {
                previewHeaders.removeChild(previewHeaders.lastChild);
            }
            
            // Add new headers
            headers.forEach(header => {
                if (header.value.trim()) {
                    const th = document.createElement('th');
                    th.textContent = header.value;
                    previewHeaders.appendChild(th);
                }
            });
        }

        function loadFormatData() {
            // Load criteria
            const criteriaData = <?= json_encode($criteria) ?>;
            criteriaData.forEach(criterion => {
                criteriaCount++;
                const html = `
                    <div class="row mb-2 criterion-row" id="criterion_${criteriaCount}">
                        <div class="col-md-4">
                            <select class="form-select form-select-sm" name="criteria_type[]">
                                <option value="sections" ${criterion.criteria_type === 'sections' ? 'selected' : ''}>Sections</option>
                                <option value="oi" ${criterion.criteria_type === 'oi' ? 'selected' : ''}>Overall Impression</option>
                                <option value="attempt" ${criterion.criteria_type === 'attempt' ? 'selected' : ''}>Attempt</option>
                                <option value="E" ${criterion.criteria_type === 'E' ? 'selected' : ''}>Execution (E)</option>
                                <option value="D" ${criterion.criteria_type === 'D' ? 'selected' : ''}>Difficulty (D)</option>
                                <option value="comparative" ${criterion.criteria_type === 'comparative' ? 'selected' : ''}>Comparative</option>
                            </select>
                        </div>
                        <div class="col-md-7">
                            <input type="text" class="form-control form-control-sm" name="criteria_name[]" value="${criterion.criteria_name}" placeholder="Criterion name">
                        </div>
                        <div class="col-md-1">
                            <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeCriterion(${criteriaCount})">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                    </div>
                `;
                document.getElementById('criteriaContainer').insertAdjacentHTML('beforeend', html);
            });
            
            // Load rounds
            const roundsData = <?= json_encode($rounds) ?>;
            roundsData.forEach(round => {
                roundsCount++;
                const html = `
                    <div class="row mb-2 round-row" id="round_${roundsCount}">
                        <div class="col-md-4">
                            <input type="text" class="form-control form-control-sm" name="round_name[]" value="${round.round_name}" placeholder="Round name">
                        </div>
                        <div class="col-md-3">
                            <input type="number" class="form-control form-control-sm" name="round_runs[]" value="${round.runs}" placeholder="Runs" min="0">
                        </div>
                        <div class="col-md-4">
                            <select class="form-select form-select-sm" name="round_aggregation[]">
                                <option value="best" ${round.aggregation === 'best' ? 'selected' : ''}>Best</option>
                                <option value="average" ${round.aggregation === 'average' ? 'selected' : ''}>Average</option>
                                <option value="sum" ${round.aggregation === 'sum' ? 'selected' : ''}>Sum</option>
                                <option value="best_2_of_3" ${round.aggregation === 'best_2_of_3' ? 'selected' : ''}>Best 2 of 3</option>
                                <option value="average_best_2" ${round.aggregation === 'average_best_2' ? 'selected' : ''}>Average Best 2</option>
                            </select>
                        </div>
                        <div class="col-md-1">
                            <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeRound(${roundsCount})">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                    </div>
                `;
                document.getElementById('roundsContainer').insertAdjacentHTML('beforeend', html);
            });
            
            // Load results headers
            const resultsData = <?= json_encode($results) ?>;
            resultsData.forEach(result => {
                resultsCount++;
                const html = `
                    <div class="row mb-2 result-row" id="result_${resultsCount}">
                        <div class="col-md-11">
                            <input type="text" class="form-control form-control-sm" name="result_headers[]" value="${result.header_name}" placeholder="Header name" onkeyup="updatePreview()">
                        </div>
                        <div class="col-md-1">
                            <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeResultHeader(${resultsCount})">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                    </div>
                `;
                document.getElementById('resultsContainer').insertAdjacentHTML('beforeend', html);
            });
            
            // Load flow stages
            const flowData = <?= json_encode($flow) ?>;
            flowData.forEach(flowStage => {
                flowCount++;
                const html = `
                    <div class="row mb-2 flow-row" id="flow_${flowCount}">
                        <div class="col-md-11">
                            <input type="text" class="form-control form-control-sm" name="flow_stages[]" value="${flowStage.flow_stage}" placeholder="Flow stage description">
                        </div>
                        <div class="col-md-1">
                            <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeFlowStage(${flowCount})">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                    </div>
                `;
                document.getElementById('flowContainer').insertAdjacentHTML('beforeend', html);
            });
            
            // Load tiebreak rules
            const tiebreakData = <?= json_encode($tiebreak) ?>;
            tiebreakData.forEach(rule => {
                tiebreakCount++;
                const html = `
                    <div class="row mb-2 tiebreak-row" id="tiebreak_${tiebreakCount}">
                        <div class="col-md-11">
                            <input type="text" class="form-control form-control-sm" name="tiebreak_rules[]" value="${rule.tiebreak_rule}" placeholder="Tiebreak rule description">
                        </div>
                        <div class="col-md-1">
                            <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeTiebreakRule(${tiebreakCount})">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                    </div>
                `;
                document.getElementById('tiebreakContainer').insertAdjacentHTML('beforeend', html);
            });
            
            // Load mode configuration
            const modeConfigData = <?= json_encode($modeConfig) ?>;
            modeConfigData.forEach(config => {
                modeConfigCount++;
                const html = `
                    <div class="row mb-2 mode-config-row" id="modeconfig_${modeConfigCount}">
                        <div class="col-md-3">
                            <select class="form-select form-select-sm" name="config_type[]">
                                <option value="sections" ${config.config_type === 'sections' ? 'selected' : ''}>Sections</option>
                                <option value="attempts" ${config.config_type === 'attempts' ? 'selected' : ''}>Attempts</option>
                                <option value="runs" ${config.config_type === 'runs' ? 'selected' : ''}>Runs</option>
                                <option value="tricks" ${config.config_type === 'tricks' ? 'selected' : ''}>Tricks</option>
                                <option value="oi" ${config.config_type === 'oi' ? 'selected' : ''}>Overall Impression</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <select class="form-select form-select-sm" name="config_key[]">
                                <option value="">Select Key</option>
                                <option value="count" ${config.config_key === 'count' ? 'selected' : ''}>Count</option>
                                <option value="weight" ${config.config_key === 'weight' ? 'selected' : ''}>Weight</option>
                                <option value="max" ${config.config_key === 'max' ? 'selected' : ''}>Max</option>
                                <option value="bestN" ${config.config_key === 'bestN' ? 'selected' : ''}>Best N</option>
                                <option value="perRound" ${config.config_key === 'perRound' ? 'selected' : ''}>Per Round</option>
                                <option value="attempts" ${config.config_key === 'attempts' ? 'selected' : ''}>Attempts</option>
                                <option value="diversity" ${config.config_key === 'diversity' ? 'selected' : ''}>Diversity</option>
                                <option value="multiplier" ${config.config_key === 'multiplier' ? 'selected' : ''}>Multiplier</option>
                            </select>
                        </div>
                        <div class="col-md-5">
                            <input type="text" class="form-control form-control-sm" name="config_value[]" value="${config.config_value}" placeholder="Config value">
                        </div>
                        <div class="col-md-1">
                            <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeModeConfig(${modeConfigCount})">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                    </div>
                `;
                document.getElementById('modeConfigContainer').insertAdjacentHTML('beforeend', html);
            });
            
            // Load diversity rules
            const diversityRulesData = <?= json_encode($diversityRules) ?>;
            const figureGroupsData = <?= json_encode($figureGroups) ?>;
            diversityRulesData.forEach(rule => {
                diversityRulesCount++;
                
                // Build figure groups options for existing rule
                let figureGroupOptions = '<option value="">Select Figure Group</option>';
                figureGroupsData.forEach(group => {
                    const selected = group.category_name === rule.group_name ? 'selected' : '';
                    figureGroupOptions += `<option value="${group.category_name}" ${selected}>${group.category_name}</option>`;
                });
                
                const html = `
                    <div class="row mb-2 diversity-rule-row" id="diversityrule_${diversityRulesCount}">
                        <div class="col-md-2">
                            <select class="form-select form-select-sm" name="diversity_rule_type[]">
                                <option value="">Select Type</option>
                                <option value="requireDistinct" ${rule.rule_type === 'requireDistinct' ? 'selected' : ''}>Require Distinct</option>
                                <option value="preventDuplicate" ${rule.rule_type === 'preventDuplicate' ? 'selected' : ''}>Prevent Duplicate</option>
                                <option value="enforceVariety" ${rule.rule_type === 'enforceVariety' ? 'selected' : ''}>Enforce Variety</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <select class="form-select form-select-sm" name="diversity_scope[]">
                                <option value="run" ${rule.scope === 'run' ? 'selected' : ''}>Per Run</option>
                                <option value="competition" ${rule.scope === 'competition' ? 'selected' : ''}>Competition-wide</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <select class="form-select form-select-sm" name="diversity_group_name[]">
                                ${figureGroupOptions}
                            </select>
                        </div>
                        <div class="col-md-2">
                            <input type="number" class="form-control form-control-sm" name="diversity_min_distinct[]" value="${rule.min_distinct || 1}" placeholder="Min distinct" min="1" max="10">
                        </div>
                        <div class="col-md-2">
                            <div class="form-check form-check-sm">
                                <input class="form-check-input" type="checkbox" name="diversity_is_optional[${diversityRulesCount}]" id="diversity_optional_${diversityRulesCount}" ${rule.is_optional ? 'checked' : ''}>
                                <label class="form-check-label small" for="diversity_optional_${diversityRulesCount}">Optional</label>
                            </div>
                        </div>
                        <div class="col-md-1">
                            <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeDiversityRule(${diversityRulesCount})">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                    </div>
                `;
                document.getElementById('diversityRulesContainer').insertAdjacentHTML('beforeend', html);
            });
            
            // Update preview table
            updatePreview();
        }

        function resetForm() {
            if (confirm('Are you sure you want to reset all changes?')) {
                location.reload();
            }
        }

        function confirmDelete() {
            if (confirm('Are you sure you want to delete this scoring format? This action cannot be undone.')) {
                if (confirm('This will permanently delete the format and all associated data. Are you absolutely sure?')) {
                    // Create a form to submit delete request
                    const form = document.createElement('form');
                    form.method = 'POST';
                    form.action = 'scoring_format_delete.php';
                    
                    const input = document.createElement('input');
                    input.type = 'hidden';
                    input.name = 'format_id';
                    input.value = '<?= $formatId ?>';
                    
                    form.appendChild(input);
                    document.body.appendChild(form);
                    form.submit();
                }
            }
        }
        
        // Handle sport change to reload figure groups
        document.getElementById('sport').addEventListener('change', function() {
            const selectedSport = this.value;
            if (selectedSport) {
                // Fetch figure groups for the selected sport
                fetch('get_figure_groups.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ sport: selectedSport })
                })
                .then(response => response.json())
                .then(data => {
                    // Update global figureGroupsData
                    figureGroupsData = data;
                    
                    // Update existing diversity rule dropdowns
                    document.querySelectorAll('select[name="diversity_group_name[]"]').forEach(select => {
                        const currentValue = select.value;
                        select.innerHTML = '<option value="">Select Figure Group</option>';
                        
                        data.forEach(group => {
                            const option = document.createElement('option');
                            option.value = group.category_name;
                            option.textContent = group.category_name;
                            if (group.category_name === currentValue) {
                                option.selected = true;
                            }
                            select.appendChild(option);
                        });
                    });
                })
                .catch(error => {
                    console.error('Error fetching figure groups:', error);
                });
            }
        });
    </script>

    </body>
</html>
