<?php
require_once '../config/database.php';
require_once '../config/auth_enhanced.php';

header('Content-Type: application/json');

// Ensure only authenticated admin users can add events
if (!isAuthenticated() || !isAdmin()) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

try {
    $pdo = getDBConnection();
    
    // Validate input
    $requiredFields = ['event_title', 'event_date', 'event_type'];
    $missingFields = [];
    
    foreach ($requiredFields as $field) {
        if (empty($_POST[$field])) {
            $missingFields[] = $field;
        }
    }
    
    if (!empty($missingFields)) {
        echo json_encode([
            'success' => false, 
            'message' => 'Missing required fields: ' . implode(', ', $missingFields)
        ]);
        exit;
    }
    
    // Get form data
    $eventTitle = $_POST['event_title'];
    $eventDescription = $_POST['event_description'] ?? '';
    $eventDate = $_POST['event_date'];
    $eventTime = $_POST['event_time'] ?? null;
    $eventLocation = $_POST['event_location'] ?? '';
    $eventType = $_POST['event_type'];
    $maxParticipants = !empty($_POST['max_participants']) ? (int)$_POST['max_participants'] : null;
    $registrationFee = !empty($_POST['registration_fee']) ? (float)$_POST['registration_fee'] : 0.00;
    
    // Determine event status based on date
    $currentDate = date('Y-m-d');
    if ($eventDate > $currentDate) {
        $status = 'upcoming';
    } elseif ($eventDate == $currentDate) {
        $status = 'ongoing';
    } else {
        $status = 'completed';
    }
    
    // Insert into database
    $stmt = $pdo->prepare("
        INSERT INTO events (
            event_title, 
            event_description, 
            event_date, 
            event_time, 
            event_location, 
            event_type, 
            max_participants, 
            registration_fee, 
            status, 
            created_by, 
            created_at
        ) VALUES (
            :event_title, 
            :event_description, 
            :event_date, 
            :event_time, 
            :event_location, 
            :event_type, 
            :max_participants, 
            :registration_fee, 
            :status, 
            :created_by, 
            NOW()
        )
    ");
    
    $stmt->execute([
        ':event_title' => $eventTitle,
        ':event_description' => $eventDescription,
        ':event_date' => $eventDate,
        ':event_time' => $eventTime,
        ':event_location' => $eventLocation,
        ':event_type' => $eventType,
        ':max_participants' => $maxParticipants,
        ':registration_fee' => $registrationFee,
        ':status' => $status,
        ':created_by' => $_SESSION['user_id'] ?? 1
    ]);
    
    $eventId = $pdo->lastInsertId();
    
    // If file upload is provided, handle it
    if (isset($_FILES['event_banner']) && $_FILES['event_banner']['error'] == 0) {
        $uploadDir = '../../uploads/events/';
        
        // Create directory if it doesn't exist
        if (!file_exists($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }
        
        $fileName = 'event_' . $eventId . '_' . time() . '_' . basename($_FILES['event_banner']['name']);
        $targetFile = $uploadDir . $fileName;
        
        if (move_uploaded_file($_FILES['event_banner']['tmp_name'], $targetFile)) {
            // Update event with banner URL
            $relativePath = 'uploads/events/' . $fileName;
            $stmt = $pdo->prepare("UPDATE events SET event_banner_url = :banner_url WHERE id = :id");
            $stmt->execute([':banner_url' => $relativePath, ':id' => $eventId]);
        }
    }
    
    echo json_encode([
        'success' => true, 
        'message' => 'Event added successfully',
        'event_id' => $eventId
    ]);
    
} catch (PDOException $e) {
    error_log('Error adding event: ' . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
} catch (Exception $e) {
    error_log('General error adding event: ' . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>
