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

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

if (!isset($_SESSION['admin_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

// Get event data from POST request
$title = $_POST['title'] ?? '';
$description = $_POST['description'] ?? '';
$location = $_POST['location'] ?? '';
$start_date = $_POST['start_date'] ?? '';
$end_date = $_POST['end_date'] ?? '';
$start_time = $_POST['start_time'] ?? null;
$end_time = $_POST['end_time'] ?? null;
$all_day = isset($_POST['all_day']) ? (int)$_POST['all_day'] : 0;
$recurring = isset($_POST['recurring']) ? (int)$_POST['recurring'] : 0;
$recurrence_pattern = $_POST['recurrence_pattern'] ?? null;
$color = $_POST['color'] ?? '';
$status = $_POST['status'] ?? 'scheduled';
$max_participants = $_POST['max_participants'] ? (int)$_POST['max_participants'] : null;
$registration_required = isset($_POST['registration_required']) ? (int)$_POST['registration_required'] : 0;

// Validate required fields
if (empty($title) || empty($start_date)) {
    echo json_encode(['success' => false, 'message' => 'Title and start date are required']);
    exit();
}

// If end date is not provided, use start date
if (empty($end_date)) {
    $end_date = $start_date;
}

try {
    $conn = new PDO($dsn, $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Begin transaction
    $conn->beginTransaction();
    
    // Insert event into the database
    $stmt = $conn->prepare("
        INSERT INTO events (
            title, description, location, start_date, end_date, 
            start_time, end_time, all_day, recurring, recurrence_pattern,
            color, status, organizer_id, max_participants, registration_required,
            created_at, updated_at
        ) VALUES (
            ?, ?, ?, ?, ?,
            ?, ?, ?, ?, ?,
            ?, ?, ?, ?, ?,
            CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
        )
    ");
    
    $stmt->execute([
        $title, $description, $location, $start_date, $end_date,
        $start_time, $end_time, $all_day, $recurring, $recurrence_pattern,
        $color, $status, $_SESSION['admin_id'], $max_participants, $registration_required
    ]);
    
    $event_id = $conn->lastInsertId();
    
    // Log the action
    $stmt = $conn->prepare("
        INSERT INTO admin_logs (admin_id, action, details, created_at)
        VALUES (?, 'create_event', ?, CURRENT_TIMESTAMP)
    ");
    $stmt->execute([
        $_SESSION['admin_id'],
        'Created new event: ' . $title
    ]);
    
    $conn->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'Event created successfully',
        'event_id' => $event_id
    ]);
    
} catch (PDOException $e) {
    if ($conn) {
        $conn->rollBack();
    }
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
