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

// Check if logged in
if (!isset($_SESSION['user_logged_in']) || $_SESSION['user_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

$user_id = $_SESSION['user_id'] ?? 0;

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

// Handle event creation
$create_success = false;
$create_error = '';

if (isset($_POST['create_event'])) {
    $event_name = trim($_POST['event_name'] ?? '');
    $event_type = trim($_POST['event_type'] ?? 'Other');
    $name1 = trim($_POST['name1'] ?? '');
    $name2 = trim($_POST['name2'] ?? '');
    $event_date = trim($_POST['event_date'] ?? '');
    
    if (empty($event_name) || empty($name1)) {
        $create_error = 'Please fill in event name and at least one name';
    } elseif ($event_type === 'Wedding' && empty($name2)) {
        $create_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) {
            $create_error = 'Event date cannot be in the past';
        } elseif ($event_date_obj > $max_date) {
            $create_error = 'Events cannot be uploaded more than 7 days before the event date';
        }
    }
    
    if (empty($create_error)) {
        // Check if file was uploaded
        if (!isset($_FILES['programme'])) {
            $create_error = 'Please select a PDF file to upload';
        } elseif (isset($_FILES['programme']['error']) && $_FILES['programme']['error'] !== UPLOAD_ERR_OK) {
            // Provide specific error messages based on upload error code
            $upload_errors = [
                UPLOAD_ERR_INI_SIZE => 'File exceeds the maximum upload size limit set by the server. Please reduce file size or contact administrator.',
                UPLOAD_ERR_FORM_SIZE => 'File exceeds the maximum upload size limit set by the form. Please reduce file size.',
                UPLOAD_ERR_PARTIAL => 'File was only partially uploaded. Please try again.',
                UPLOAD_ERR_NO_FILE => 'Please select a PDF file to upload',
                UPLOAD_ERR_NO_TMP_DIR => 'Server error: Missing temporary folder. Please contact administrator.',
                UPLOAD_ERR_CANT_WRITE => 'Server error: Failed to write file to disk. Please contact administrator.',
                UPLOAD_ERR_EXTENSION => 'File upload was stopped by a server extension. Please contact administrator.'
            ];
            $error_code = $_FILES['programme']['error'];
            $create_error = $upload_errors[$error_code] ?? 'File upload error (Code: ' . $error_code . '). Please try again.';
        } elseif (!isset($_FILES['programme']['tmp_name']) || empty($_FILES['programme']['tmp_name']) || !is_uploaded_file($_FILES['programme']['tmp_name'])) {
            $create_error = 'File upload failed. Please check that the file was selected and try again.';
        }
    }
    
    if (empty($create_error)) {
        // Create event slug
        $event_slug = preg_replace('/[^a-z0-9-]/', '', strtolower(str_replace(' ', '-', $event_name)));
        
        // Check if slug already exists globally, append number if needed
        $conn = getDBConnection();
        $original_slug = $event_slug;
        $counter = 1;
        while (true) {
            $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) {
                $stmt->close();
                break;
            }
            $event_slug = $original_slug . '-' . $counter;
            $counter++;
            $stmt->close();
        }
        
        // Ensure events directory exists
        $events_base_dir = __DIR__ . '/events';
        if (!is_dir($events_base_dir)) {
            if (!mkdir($events_base_dir, 0755, true)) {
                $create_error = 'Failed to create events directory. Please check server permissions.';
            }
        }
        
        // Create event directory
        $event_dir = $events_base_dir . '/' . $event_slug;
        if (!is_dir($event_dir)) {
            if (!mkdir($event_dir, 0755, true)) {
                $create_error = 'Failed to create event directory. Please check server permissions.';
            }
        }
        
        // Check if directory is writable
        if (empty($create_error) && !is_writable($event_dir)) {
            $create_error = 'Event directory is not writable. Please check server permissions.';
        }
        
        // Validate and save file
        if (empty($create_error)) {
            $file = $_FILES['programme'];
            
            // Check if file was actually uploaded
            if (!isset($file['tmp_name']) || !is_uploaded_file($file['tmp_name'])) {
                $create_error = 'File upload failed. Please check file size limits and try again.';
            } elseif (!file_exists($file['tmp_name'])) {
                $create_error = 'Uploaded file not found. Please try again.';
            } else {
                $allowed_types = ['application/pdf'];
                $file_type = mime_content_type($file['tmp_name']);
                
                if (!in_array($file_type, $allowed_types)) {
                    $create_error = 'Only PDF files are allowed. Detected type: ' . htmlspecialchars($file_type);
                } else {
                    $filename = 'programme.pdf';
                    $destination = $event_dir . '/' . $filename;
                    
                    // Handle header image upload (optional)
                    $header_image_filename = 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)) {
                            $image_extension = pathinfo($header_image['name'], PATHINFO_EXTENSION);
                            $header_image_filename = 'header.' . strtolower($image_extension);
                            $header_image_destination = $event_dir . '/' . $header_image_filename;
                            
                            if (!move_uploaded_file($header_image['tmp_name'], $header_image_destination)) {
                                $create_error = 'Failed to upload header image. Please check directory permissions.';
                            }
                        } else {
                            $create_error = 'Header image must be JPG, PNG, GIF, or WebP format.';
                        }
                    }
                    
                    if (empty($create_error) && move_uploaded_file($file['tmp_name'], $destination)) {
                        // Save to database
                        $name2_value = empty($name2) ? null : $name2;
                        $stmt = $conn->prepare("INSERT INTO events (user_id, event_slug, event_name, event_type, celebrant1, celebrant2, event_date, programme_filename, header_image) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                        $stmt->bind_param("issssssss", $user_id, $event_slug, $event_name, $event_type, $name1, $name2_value, $event_date, $filename, $header_image_filename);
                        
                        if ($stmt->execute()) {
                            $create_success = true;
                            $created_event_slug = $event_slug;
                        } else {
                            $create_error = 'Failed to save event. Please try again.';
                        }
                        $stmt->close();
                    } else {
                        if (empty($create_error)) {
                            $create_error = 'Failed to upload file. Please check directory permissions.';
                        }
                    }
                }
            }
        }
        $conn->close();
    }
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Evently - Share Your Event Programme</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">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

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

        .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;
            }
        }

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

        .content-wrapper {
            padding: 20px;
        }

        .hero-section {
            text-align: center;
            padding: 60px 20px;
            color: white;
            margin-bottom: 40px;
        }

        .hero-section h1 {
            font-size: 48px;
            font-weight: 300;
            margin-bottom: 15px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.2);
        }

        .hero-section p {
            font-size: 20px;
            opacity: 0.95;
            max-width: 600px;
            margin: 0 auto;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .main-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
            margin-bottom: 40px;
        }

        .card {
            background-color: #ffffff;
            border-radius: 0;
            padding: 30px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
        }

        .card h2 {
            font-size: 24px;
            font-weight: 400;
            margin-bottom: 20px;
            color: #2c3e50;
            border-bottom: 2px solid #667eea;
            padding-bottom: 10px;
        }

        .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"] {
            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 {
            outline: none;
            border-color: #667eea;
        }

        .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;
        }

        .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;
        }


        .admin-link {
            position: fixed;
            bottom: 20px;
            right: 20px;
            padding: 10px 20px;
            background-color: rgba(255, 255, 255, 0.9);
            color: #667eea;
            text-decoration: none;
            border-radius: 6px;
            font-size: 14px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
            transition: background-color 0.2s;
        }

        .admin-link:hover {
            background-color: #ffffff;
        }

        @media (max-width: 768px) {
            .main-content {
                grid-template-columns: 1fr;
            }

            .hero-section h1 {
                font-size: 32px;
            }

            .hero-section p {
                font-size: 16px;
            }

            .container {
                padding: 15px;
            }

            .card {
                padding: 20px;
            }

            .content-wrapper {
                padding: 10px;
            }

            .hero-section {
                padding: 40px 15px;
            }

            h2 {
                font-size: 20px;
            }

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

            input[type="text"],
            input[type="date"],
            select {
                font-size: 16px; /* Prevents zoom on iOS */
            }
        }
    </style>
