<?php
session_start();
require_once 'config.php';

// Handle logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: login.php');
    exit;
}

// Check if logged in (must be before any use of $logged_in)
$logged_in = isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true;

// Redirect to login if not logged in
if (!$logged_in) {
    header('Location: login.php');
    exit;
}

// Handle delete event
if ($logged_in && isset($_GET['delete']) && isset($_GET['event'])) {
    $event_slug = preg_replace('/[^a-z0-9-]/', '', strtolower(trim($_GET['event'])));
    
    $conn = getDBConnection();
    $stmt = $conn->prepare("SELECT id FROM events WHERE event_slug = ?");
    $stmt->bind_param("s", $event_slug);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 1) {
        // Delete event directory and files
        $event_dir = __DIR__ . '/events/' . $event_slug;
        if (is_dir($event_dir)) {
            $files = glob($event_dir . '/*');
            foreach ($files as $file) {
                if (is_file($file)) {
                    unlink($file);
                }
            }
            rmdir($event_dir);
        }
        
        // Delete from database
        $stmt->close();
        $stmt = $conn->prepare("DELETE FROM events WHERE event_slug = ?");
        $stmt->bind_param("s", $event_slug);
        $stmt->execute();
        $stmt->close();
        
        header('Location: admin.php?deleted=1');
        exit;
    }
    $stmt->close();
    $conn->close();
}

// Handle update event
$update_error = '';
$editing_event = null;

if ($logged_in && isset($_GET['edit']) && isset($_GET['event'])) {
    $event_slug = preg_replace('/[^a-z0-9-]/', '', strtolower(trim($_GET['event'])));
    $conn = getDBConnection();
    $stmt = $conn->prepare("SELECT * FROM events WHERE event_slug = ?");
    $stmt->bind_param("s", $event_slug);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 1) {
        $editing_event = $result->fetch_assoc();
        // Set default event_type if not set
        if (empty($editing_event['event_type'])) {
            $editing_event['event_type'] = 'Other';
        }
    }
    $stmt->close();
    $conn->close();
}

if ($logged_in && isset($_POST['update'])) {
    $event_id = intval($_POST['event_id'] ?? 0);
    $event_name = trim($_POST['event_name'] ?? '');
    $celebrant1 = trim($_POST['celebrant1'] ?? '');
    $celebrant2 = trim($_POST['celebrant2'] ?? '');
    $event_date = trim($_POST['event_date'] ?? '');
    
    if (empty($event_name) || empty($celebrant1)) {
        $update_error = 'Please fill in event name and at least one name';
    } elseif ($event_id <= 0) {
        $update_error = 'Invalid event ID';
    } elseif (!empty($event_date)) {
        // Validate event date is not more than 7 days in the future
        $event_date_obj = DateTime::createFromFormat('Y-m-d', $event_date);
        $today = new DateTime();
        $today->setTime(0, 0, 0); // Set to start of day for date-only comparison
        $event_date_obj->setTime(0, 0, 0); // Set to start of day for date-only comparison
        $max_date = (clone $today)->modify('+7 days');
        
        if ($event_date_obj < $today) {
            $update_error = 'Event date cannot be in the past';
        } elseif ($event_date_obj > $max_date) {
            $update_error = 'Events cannot be uploaded more than 7 days before the event date';
        }
    }
    
    if (empty($update_error)) {
        $conn = getDBConnection();
        
        // Get current event data
        $stmt = $conn->prepare("SELECT event_slug, programme_filename, header_image FROM events WHERE id = ?");
        $stmt->bind_param("i", $event_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows === 1) {
            $current_event = $result->fetch_assoc();
            $old_slug = $current_event['event_slug'];
            $filename = $current_event['programme_filename'];
            
            // Handle file upload if new file provided
            if (isset($_FILES['programme']) && $_FILES['programme']['error'] === UPLOAD_ERR_OK) {
                $file = $_FILES['programme'];
                $allowed_types = ['application/pdf'];
                $file_type = mime_content_type($file['tmp_name']);
                
                if (in_array($file_type, $allowed_types)) {
                    $event_dir = __DIR__ . '/events/' . $old_slug;
                    if (!is_dir($event_dir)) {
                        mkdir($event_dir, 0755, true);
                    }
                    $destination = $event_dir . '/' . $filename;
                    move_uploaded_file($file['tmp_name'], $destination);
                }
            }
            
            // Handle header image upload (optional)
            $header_image_filename = $current_event['header_image'] ?? null;
            if (isset($_FILES['header_image']) && $_FILES['header_image']['error'] === UPLOAD_ERR_OK) {
                $header_image = $_FILES['header_image'];
                $allowed_image_types = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
                $image_file_type = mime_content_type($header_image['tmp_name']);
                
                if (in_array($image_file_type, $allowed_image_types)) {
                    $event_dir = __DIR__ . '/events/' . $old_slug;
                    if (!is_dir($event_dir)) {
                        mkdir($event_dir, 0755, true);
                    }
                    $image_extension = pathinfo($header_image['name'], PATHINFO_EXTENSION);
                    $header_image_filename = 'header.' . strtolower($image_extension);
                    $header_image_destination = $event_dir . '/' . $header_image_filename;
                    move_uploaded_file($header_image['tmp_name'], $header_image_destination);
                }
            }
            
            // Update database
            $stmt->close();
            $event_date = empty($event_date) ? null : $event_date;
            $celebrant2 = empty($celebrant2) ? null : $celebrant2;
            $stmt = $conn->prepare("UPDATE events SET event_name = ?, event_type = ?, celebrant1 = ?, celebrant2 = ?, event_date = ?, header_image = ? WHERE id = ?");
            $stmt->bind_param("ssssssi", $event_name, $event_type, $celebrant1, $celebrant2, $event_date, $header_image_filename, $event_id);
            
            if ($stmt->execute()) {
                $stmt->close();
                $conn->close();
                header('Location: admin.php?updated=1');
                exit;
            } else {
                $update_error = 'Failed to update event: ' . $conn->error;
            }
        } else {
            $update_error = 'Event not found';
        }
        
        $stmt->close();
        $conn->close();
    }
}

