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

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

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

// Check if event ID is provided
if (!isset($_POST['id']) || empty($_POST['id'])) {
    echo json_encode(['success' => false, 'message' => 'Event ID is required']);
    exit;
}

$eventId = (int)$_POST['id'];

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;
    $status = $_POST['status'] ?? 'upcoming';
    
    // Update database
    $stmt = $pdo->prepare("
        UPDATE events SET
            event_title = :event_title, 
            event_description = :event_description, 
            event_date = :event_date, 
            event_time = :event_time, 
            event_location = :event_location, 
            event_type = :event_type, 
            max_participants = :max_participants, 
            registration_fee = :registration_fee, 
            status = :status, 
            updated_at = NOW()
        WHERE id = :id
    ");
    
    $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,
        ':id' => $eventId
    ]);
    
    // 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 updated successfully',
        'event_id' => $eventId
    ]);
    
} catch (PDOException $e) {
    error_log('Error updating event: ' . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
} catch (Exception $e) {
    error_log('General error updating event: ' . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>