</head>
<body>
    <nav class="navbar">
        <a href="home.php" class="navbar-brand">
            <img src="assets/img/logo.svg" alt="Evently">
            <span>Evently</span>
        </a>
        <div class="hamburger" onclick="toggleMenu()">
            <span></span>
            <span></span>
            <span></span>
        </div>
        <div class="navbar-nav" id="navbarNav">
            <a href="home.php">Create Event</a>
            <a href="my_events.php">My Events</a>
            <span><?php echo htmlspecialchars($_SESSION['user_username'] ?? 'User'); ?></span>
            <a href="?logout=1">Logout</a>
        </div>
    </nav>
    <div class="content-wrapper">
    <div class="hero-section">
        <h1>Evently</h1>
        <p>Create and share event programmes for weddings, funerals, memorials, and all special occasions</p>
    </div>

    <div class="container">
        <div class="main-content">
            <div class="card">
                <h2>Create Your Event</h2>
                
                <?php if ($create_success): ?>
                    <div class="alert alert-success">
                        <strong>Event created successfully!</strong><br>
                        <a href="index.php?event=<?php echo urlencode($created_event_slug); ?>" style="color: #155724; text-decoration: underline;">View your event →</a>
                    </div>
                <?php endif; ?>
                
                <?php if ($create_error): ?>
                    <div class="alert alert-error"><?php echo htmlspecialchars($create_error); ?></div>
                <?php endif; ?>
                
                <form method="POST" enctype="multipart/form-data">
                    <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">Wedding</option>
                            <option value="Funeral">Funeral</option>
                            <option value="Memorial">Memorial Service</option>
                            <option value="Anniversary">Anniversary</option>
                            <option value="Birthday">Birthday</option>
                            <option value="Graduation">Graduation</option>
                            <option value="Baptism">Baptism</option>
                            <option value="Other">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">
                    </div>
                    
                    <div class="form-group">
                        <label for="name1">Name 1 *</label>
                        <input type="text" id="name1" name="name1" required placeholder="e.g., John Doe">
                    </div>
                    
                    <div class="form-group">
                        <label for="name2">Name 2 <span id="name2-required" style="display: none; color: #dc3545;">*</span></label>
                        <input type="text" id="name2" name="name2" placeholder="e.g., Jane Smith (optional)">
                    </div>
                    
                    <div class="form-group">
                        <label for="event_date">Event Date</label>
                        <input type="date" id="event_date" name="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>
                    </div>
                    
                    <div class="form-group">
                        <label for="programme">Programme PDF *</label>
                        <input type="file" id="programme" name="programme" accept=".pdf,application/pdf" required>
                    </div>
                    
                    <button type="submit" name="create_event" class="btn">Create Event</button>
                </form>
            </div>

            <div class="card">
                <h2>How It Works</h2>
                <ol style="line-height: 2; color: #495057;">
                    <li><strong>Create Your Event:</strong> Fill in the form with event details and upload your programme PDF</li>
                    <li><strong>Get Your Link:</strong> You'll receive a unique link to share with your guests</li>
                    <li><strong>Share & Download:</strong> Guests can view or download the programme directly from their phones</li>
                    <li><strong>QR Code:</strong> Each event gets a QR code for easy sharing at the venue</li>
                </ol>
                <p style="margin-top: 20px; color: #6c757d; font-size: 14px;">
                    <strong>Perfect for:</strong> Weddings, Funerals, Memorials, Anniversaries, Celebrations, and more!
                </p>
            </div>
        </div>
    </div>
    </div>

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

        // Make Name 2 required for weddings
        document.addEventListener('DOMContentLoaded', function() {
            const eventType = document.getElementById('event_type');
            if (eventType) {
                eventType.addEventListener('change', function() {
                    const name2Field = document.getElementById('name2');
                    const name2Required = document.getElementById('name2-required');
                    
                    if (name2Field && name2Required) {
                        if (this.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)';
                        }
                    }
                });
                eventType.dispatchEvent(new Event('change'));
            }
        });
    </script>
    <footer class="footer">
        <p>&copy; <?php echo date('Y'); ?> Evently. All rights reserved.</p>
    </footer>
</body>
</html>
