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

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

$message = '';
$event = null;

// 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'] ?? null;
    $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;

    $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 = ?
                           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, $event_id])) {
        $message = '<div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="fas fa-check-circle"></i> Event updated successfully! 
                        <a href="events.php" class="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-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 event data - SIMPLE DIRECT QUERY
try {
    $stmt = $pdo->prepare("SELECT * FROM events WHERE id = ?");
    $stmt->execute([$event_id]);
    $event = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$event) {
        die("Event with ID $event_id not found in database.");
    }
    
    // Debug: Log what we actually got
    error_log("DIRECT DATABASE FETCH FOR EVENT $event_id:");
    error_log("Name: " . ($event['name'] ?? 'NULL'));
    error_log("Sport: " . ($event['sport_discipline'] ?? 'NULL'));
    error_log("Location: " . ($event['location'] ?? 'NULL'));
    error_log("Format: " . ($event['scoring_format'] ?? 'NULL'));
    error_log("Mode: " . ($event['scoring_mode'] ?? 'NULL'));
    
} catch (Exception $e) {
    die("Database error: " . $e->getMessage());
}

// 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 available sports
$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
$formats_stmt = $pdo->prepare("
    SELECT sf.format_id, sf.name, sf.sport
    FROM scoring_formats sf
    WHERE sf.is_active = 1
    ORDER BY sf.sport, sf.name
");
$formats_stmt->execute();
$scoring_formats = $formats_stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!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'] ?? 'Event') ?> - Style Score Admin</title>
    <?php include_once '../includes/stylesheets.php'; ?>
    <style>
        .form-section {
            background: #ffffff;
            border: 1px solid #dee2e6;
            border-radius: 0.375rem;
            border-left: 4px solid #198754;
        }
        .required::after {
            content: ' *';
            color: #dc3545;
        }
        .debug-info {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            padding: 15px;
            margin: 15px 0;
            border-radius: 5px;
            font-family: monospace;
        }
    </style>
</head>
<body class="body-bg-aurora-bright">
    <?php include '../menu.php'; ?>

    <div class="container-fluid container-StyleScore p-4">
        <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">Event ID: <?= $event_id ?> | Participants: <?= $participant_count ?></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; ?>

                <!-- Debug Info -->
                <div class="debug-info">
                    <strong>Database Values for Event <?= $event_id ?>:</strong><br>
                    Name: <?= htmlspecialchars($event['name'] ?? 'NULL') ?><br>
                    Sport: <?= htmlspecialchars($event['sport_discipline'] ?? 'NULL') ?><br>
                    Location: <?= htmlspecialchars($event['location'] ?? 'NULL') ?><br>
                    Format: <?= htmlspecialchars($event['scoring_format'] ?? 'NULL') ?><br>
                    Mode: <?= htmlspecialchars($event['scoring_mode'] ?? 'NULL') ?><br>
                    Status: <?= htmlspecialchars($event['status'] ?? 'NULL') ?>
                </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>
                                </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..."><?= 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>
                                
                                <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>
                                        <?php foreach ($available_sports as $sport): ?>
                                            <option value="<?= htmlspecialchars($sport) ?>" 
                                                    <?= ($event['sport_discipline'] ?? '') === $sport ? 'selected' : '' ?>>
                                                <?= htmlspecialchars(ucwords(str_replace('_', ' ', $sport))) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <div class="invalid-feedback">Please select a sport discipline.</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>
                                        <?php foreach ($scoring_formats as $format): ?>
                                            <?php 
                                                // Handle both numeric IDs and string names
                                                $isSelected = ($event['scoring_format'] ?? '') == $format['format_id'] || 
                                                             ($event['scoring_format'] ?? '') === $format['name'];
                                            ?>
                                            <option value="<?= $format['format_id'] ?>" 
                                                    data-sport="<?= htmlspecialchars($format['sport']) ?>"
                                                    <?= $isSelected ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($format['name']) ?> (<?= htmlspecialchars($format['sport']) ?>)
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>

                                <div class="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>
                                        <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>
                                    </select>
                                </div>

                                <div class="row">
                                    <div class="col-md-6 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="<?= htmlspecialchars($event['runs_per_heat'] ?? '2') ?>" min="1" max="10">
                                    </div>
                                    <div class="col-md-6 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="<?= htmlspecialchars($event['heats_total'] ?? '1') ?>" min="1" max="20">
                                    </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">
                                        <option value="draft" <?= ($event['status'] ?? '') === 'draft' ? 'selected' : '' ?>>Draft</option>
                                        <option value="open" <?= ($event['status'] ?? '') === 'open' ? 'selected' : '' ?>>Open for Registration</option>
                                        <option value="live" <?= ($event['status'] ?? '') === 'live' ? 'selected' : '' ?>>Live Event</option>
                                        <option value="completed" <?= ($event['status'] ?? '') === 'completed' ? 'selected' : '' ?>>Completed</option>
                                        <option value="cancelled" <?= ($event['status'] ?? '') === 'cancelled' ? 'selected' : '' ?>>Cancelled</option>
                                    </select>
                                </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="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'] ?? '') ?>" min="1">
                                    </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>
                                </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>
                            </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>
        // 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);
        })();

        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 ?>';
            }
        }

        console.log('Clean Event Edit Page Loaded');
        console.log('Event ID:', <?= $event_id ?>);
        console.log('Event data loaded:', <?= json_encode($event) ?>);
    </script>
    
    <?php include 'footer.php'; ?>
</body>
</html>