<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

$event_id = $_GET['id'] ?? null;
if (!$event_id) {
    header('Location: events.php');
    exit;
}

$message = '';

// Check if redirected from event creation
if (isset($_GET['created']) && $_GET['created'] == '1') {
    $message = '<div class="alert alert-success alert-dismissible fade show" role="alert">
                    <i class="fas fa-check-circle"></i> <strong>Event created successfully!</strong> 
                    Now configure the detailed settings below to complete your event setup.
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>';
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = $_POST['name'];
    $date = $_POST['date'];
    $location = $_POST['location'];
    $sport_discipline = $_POST['sport_discipline'];
    $description = $_POST['description'];
    $max_participants = $_POST['max_participants'];
    $age_limit = $_POST['age_limit'];
    $entry_fee = $_POST['entry_fee'];
    $contact_email = $_POST['contact_email'];
    $contact_phone = $_POST['contact_phone'];
    $scoring_mode = $_POST['scoring_mode'];
    $runs_per_heat = $_POST['runs_per_heat'];
    $heats_total = $_POST['heats_total'];
    $registration_deadline = $_POST['registration_deadline'];
    $status = $_POST['status'];
    $scoring_format = $_POST['scoring_format'] ?? null;
    $scoring_layout_config = $_POST['scoring_layout_config'] ?? null;

    // Process scoring layout configuration with proper checkbox handling
    if ($scoring_layout_config) {
        // Handle checkboxes - unchecked checkboxes don't appear in POST data
        // Define the components that should exist
        $availableComponents = [
            'criteriaInputGrid', 'finalCalculatedScore', 'figuresCard', 
            'latestScores', 'otherHeatScores', 'diversityValidation', 
            'figureHistory', 'formatInfo'
        ];
        
        // Ensure all components have an enabled status (default false if not present)
        if (isset($scoring_layout_config['cards'])) {
            foreach ($availableComponents as $component) {
                if (!isset($scoring_layout_config['cards'][$component]['enabled'])) {
                    $scoring_layout_config['cards'][$component]['enabled'] = false;
                } else {
                    // Convert string "1" to boolean true
                    $scoring_layout_config['cards'][$component]['enabled'] = 
                        ($scoring_layout_config['cards'][$component]['enabled'] == '1');
                }
            }
        }
        
        // Convert layout options to proper types
        if (isset($scoring_layout_config['layout']['compactMode'])) {
            $scoring_layout_config['layout']['compactMode'] = 
                ($scoring_layout_config['layout']['compactMode'] == '1');
        }
        if (isset($scoring_layout_config['layout']['hideEmptyCards'])) {
            $scoring_layout_config['layout']['hideEmptyCards'] = 
                ($scoring_layout_config['layout']['hideEmptyCards'] == '1');
        }
        
        $scoring_layout_config = json_encode($scoring_layout_config);
    }

    $stmt = $pdo->prepare("UPDATE events SET 
                           name = ?, date = ?, location = ?, sport_discipline = ?, description = ?, 
                           max_participants = ?, age_limit = ?, entry_fee = ?, contact_email = ?, contact_phone = ?, 
                           scoring_mode = ?, runs_per_heat = ?, heats_total = ?, registration_deadline = ?, status = ?, scoring_format = ?, scoring_layout_config = ?
                           WHERE id = ?");
    
    if ($stmt->execute([$name, $date, $location, $sport_discipline, $description, $max_participants, $age_limit, $entry_fee, $contact_email, $contact_phone, $scoring_mode, $runs_per_heat, $heats_total, $registration_deadline, $status, $scoring_format, $scoring_layout_config, $event_id])) {
        $configSummary = $scoring_layout_config ? " Layout configuration saved: " . strlen($scoring_layout_config) . " chars." : " No layout configuration provided.";
        $message = '<div class="alert alert-success alert alert-dismissible fade show" role="alert">
                        <i class="fas fa-check-circle"></i> Event updated successfully!' . $configSummary . ' 
                        <a href="events.php" class="alert alert-link">Back to Events</a>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>';
    } else {
        $message = '<div class="alert alert-danger alert alert-dismissible fade show" role="alert">
                        <i class="fas fa-exclamation-triangle"></i> Failed to update event. Please try again.
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>';
    }
}

// Fetch existing event data - using SELECT * to ensure we get all fields
$stmt = $pdo->prepare("SELECT * FROM events WHERE id = ?");
$stmt->execute([$event_id]);
$event_data = $stmt->fetch(PDO::FETCH_ASSOC);

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

// PROTECT THE DATA: Save to a protected variable name
$protected_event_data = $event_data;



// Keep reference to original data - but use protected version throughout the page
$event = $protected_event_data;

// Get participant count
$participant_count_stmt = $pdo->prepare("SELECT COUNT(*) FROM event_participants WHERE event_id = ?");
$participant_count_stmt->execute([$event_id]);
$participant_count = $participant_count_stmt->fetchColumn();

// Load sports from figure_sports table
$sports_stmt = $pdo->prepare("SELECT sport_name FROM figure_sports WHERE is_active = 1 ORDER BY sport_name");
$sports_stmt->execute();
$available_sports = $sports_stmt->fetchAll(PDO::FETCH_COLUMN);

// Load scoring formats grouped by sport with round data and unique aggregations
$formats_stmt = $pdo->prepare("
    SELECT sf.format_id, sf.name, sf.sport,
           GROUP_CONCAT(DISTINCT sfr.runs ORDER BY sfr.round_name) as round_runs,
           GROUP_CONCAT(DISTINCT sfr.aggregation ORDER BY sfr.round_name) as aggregations,
           COUNT(DISTINCT sfr.id) as total_rounds
    FROM scoring_formats sf
    LEFT JOIN scoring_format_rounds sfr ON sf.format_id = sfr.format_id
    WHERE sf.is_active = 1
    GROUP BY sf.format_id, sf.name, sf.sport
    ORDER BY sf.sport, sf.name
");
$formats_stmt->execute();
$scoring_formats = $formats_stmt->fetchAll(PDO::FETCH_ASSOC);

// Get all unique aggregation methods for dynamic scoring mode options
$aggregation_stmt = $pdo->prepare("
    SELECT DISTINCT aggregation 
    FROM scoring_format_rounds 
    WHERE aggregation IS NOT NULL AND aggregation != ''
    ORDER BY aggregation
");
$aggregation_stmt->execute();
$available_aggregations = $aggregation_stmt->fetchAll(PDO::FETCH_COLUMN);

// Group formats by sport for JavaScript
$formats_by_sport = [];
foreach ($scoring_formats as $format) {
    $formats_by_sport[$format['sport']][] = $format;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Event - <?= htmlspecialchars($event['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>
        body {
            font-family: 'Inter', sans-serif;
        }
        
        .form-section {
            background: #ffffff;
            border: 1px solid #dee2e6;
            border-radius: 0.375rem;
            border-left: 4px solid #198754;
        }
        
        .required::after {
            content: ' *';
            color: #dc3545;
        }
    </style>
</head>
<body class="body-bg-aurora-bright">
    <?php include '../menu.php'; ?>
    <!-- Help Button and Modal -->
    <div class="position-fixed end-0 top-0 p-3  help_f_button" style="z-index: 1055;">
        <button type="button" class="btn btn-info btn-lg rounded-circle shadow" title="Help / Guide" data-bs-toggle="modal" data-bs-target="#helpModal" style="width:56px; height:56px;">
            <i class="fas fa-question"></i>
        </button>
    </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-edit me-2"></i>Edit Event 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/event_edit_help.html" style="width:100%;height:100%;border:0;" title="Edit Event Help"></iframe>
                </div>
            </div>
        </div>
    </div>
    <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-xl-10">
                <!-- Header -->
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <div>
                        <h1 class="h2 mb-1">
                            <i class="fas fa-edit text-success me-2"></i>Edit Event
                        </h1>
                        <p class="text-muted mb-0">Update event details and configuration settings</p>
                    </div>
                    <div>
                        <a href="events.php" class="btn btn-outline-primary">
                            <i class="fas fa-list me-1"></i>All Events
                        </a>
                    </div>
                </div>

                <?php echo $message; ?>

                <!-- Event Info Badge -->
                <div class="alert alert-info mb-4">
                    <div class="row align-items-center">
                        <div class="col-md-8">
                            <h6 class="mb-1"><i class="fas fa-calendar-alt me-2"></i>Event Information</h6>
                            <small>Created: <?= date('M d, Y', strtotime($event['created_at'] ?? 'now')) ?> | Participants: <?= $participant_count ?></small>
                        </div>
                        <div class="col-md-4 text-end">
                            <?php if ($participant_count > 0): ?>
                                <span class="badge bg-success">Active Event</span>
                            <?php else: ?>
                                <span class="badge bg-secondary">Draft Event</span>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <!-- Edit Form -->
                <form method="post" class="needs-validation" novalidate>
                    <div class="row g-4">
                        <!-- Basic Information -->
                        <div class="col-lg-6">
                            <div class="form-section p-4">
                                <h5 class="mb-3">
                                    <i class="fas fa-info-circle text-success me-2"></i>Basic Information
                                </h5>
                                
                                <div class="mb-3">
                                    <label for="name" class="form-label fw-bold required">Event Name</label>
                                    <input type="text" class="form-control" id="name" name="name" 
                                           value="<?= htmlspecialchars($event['name'] ?? '') ?>" required>
                                    <div class="invalid-feedback">Please provide a valid event name.</div>
                                </div>

                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="date" class="form-label fw-bold required">Event Date</label>
                                        <input type="date" class="form-control" id="date" name="date" 
                                               value="<?= htmlspecialchars($event['date'] ?? '') ?>" required>
                                        <div class="invalid-feedback">Please provide a valid date.</div>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label for="registration_deadline" class="form-label fw-bold">Registration Deadline</label>
                                        <input type="date" class="form-control" id="registration_deadline" name="registration_deadline" 
                                               value="<?= htmlspecialchars($event['registration_deadline'] ?? '') ?>">
                                        <div class="form-text">Optional deadline for registration</div>
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="location" class="form-label fw-bold required">Location</label>
                                    <input type="text" class="form-control" id="location" name="location" 
                                           value="<?= htmlspecialchars($event['location'] ?? '') ?>" 
                                           placeholder="e.g., Central Skate Park, New York" required>
                                    <div class="invalid-feedback">Please provide a valid location.</div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="description" class="form-label fw-bold">Description</label>
                                    <textarea class="form-control" id="description" name="description" rows="3" 
                                              placeholder="Brief description of the event, rules, or special notes..."><?= htmlspecialchars($event['description'] ?? '') ?></textarea>
                                </div>
                            </div>
                        </div>

                        <!-- Sport & Format Configuration -->
                        <div class="col-lg-6">
                            <div class="form-section p-4">
                                <h5 class="mb-3">
                                    <i class="fas fa-trophy text-success me-2"></i>Sport & Format
                                </h5>
                                
                                <?php
                                    // RESTORE PROTECTED DATA: In case $event got corrupted by includes
                                    $event = $protected_event_data;
                                ?>
                                
                                <?php if ($participant_count > 0): ?>
                                    <div class="alert alert-warning mb-3">
                                        <i class="fas fa-exclamation-triangle me-2"></i>
                                        <strong>Warning:</strong> This event has participants. Changing sport or format may affect scoring.
                                    </div>
                                <?php endif; ?>
                                
                                <div class="mb-3">
                                    <label for="sport_discipline" class="form-label fw-bold required">Sport Discipline</label>
                                    <select class="form-select" id="sport_discipline" name="sport_discipline" required>
                                        <option value="">Select Sport</option>
                                        
                                        <!-- Dynamic Sports from Database -->
                                        <optgroup label="Available Sports">
                                            <?php foreach ($available_sports as $sport): ?>
                                                <?php $isSelected = ($event['sport_discipline'] ?? '') === $sport; ?>
                                                <option value="<?= htmlspecialchars($sport) ?>" 
                                                        <?= $isSelected ? 'selected="selected"' : '' ?>>
                                                    <?= htmlspecialchars(ucwords(str_replace('_', ' ', $sport))) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </optgroup>
                                    </select>
                                    <div class="invalid-feedback">Please select a sport discipline.</div>
                                    <div class="form-text">
                                        Sports are loaded from the figures database. 
                                        <a href="figures_management.php" target="_blank">Manage sports</a>
                                    </div>
                                </div>

                                <div class="mb-3">
                                    <label for="scoring_format" class="form-label fw-bold">Scoring Format</label>
                                    <select class="form-select" id="scoring_format" name="scoring_format">
                                        <option value="">Select Format</option>
                                        
                                        <!-- Dynamic Formats grouped by sport -->
                                        <?php foreach ($scoring_formats as $format): ?>
                                            <?php 
                                                // Handle both numeric IDs and string names for backward compatibility
                                                $isSelected = ($event['scoring_format'] ?? '') == $format['format_id'] || 
                                                             ($event['scoring_format'] ?? '') === $format['name'];
                                            ?>
                                            <option value="<?= $format['format_id'] ?>" 
                                                    data-sport="<?= htmlspecialchars($format['sport']) ?>"
                                                    data-runs="<?= htmlspecialchars($format['round_runs'] ?? '') ?>"
                                                    data-aggregations="<?= htmlspecialchars($format['aggregations'] ?? '') ?>"
                                                    data-total-rounds="<?= $format['total_rounds'] ?? 0 ?>"
                                                    <?= $isSelected ? 'selected="selected"' : '' ?>>
                                                <?= htmlspecialchars($format['name']) ?> (<?= htmlspecialchars($format['sport']) ?>)
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <div class="form-text">
                                        <i class="fas fa-filter me-1"></i>Formats are automatically filtered by selected sport discipline. 
                                        <a href="scoring_formats.php" target="_blank">Manage formats</a>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="max_participants" class="form-label fw-bold">Max Participants</label>
                                        <input type="number" class="form-control" id="max_participants" name="max_participants" 
                                               value="<?= htmlspecialchars($event['max_participants'] ?? '') ?>" >
                                        <div class="form-text">Leave empty for unlimited</div>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label for="age_limit" class="form-label fw-bold">Age Limit</label>
                                        <input type="number" class="form-control" id="age_limit" name="age_limit" 
                                               value="<?= htmlspecialchars($event['age_limit'] ?? '') ?>" min="0">
                                        <div class="form-text">Minimum age requirement (0 = no limit)</div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Scoring Configuration -->
                        <div class="col-lg-6">
                            <div class="form-section p-4">
                                <h5 class="mb-3">
                                    <i class="fas fa-calculator text-success me-2"></i>Scoring Configuration
                                </h5>
                                
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="scoring_mode" class="form-label fw-bold">Scoring Mode</label>
                                        <select class="form-select" id="scoring_mode" name="scoring_mode">
                                            <option value="">Select Mode</option>
                                            
                                            <!-- Standard Modes -->
                                            <optgroup label="Standard Modes">
                                                <option value="average" <?= ($event['scoring_mode'] ?? '') === 'average' ? 'selected' : '' ?>>Average</option>
                                                <option value="best" <?= ($event['scoring_mode'] ?? '') === 'best' ? 'selected' : '' ?>>Best</option>
                                                <option value="total" <?= ($event['scoring_mode'] ?? '') === 'total' ? 'selected' : '' ?>>Total</option>
                                                <option value="as_per_format" <?= ($event['scoring_mode'] ?? '') === 'as_per_format' ? 'selected' : '' ?>>As Per Format</option>
                                            </optgroup>
                                            
                                            <!-- Format-Specific Modes (populated dynamically) -->
                                            <optgroup label="Format-Specific Modes" id="format-specific-modes">
                                                <!-- Populated by JavaScript based on selected format -->
                                            </optgroup>
                                        </select>
                                        <div class="form-text">Automatically selected based on format</div>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label for="runs_per_heat" class="form-label fw-bold">Runs Per Heat</label>
                                        <input type="number" class="form-control" id="runs_per_heat" name="runs_per_heat" 
                                               value="<?= $event['runs_per_heat'] ?? '2' ?>" min="1" max="10">
                                        <div class="form-text">Auto-populated from format</div>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label for="heats_total" class="form-label fw-bold">Total Heats</label>
                                        <input type="number" class="form-control" id="heats_total" name="heats_total" 
                                               value="<?= $event['heats_total'] ?? '1' ?>" min="1" max="20">
                                        <div class="form-text">Auto-populated from format</div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Contact & Financial -->
                        <div class="col-lg-6">
                            <div class="form-section p-4">
                                <h5 class="mb-3">
                                    <i class="fas fa-address-book text-success me-2"></i>Contact & Financial
                                </h5>
                                
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="contact_email" class="form-label fw-bold">Contact Email</label>
                                        <input type="email" class="form-control" id="contact_email" name="contact_email" 
                                               value="<?= htmlspecialchars($event['contact_email'] ?? '') ?>">
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label for="contact_phone" class="form-label fw-bold">Contact Phone</label>
                                        <input type="text" class="form-control" id="contact_phone" name="contact_phone" 
                                               value="<?= htmlspecialchars($event['contact_phone'] ?? '') ?>">
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="entry_fee" class="form-label fw-bold">Entry Fee ($)</label>
                                    <input type="number" class="form-control" id="entry_fee" name="entry_fee" 
                                           value="<?= htmlspecialchars($event['entry_fee'] ?? '0') ?>" min="0" step="0.01">
                                    <div class="form-text">Set to 0 for free events</div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="status" class="form-label fw-bold">Event Status</label>
                                    <select class="form-select" id="status" name="status" required>
                                        <option value="draft" <?= ($event['status'] ?? '') === 'draft' ? 'selected' : '' ?>>Draft</option>
                                        <option value="published" <?= ($event['status'] ?? '') === 'published' ? 'selected' : '' ?>>Published</option>
                                        <option value="live" <?= ($event['status'] ?? '') === 'live' ? 'selected' : '' ?>>Live</option>
                                        <option value="completed" <?= ($event['status'] ?? '') === 'completed' ? 'selected' : '' ?>>Completed</option>
                                        <option value="cancelled" <?= ($event['status'] ?? '') === 'cancelled' ? 'selected' : '' ?>>Cancelled</option>
                                    </select>
                                    <div class="form-text">Current event status</div>
                                </div>
                            </div>
                        </div>

                        <!-- Scoring Layout Configuration -->
                        <div class="col-lg-12">
                            <div class="form-section p-4">
                                <h5 class="mb-3">
                                    <i class="fas fa-layout text-success me-2"></i>Judge Scoring Panel Layout
                                </h5>
                                
                                <p class="text-muted mb-3">Configure which components are visible on the judge scoring panel (score.php). This affects what judges see when scoring participants.</p>
                                
                                <?php
                                    // Get current scoring layout config or use defaults
                                    $currentConfig = [];
                                    if (!empty($event['scoring_layout_config'])) {
                                        $currentConfig = json_decode($event['scoring_layout_config'], true) ?? [];
                                    }
                                    
                                    // Debug information (remove in production)
                                    if (!empty($event['scoring_layout_config'])) {
                                        echo '<div class="alert alert-info alert-sm mb-3">';
                                        echo '<strong>Current Configuration Status:</strong> ';
                                        echo 'Stored as: ' . strlen($event['scoring_layout_config']) . ' characters. ';
                                        echo 'Decoded successfully: ' . (is_array($currentConfig) ? 'Yes' : 'No');
                                        if (is_array($currentConfig)) {
                                            $componentCount = count($currentConfig['cards'] ?? []);
                                            echo '. Components configured: ' . $componentCount;
                                        }
                                        echo '</div>';
                                    } else {
                                        echo '<div class="alert alert-warning alert-sm mb-3">';
                                        echo '<strong>Configuration Status:</strong> No saved configuration found. Using default settings.';
                                        echo '</div>';
                                    }
                                    
                                    // Define available scoring panel components
                                    $availableComponents = [
                                        'criteriaInputGrid' => [
                                            'title' => 'Criteria Scoring Grid',
                                            'description' => 'Individual criteria input fields with sliders for detailed scoring',
                                            'default' => true
                                        ],
                                        'finalCalculatedScore' => [
                                            'title' => 'Final Score Display',
                                            'description' => 'Shows the final calculated score from criteria or manual input',
                                            'default' => true
                                        ],
                                        'figuresCard' => [
                                            'title' => 'Figures Selection Card',
                                            'description' => 'Figure selection chips for snowboard/freestyle sports with diversity validation',
                                            'default' => true
                                        ],
                                        'latestScores' => [
                                            'title' => 'Latest Scores Table',
                                            'description' => 'Recent scores with edit/overwrite functionality',
                                            'default' => true
                                        ],
                                        'otherHeatScores' => [
                                            'title' => 'Other Judges Scores',
                                            'description' => 'Scores from other judges for the same participant',
                                            'default' => true
                                        ],
                                        'diversityValidation' => [
                                            'title' => 'Diversity Validation',
                                            'description' => 'Real-time figure diversity rule checking and warnings',
                                            'default' => true
                                        ],
                                        'figureHistory' => [
                                            'title' => 'Figure History',
                                            'description' => 'Previous figure selections across runs for reference',
                                            'default' => true
                                        ],
                                        'formatInfo' => [
                                            'title' => 'Format Information Card',
                                            'description' => 'Scoring format details, rules, and metadata',
                                            'default' => false
                                        ]
                                    ];
                                ?>
                                
                                <div class="row">
                                    <div class="col-lg-8">
                                        <h6 class="fw-bold mb-3">Visible Components</h6>
                                        
                                        <?php foreach ($availableComponents as $key => $component): ?>
                                            <?php 
                                                $isEnabled = $currentConfig['cards'][$key]['enabled'] ?? $component['default'];
                                            ?>
                                            <div class="form-check mb-2">
                                                <input class="form-check-input" type="checkbox" 
                                                       name="scoring_layout_config[cards][<?= $key ?>][enabled]" 
                                                       id="layout_<?= $key ?>" 
                                                       value="1" <?= $isEnabled ? 'checked' : '' ?>>
                                                <label class="form-check-label" for="layout_<?= $key ?>">
                                                    <strong><?= htmlspecialchars($component['title']) ?></strong>
                                                    <br>
                                                    <small class="text-muted"><?= htmlspecialchars($component['description']) ?></small>
                                                </label>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                    
                                    <div class="col-lg-4">
                                        <h6 class="fw-bold mb-3">Layout Options</h6>
                                        
                                        <div class="mb-3">
                                            <label class="form-label">Cards Display Mode</label>
                                            <select class="form-select form-select-sm" name="scoring_layout_config[layout][compactMode]">
                                                <option value="0" <?= (!($currentConfig['layout']['compactMode'] ?? false)) ? 'selected' : '' ?>>Full Size Cards</option>
                                                <option value="1" <?= ($currentConfig['layout']['compactMode'] ?? false) ? 'selected' : '' ?>>Compact Mode</option>
                                            </select>
                                            <div class="form-text">Compact mode reduces card padding and spacing</div>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" 
                                                       name="scoring_layout_config[layout][hideEmptyCards]" 
                                                       id="hideEmptyCards" value="1" 
                                                       <?= ($currentConfig['layout']['hideEmptyCards'] ?? true) ? 'checked' : '' ?>>
                                                <label class="form-check-label" for="hideEmptyCards">
                                                    Hide Empty Cards
                                                </label>
                                            </div>
                                            <div class="form-text">Automatically hide cards with no content</div>
                                        </div>
                                        
                                        <div class="alert alert-info">
                                            <i class="fas fa-info-circle me-2"></i>
                                            <strong>Note:</strong> Changes affect all judges using this event. Individual heat configurations can override these settings.
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Submit Actions -->
                        <div class="col-12">
                            <div class="d-flex justify-content-between align-items-center">
                                <div class="text-muted">
                                    <small><i class="fas fa-info-circle me-1"></i>Changes will be saved to the database</small>
                                </div>
                                <div>
                                    <a href="events.php" class="btn btn-outline-secondary me-2">
                                        <i class="fas fa-times me-1"></i>Cancel
                                    </a>
                                    <button type="submit" class="btn btn-success">
                                        <i class="fas fa-save me-1"></i>Update Event
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>

                <!-- Danger Zone -->
                <?php if ($participant_count == 0): ?>
                <div class="mt-4">
                    <div class="form-section p-4 border-danger">
                        <h5 class="text-danger mb-3"><i class="fas fa-exclamation-triangle me-2"></i>Danger Zone</h5>
                        <p class="text-muted mb-3">Permanently delete this event. This action cannot be undone.</p>
                        <button type="button" class="btn btn-danger" onclick="confirmDelete()">
                            <i class="fas fa-trash me-1"></i>Delete Event
                        </button>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>


                          

<script>
    // Store initial PHP values for debugging
    const savedValues = {
        sport_discipline: <?php echo json_encode($event['sport_discipline'] ?? ''); ?>,
        scoring_format: <?php echo json_encode($event['scoring_format'] ?? ''); ?>,
        scoring_mode: <?php echo json_encode($event['scoring_mode'] ?? ''); ?>,
        location: <?php echo json_encode($event['location'] ?? ''); ?>
    };
    
    console.log('PHP saved values:', savedValues);
    console.log('Raw PHP event array keys:', <?php echo json_encode(array_keys($event ?? [])); ?>);
    console.log('Raw PHP event values (first 5):', <?php echo json_encode(array_slice($event ?? [], 0, 5, true)); ?>);
    
    // Bootstrap form validation
    (function() {
        'use strict';
        window.addEventListener('load', function() {
            var forms = document.getElementsByClassName('needs-validation');
            var validation = Array.prototype.filter.call(forms, function(form) {
                form.addEventListener('submit', function(event) {
                    if (form.checkValidity() === false) {
                        event.preventDefault();
                        event.stopPropagation();
                    }
                    form.classList.add('was-validated');
                }, false);
            });
        }, false);
    })();

    document.addEventListener('DOMContentLoaded', function() {
        console.log('=== FORM PREPOPULATION DEBUG ===');
        
        // Get all form elements
        const sportSelect = document.querySelector('select[name="sport_discipline"]');
        const formatSelect = document.getElementById('scoring_format');
        const scoringModeSelect = document.getElementById('scoring_mode');
        const locationInput = document.getElementById('location');
        const nameInput = document.getElementById('name');
        
        // Log what PHP should have set
        console.log('Expected values from PHP:');
        console.log('- Sport:', savedValues.sport_discipline);
        console.log('- Format:', savedValues.scoring_format);
        console.log('- Mode:', savedValues.scoring_mode);
        console.log('- Location:', savedValues.location);
        
        // Log actual form values
        console.log('Actual form values:');
        console.log('- Sport field value:', sportSelect?.value || 'MISSING');
        console.log('- Format field value:', formatSelect?.value || 'MISSING');
        console.log('- Mode field value:', scoringModeSelect?.value || 'MISSING');
        console.log('- Location field value:', locationInput?.value || 'MISSING');
        console.log('- Name field value:', nameInput?.value || 'MISSING');
        
        // Check if form elements exist
        console.log('Form elements status:');
        console.log('- Sport select exists:', !!sportSelect);
        console.log('- Format select exists:', !!formatSelect);
        console.log('- Mode select exists:', !!scoringModeSelect);
        console.log('- Location input exists:', !!locationInput);
        
        // Analyze sport options
        if (sportSelect) {
            console.log('=== SPORT OPTIONS ANALYSIS ===');
            Array.from(sportSelect.options).forEach((opt, i) => {
                const isSelected = opt.selected;
                const shouldBeSelected = opt.value === savedValues.sport_discipline;
                console.log(`Option ${i}: "${opt.value}" = "${opt.text}" | Selected: ${isSelected} | Should be: ${shouldBeSelected}`);
            });
            
            // Force set if not matching
            if (sportSelect.value !== savedValues.sport_discipline && savedValues.sport_discipline) {
                console.log('FIXING: Setting sport to saved value:', savedValues.sport_discipline);
                sportSelect.value = savedValues.sport_discipline;
                sportSelect.style.border = '2px solid orange';
            }
        }
        
        // Analyze format options  
        if (formatSelect) {
            console.log('=== FORMAT OPTIONS ANALYSIS ===');
            Array.from(formatSelect.options).forEach((opt, i) => {
                const isSelected = opt.selected;
                const shouldBeSelected = opt.value === savedValues.scoring_format;
                console.log(`Option ${i}: "${opt.value}" = "${opt.text}" | Selected: ${isSelected} | Should be: ${shouldBeSelected}`);
            });
            
            // Force set if not matching
            if (formatSelect.value !== savedValues.scoring_format && savedValues.scoring_format) {
                console.log('FIXING: Setting format to saved value:', savedValues.scoring_format);
                formatSelect.value = savedValues.scoring_format;
                formatSelect.style.border = '2px solid orange';
            }
        }
        
        // Analyze mode options
        if (scoringModeSelect) {
            console.log('=== MODE OPTIONS ANALYSIS ===');
            Array.from(scoringModeSelect.options).forEach((opt, i) => {
                const isSelected = opt.selected;
                const shouldBeSelected = opt.value === savedValues.scoring_mode;
                console.log(`Option ${i}: "${opt.value}" = "${opt.text}" | Selected: ${isSelected} | Should be: ${shouldBeSelected}`);
            });
            
            // Force set if not matching
            if (scoringModeSelect.value !== savedValues.scoring_mode && savedValues.scoring_mode) {
                console.log('FIXING: Setting mode to saved value:', savedValues.scoring_mode);
                scoringModeSelect.value = savedValues.scoring_mode;
                scoringModeSelect.style.border = '2px solid orange';
            }
        }
        
        // Check location input
        if (locationInput) {
            if (locationInput.value !== savedValues.location && savedValues.location) {
                console.log('FIXING: Setting location to saved value:', savedValues.location);
                locationInput.value = savedValues.location;
                locationInput.style.border = '2px solid orange';
            }
        }
        
        console.log('=== FORM DEBUG COMPLETE ===');
        
        // Add simple change listeners for debugging
        if (sportSelect) {
            sportSelect.addEventListener('change', function() {
                console.log('Sport changed to:', this.value);
            });
        }
        
        if (formatSelect) {
            formatSelect.addEventListener('change', function() {
                console.log('Format changed to:', this.value);
            });
        }
        
        if (scoringModeSelect) {
            scoringModeSelect.addEventListener('change', function() {
                console.log('Mode changed to:', this.value);
            });
        }
    });
    
    function confirmDelete() {
        if (confirm('Are you sure you want to delete this event? This action cannot be undone.')) {
            window.location.href = 'event_delete.php?id=<?= $event_id ?>';
        }
    }
</script>
<?php include 'footer.php'; ?>
</body>
</html>