// Handle file upload (CREATE)
$upload_success = false;
$upload_error = '';

if ($logged_in && isset($_POST['upload'])) {
    $event_name = trim($_POST['event_name']);
    $event_type = trim($_POST['event_type'] ?? 'Other');
    $celebrant1 = trim($_POST['celebrant1']);
    $celebrant2 = trim($_POST['celebrant2']);
    $event_date = trim($_POST['event_date']);
    
    if (empty($event_name) || empty($celebrant1)) {
        $upload_error = 'Please fill in event name and at least one name';
    } elseif ($event_type === 'Wedding' && empty($celebrant2)) {
        $upload_error = 'Name 2 is required for weddings';
    } elseif (!empty($event_date)) {
        // Validate event date is not more than 7 days in the future
        $event_date_obj = DateTime::createFromFormat('Y-m-d', $event_date);
        $today = new DateTime();
        $today->setTime(0, 0, 0); // Set to start of day for date-only comparison
        $event_date_obj->setTime(0, 0, 0); // Set to start of day for date-only comparison
        $max_date = (clone $today)->modify('+7 days');
        
        if ($event_date_obj < $today) {
            $upload_error = 'Event date cannot be in the past';
        } elseif ($event_date_obj > $max_date) {
            $upload_error = 'Events cannot be uploaded more than 7 days before the event date';
        }
    }
    
    if (empty($upload_error) && (!isset($_FILES['programme']) || $_FILES['programme']['error'] !== UPLOAD_ERR_OK)) {
        $upload_error = 'Please select a PDF file to upload';
    } else {
        // Create event slug (safe directory name)
        $event_slug = preg_replace('/[^a-z0-9-]/', '', strtolower(str_replace(' ', '-', $event_name)));
        
        // Create event directory if it doesn't exist
        $event_dir = __DIR__ . '/events/' . $event_slug;
        if (!is_dir($event_dir)) {
            mkdir($event_dir, 0755, true);
        }
        
        // Validate file type
        $file = $_FILES['programme'];
        $allowed_types = ['application/pdf'];
        $file_type = mime_content_type($file['tmp_name']);
        
        if (!in_array($file_type, $allowed_types)) {
            $upload_error = 'Only PDF files are allowed';
        } else {
            // Save file
            $filename = 'programme.pdf';
            $destination = $event_dir . '/' . $filename;
            
            if (move_uploaded_file($file['tmp_name'], $destination)) {
                // Save event data to database
                $conn = getDBConnection();
                
                // Check if event slug already exists
                $stmt = $conn->prepare("SELECT id FROM events WHERE event_slug = ?");
                $stmt->bind_param("s", $event_slug);
                $stmt->execute();
                $result = $stmt->get_result();
                
                if ($result->num_rows > 0) {
                    // Update existing event
                    $celebrant2_value = empty($celebrant2) ? null : $celebrant2;
                    $stmt = $conn->prepare("UPDATE events SET event_name = ?, event_type = ?, celebrant1 = ?, celebrant2 = ?, event_date = ?, programme_filename = ? WHERE event_slug = ?");
                    $stmt->bind_param("sssssss", $event_name, $event_type, $celebrant1, $celebrant2_value, $event_date, $filename, $event_slug);
                } else {
                    // Insert new event (admin creates events without user_id - system events)
                    // Make celebrant2 optional (empty string becomes NULL)
                    $celebrant2_value = empty($celebrant2) ? null : $celebrant2;
                    // Admin events have user_id = 0
                    $admin_user_id = 0;
                    $stmt = $conn->prepare("INSERT INTO events (user_id, event_slug, event_name, event_type, celebrant1, celebrant2, event_date, programme_filename) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                    $stmt->bind_param("isssssss", $admin_user_id, $event_slug, $event_name, $event_type, $celebrant1, $celebrant2_value, $event_date, $filename);
                }
                
                if ($stmt->execute()) {
                    $stmt->close();
                    $conn->close();
                    
                    $upload_success = true;
                    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
                    $host = $_SERVER['HTTP_HOST'];
                    $base_url = $protocol . '://' . $host . dirname($_SERVER['SCRIPT_NAME']);
                    $event_url = $base_url . '/index.php?event=' . urlencode($event_slug);
                    $qr_url = 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=' . urlencode($event_url);
                    $upload_message = "Event created successfully!<br><br>";
                    $upload_message .= "Share this link: <strong>" . htmlspecialchars($event_url) . "</strong><br><br>";
                    $upload_message .= "<div style='text-align: center; margin-top: 20px;'>";
                    $upload_message .= "<strong>QR Code:</strong><br>";
                    $upload_message .= "<img src='" . htmlspecialchars($qr_url) . "' alt='QR Code' style='margin-top: 10px; border: 1px solid #ddd; padding: 10px; background: white;'><br>";
                    $upload_message .= "<a href='qr_generator.php?event=" . urlencode($event_slug) . "&size=500' target='_blank' style='font-size: 12px; color: #2c3e50; margin-top: 10px; display: inline-block;'>Download Larger QR Code</a>";
                    $upload_message .= "</div>";
                } else {
                    $stmt->close();
                    $conn->close();
                    $upload_error = 'Failed to save event data to database.';
                }
            } else {
                $upload_error = 'Failed to upload file. Please check directory permissions.';
            }
        }
    }
}


// Success messages
$deleted_success = isset($_GET['deleted']) && $_GET['deleted'] == '1';
$updated_success = isset($_GET['updated']) && $_GET['updated'] == '1';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin - Evently</title>
    <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@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        html, body {
            height: 100%;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            background-color: #000000;
            color: #333;
            padding: 0;
            margin: 0;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

        .navbar {
            background-color: #ffffff;
            padding: 15px 20px;
            border-bottom: 1px solid #e0e0e0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .navbar-brand {
            color: #000000;
            font-family: 'Inter', sans-serif;
            font-size: 20px;
            font-weight: 700;
            text-decoration: none;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .navbar-brand img {
            height: 30px;
            width: auto;
        }

        .navbar-nav {
            display: flex;
            gap: 20px;
            align-items: center;
        }

        .navbar-nav a {
            color: #000000;
            text-decoration: none;
            font-size: 14px;
            transition: opacity 0.2s;
        }

        .navbar-nav a:hover {
            opacity: 0.7;
        }

        .navbar-nav span {
            color: #000000;
        }

        .hamburger {
            display: none;
            flex-direction: column;
            cursor: pointer;
            padding: 5px;
            gap: 4px;
        }

        .hamburger span {
            width: 25px;
            height: 3px;
            background-color: #000000;
            transition: all 0.3s;
        }

        .hamburger.active span:nth-child(1) {
            transform: rotate(45deg) translate(5px, 5px);
        }

        .hamburger.active span:nth-child(2) {
            opacity: 0;
        }

        .hamburger.active span:nth-child(3) {
            transform: rotate(-45deg) translate(7px, -6px);
        }

        @media (max-width: 768px) {
            .hamburger {
                display: flex;
            }

            .navbar-nav {
                position: fixed;
                top: 60px;
                left: 0;
                right: 0;
                background-color: #ffffff;
                flex-direction: column;
                padding: 20px;
                border-bottom: 1px solid #e0e0e0;
                box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
                transform: translateY(-100%);
                opacity: 0;
                visibility: hidden;
                transition: all 0.3s ease;
                z-index: 1000;
            }

            .navbar-nav.active {
                transform: translateY(0);
                opacity: 1;
                visibility: visible;
            }

            .navbar-nav a,
            .navbar-nav span {
                padding: 12px 0;
                border-bottom: 1px solid #f0f0f0;
                width: 100%;
            }

            .navbar-nav a:last-child,
            .navbar-nav span:last-child {
                border-bottom: none;
            }
        }

        .content-wrapper {
            padding: 20px;
            flex: 1;
        }

        .footer {
            background-color: #ffffff;
            padding: 20px;
            border-top: 1px solid #e0e0e0;
            text-align: center;
            color: #666;
            font-size: 14px;
            margin-top: auto;
        }

        @media (max-width: 768px) {
            .container {
                padding: 20px 15px;
            }

            .content-wrapper {
                padding: 10px;
            }

            h1 {
                font-size: 24px;
                margin-bottom: 20px;
            }

            .form-group {
                margin-bottom: 15px;
            }

            input[type="text"],
            input[type="date"],
            select,
            textarea {
                font-size: 16px; /* Prevents zoom on iOS */
            }

            .btn {
                padding: 12px 20px;
                font-size: 16px;
            }
        }

        .nav-links {
            margin-bottom: 20px;
        }

        .nav-links a {
            color: #2c3e50;
            text-decoration: none;
            margin-right: 15px;
            font-size: 14px;
        }

        .nav-links a:hover {
            text-decoration: underline;
        }


        .container {
            max-width: 800px;
            margin: 0 auto;
            background-color: #ffffff;
            border-radius: 0;
            padding: 40px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
        }

        h1 {
            font-size: 28px;
            font-weight: 400;
            margin-bottom: 30px;
            color: #2c3e50;
        }

        .form-group {
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            font-size: 14px;
            font-weight: 500;
            color: #495057;
        }

        input[type="text"],
        input[type="date"],
        input[type="file"],
        input[type="password"] {
            width: 100%;
            padding: 12px;
            border: 1px solid #ced4da;
            border-radius: 0;
            font-size: 16px;
            font-family: inherit;
            transition: border-color 0.2s;
        }

        input[type="text"]:focus,
        input[type="date"]:focus,
        input[type="file"]:focus,
        input[type="password"]:focus {
            outline: none;
            border-color: #2c3e50;
        }

        .btn {
            padding: 12px 30px;
            background-color: #000000;
            color: #ffffff;
            border: none;
            border-radius: 0;
            font-size: 16px;
            cursor: pointer;
            transition: transform 0.2s, box-shadow 0.2s;
            width: 100%;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.4);
            background-color: #333333;
        }

        .btn-secondary {
            background-color: #000000;
        }

        .btn-secondary:hover {
            background-color: #333333;
        }

        .alert {
            padding: 15px;
            border-radius: 0;
            margin-bottom: 20px;
        }

        .alert-success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .alert-error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .events-list {
            margin-top: 40px;
            padding-top: 40px;
            border-top: 1px solid #e0e0e0;
        }

        .events-list h2 {
            font-size: 20px;
            margin-bottom: 20px;
            color: #2c3e50;
        }

        .events-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        .events-table th,
        .events-table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #e0e0e0;
        }

        .events-table th {
            background-color: #f8f9fa;
            font-weight: 500;
            color: #495057;
            font-size: 14px;
        }

        .events-table tr:hover {
            background-color: #f8f9fa;
        }

        .events-table td {
            vertical-align: middle;
        }

        .event-link {
            color: #2c3e50;
            font-size: 13px;
            word-break: break-all;
            text-decoration: none;
        }

        .event-link:hover {
            text-decoration: underline;
        }

        .event-name {
            font-weight: 500;
            color: #2c3e50;
        }

        .event-date {
            font-size: 13px;
            color: #6c757d;
        }

        .qr-code {
            text-align: center;
        }

        .qr-code img {
            border: 1px solid #e0e0e0;
            padding: 8px;
            background: white;
            border-radius: 4px;
            width: 80px;
            height: 80px;
        }

        .qr-link {
            font-size: 11px;
            color: #2c3e50;
            text-decoration: none;
            display: inline-block;
            margin-top: 5px;
        }

        .qr-link:hover {
            text-decoration: underline;
        }

        .logout-link {
            float: right;
            color: #6c757d;
            text-decoration: none;
            font-size: 14px;
        }

        .logout-link:hover {
            color: #2c3e50;
        }

        .event-actions {
            margin-top: 10px;
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        .event-actions a {
            padding: 8px 12px;
            font-size: 16px;
            border-radius: 4px;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 36px;
            height: 36px;
            transition: transform 0.2s, opacity 0.2s;
        }

        .event-actions a:hover {
            transform: scale(1.1);
            opacity: 0.9;
        }

        .event-actions a:active {
            transform: scale(0.95);
        }

        .event-actions a i {
            font-size: 16px;
        }
    </style>
    <script>
        // Make Name 2 required for weddings
        function updateName2Requirement() {
            const eventType = document.getElementById('event_type');
            const name2Field = document.getElementById('celebrant2');
            const name2Required = document.getElementById('celebrant2-required');
            
            if (eventType && name2Field && name2Required) {
                if (eventType.value === 'Wedding') {
                    name2Field.required = true;
                    name2Required.style.display = 'inline';
                    name2Field.placeholder = 'e.g., Jane Smith (required for weddings)';
                } else {
                    name2Field.required = false;
                    name2Required.style.display = 'none';
                    name2Field.placeholder = 'e.g., Jane Smith (optional for single person events)';
                }
            }
        }
        
        // Add event listener when page loads
        document.addEventListener('DOMContentLoaded', function() {
            const eventType = document.getElementById('event_type');
            if (eventType) {
                eventType.addEventListener('change', updateName2Requirement);
                updateName2Requirement(); // Check on page load
            }
        });
    </script>
</head>
<body>
    <nav class="navbar">
        <a href="admin.php" class="navbar-brand">
            <img src="assets/img/logo.svg" alt="Evently">
            <span>Evently - Admin Panel</span>
        </a>
        <div class="hamburger" onclick="toggleMenu()">
            <span></span>
            <span></span>
            <span></span>
        </div>
        <div class="navbar-nav" id="navbarNav">
            <a href="admin.php">Upload Event</a>
            <a href="admin_events.php">View Events</a>
            <a href="admin_password.php">Change Password</a>
            <span><?php echo htmlspecialchars($_SESSION['admin_username'] ?? 'Admin'); ?></span>
            <a href="?logout=1">Logout</a>
        </div>
    </nav>
    <div class="content-wrapper">
    <div class="container">
            <h1><?php echo $editing_event ? 'Edit Event' : 'Upload Event Programme'; ?></h1>
            
            <?php if ($deleted_success): ?>
                <div class="alert alert-success">Event deleted successfully!</div>
            <?php endif; ?>
            
            <?php if ($updated_success): ?>
                <div class="alert alert-success">Event updated successfully!</div>
            <?php endif; ?>
            
            <?php if ($upload_success): ?>
                <div class="alert alert-success">
                    <?php echo $upload_message; ?>
                </div>
            <?php endif; ?>
            
            <?php if ($upload_error): ?>
                <div class="alert alert-error"><?php echo htmlspecialchars($upload_error); ?></div>
            <?php endif; ?>
            
            <?php if ($update_error): ?>
                <div class="alert alert-error"><?php echo htmlspecialchars($update_error); ?></div>
            <?php endif; ?>
            
            <?php if ($editing_event): ?>
                <a href="admin.php" style="color: #2c3e50; text-decoration: none; margin-bottom: 20px; display: inline-block;">← Back to Create</a>
            <?php endif; ?>
            
            <form method="POST" enctype="multipart/form-data">
                <?php if ($editing_event): ?>
                    <input type="hidden" name="event_id" value="<?php echo $editing_event['id']; ?>">
                <?php endif; ?>
                
                <div class="form-group">
                    <label for="event_type">Event Type *</label>
                    <select id="event_type" name="event_type" required style="width: 100%; padding: 12px; border: 1px solid #ced4da; border-radius: 0; font-size: 16px; font-family: inherit;">
                        <option value="Wedding" <?php echo (isset($editing_event['event_type']) && $editing_event['event_type'] === 'Wedding') ? 'selected' : ''; ?>>Wedding</option>
                        <option value="Funeral" <?php echo (isset($editing_event['event_type']) && $editing_event['event_type'] === 'Funeral') ? 'selected' : ''; ?>>Funeral</option>
                        <option value="Memorial" <?php echo (isset($editing_event['event_type']) && $editing_event['event_type'] === 'Memorial') ? 'selected' : ''; ?>>Memorial Service</option>
                        <option value="Anniversary" <?php echo (isset($editing_event['event_type']) && $editing_event['event_type'] === 'Anniversary') ? 'selected' : ''; ?>>Anniversary</option>
                        <option value="Birthday" <?php echo (isset($editing_event['event_type']) && $editing_event['event_type'] === 'Birthday') ? 'selected' : ''; ?>>Birthday</option>
                        <option value="Graduation" <?php echo (isset($editing_event['event_type']) && $editing_event['event_type'] === 'Graduation') ? 'selected' : ''; ?>>Graduation</option>
                        <option value="Baptism" <?php echo (isset($editing_event['event_type']) && $editing_event['event_type'] === 'Baptism') ? 'selected' : ''; ?>>Baptism</option>
                        <option value="Other" <?php echo (!isset($editing_event['event_type']) || $editing_event['event_type'] === 'Other') ? 'selected' : ''; ?>>Other</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="event_name">Event Name *</label>
                    <input type="text" id="event_name" name="event_name" required placeholder="e.g., John & Jane Wedding, Memorial Service, etc." value="<?php echo htmlspecialchars($editing_event['event_name'] ?? ''); ?>">
                </div>
                
                <div class="form-group">
                    <label for="celebrant1">Name 1 *</label>
                    <input type="text" id="celebrant1" name="celebrant1" required placeholder="e.g., John Doe" value="<?php echo htmlspecialchars($editing_event['celebrant1'] ?? ''); ?>">
                </div>
                
                <div class="form-group">
                    <label for="celebrant2">Name 2 <span id="celebrant2-required" style="display: none; color: #dc3545;">*</span></label>
                    <input type="text" id="celebrant2" name="celebrant2" placeholder="e.g., Jane Smith (optional for single person events)" value="<?php echo htmlspecialchars($editing_event['celebrant2'] ?? ''); ?>">
                </div>
                
                <div class="form-group">
                    <label for="event_date">Event Date</label>
                    <input type="date" id="event_date" name="event_date" value="<?php echo htmlspecialchars($editing_event['event_date'] ?? ''); ?>">
                </div>
                
                <div class="form-group">
                    <label for="header_image">Header Image (Optional)</label>
                    <input type="file" id="header_image" name="header_image" accept="image/jpeg,image/jpg,image/png,image/gif,image/webp">
                    <small style="display: block; margin-top: 5px; color: #6c757d; font-size: 12px;">Recommended: 1200x400px or similar wide format. JPG, PNG, GIF, or WebP.</small>
                    <?php if ($editing_event && !empty($editing_event['header_image'])): ?>
                        <div style="margin-top: 10px;">
                            <p style="font-size: 12px; color: #6c757d; margin-bottom: 5px;">Current header image:</p>
                            <img src="events/<?php echo htmlspecialchars($editing_event['event_slug']); ?>/<?php echo htmlspecialchars($editing_event['header_image']); ?>" alt="Current header" style="max-width: 200px; max-height: 100px; border: 1px solid #e0e0e0;">
                        </div>
                    <?php endif; ?>
                </div>
                
                <div class="form-group">
                    <label for="programme">Programme PDF <?php echo $editing_event ? '(Leave empty to keep current file)' : '*'; ?></label>
                    <input type="file" id="programme" name="programme" accept=".pdf,application/pdf" <?php echo $editing_event ? '' : 'required'; ?>>
                </div>
                
                <?php if ($editing_event): ?>
                    <button type="submit" name="update" class="btn">Update Event</button>
                    <a href="admin.php" class="btn btn-secondary" style="margin-left: 10px; text-decoration: none; display: inline-block;">Cancel</a>
                <?php else: ?>
                    <button type="submit" name="upload" class="btn">Upload Programme</button>
                <?php endif; ?>
            </form>
    </div>
    </div>
    <footer class="footer">
        <p>&copy; <?php echo date('Y'); ?> Evently. All rights reserved.</p>
    </footer>
    <script>
        // Hamburger menu toggle
        function toggleMenu() {
            const nav = document.getElementById('navbarNav');
            const hamburger = document.querySelector('.hamburger');
            if (nav && hamburger) {
                nav.classList.toggle('active');
                hamburger.classList.toggle('active');
            }
        }

        // Close menu when clicking outside
        document.addEventListener('click', function(event) {
            const nav = document.getElementById('navbarNav');
            const hamburger = document.querySelector('.hamburger');
            const navbar = document.querySelector('.navbar');
            
            if (nav && hamburger && navbar && !navbar.contains(event.target) && nav.classList.contains('active')) {
                nav.classList.remove('active');
                hamburger.classList.remove('active');
            }
        });
    </script>
</body>
</html>


