<?php
header('Content-Type: application/json');
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/auth.php';

if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Please log in to view events']);
    exit;
}

$response = [
    'success' => false,
    'message' => '',
    'event' => null,
    'agendas' => [],
    'sponsors' => [],
    'is_registered' => false
];

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($id <= 0) {
    $response['message'] = "Invalid Event ID.";
    echo json_encode($response);
    exit();
}

try {
    // 1. Fetch Event
    $stmt = $pdo->prepare("SELECT * FROM events WHERE id = ?");
    $stmt->execute([$id]);
    $event = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$event) {
        $response['message'] = "Event not found.";
        echo json_encode($response);
        exit();
    }

    if (isset($event['status']) && $event['status'] === 'draft') {
        $hasAccess = false;
        if (isLoggedIn()) {
            $currUser = getCurrentUser();
            if ($currUser['role'] === 'admin' || $currUser['role'] === 'organizer') {
                $hasAccess = true;
            }
        }
        if (!$hasAccess) {
            $response['message'] = "Event not found.";
            echo json_encode($response);
            exit();
        }
    }

    if (isLoggedIn()) {
        $allowedIds = getAccessibleEventIdsForUser(getCurrentUser()['id'], getCurrentUser()['role'], $pdo);
        if ($allowedIds !== null && !in_array($id, $allowedIds)) {
            $response['message'] = "Access Denied: This event is not permitted under your designation level.";
            echo json_encode($response);
            exit();
        }
    }

    $response['event'] = $event;

    // 2. Fetch Agendas
    $stmt_ag = $pdo->prepare("
        SELECT ea.*, sp.full_name as speaker_name 
        FROM event_agendas ea
        LEFT JOIN speaker_profiles sp ON ea.speaker_profile_id = sp.id
        WHERE ea.event_id = ?
        ORDER BY ea.agenda_date ASC, ea.start_time ASC
    ");
    $stmt_ag->execute([$id]);
    $response['agendas'] = $stmt_ag->fetchAll(PDO::FETCH_ASSOC) ?: [];

    // 3. Fetch Sponsors
    $stmt_spon = $pdo->prepare("
        SELECT es.tier, sp.company_name, sp.website_url 
        FROM event_sponsors es
        JOIN sponsor_profiles sp ON es.sponsor_profile_id = sp.id
        WHERE es.event_id = ?
        ORDER BY es.tier DESC, sp.company_name ASC
    ");
    $stmt_spon->execute([$id]);
    $response['sponsors'] = $stmt_spon->fetchAll(PDO::FETCH_ASSOC) ?: [];

    // 4. Check if current user is registered
    if (isLoggedIn()) {
        $currentUser = getCurrentUser();
        $stmt_reg = $pdo->prepare("SELECT COUNT(*) FROM registrations WHERE event_id = ? AND user_id = ?");
        $stmt_reg->execute([$id, $currentUser['id']]);
        $response['is_registered'] = $stmt_reg->fetchColumn() > 0;
    }

    $response['success'] = true;
} catch (PDOException $e) {
    $response['message'] = "Database error: " . $e->getMessage();
}

echo json_encode($response);
