<?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' => true,
    'site_name' => 'EventPortal',
    'logo_url' => '',
    'events' => [],
    'total_pages' => 1,
    'page' => 1
];

try {
    $stmt_c = $pdo->query("SELECT key, value FROM system_settings");
    $configs = $stmt_c->fetchAll(PDO::FETCH_KEY_PAIR) ?: [];
    
    $response['site_name'] = $configs['site_name'] ?? 'EventPortal';
    $response['logo_url'] = $configs['site_logo'] ?? '';

    $limit = 9;
    $page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
    $offset = ($page - 1) * $limit;

    $allowedIds = null;
    if (isLoggedIn()) {
        $allowedIds = getAccessibleEventIdsForUser(getCurrentUser()['id'], getCurrentUser()['role'], $pdo);
    }

    $count_q = "SELECT COUNT(*) FROM events WHERE start_date > NOW() AND status = 'published'";
    $data_q = "SELECT * FROM events WHERE start_date > NOW() AND status = 'published'";

    if ($allowedIds !== null) {
        if (!empty($allowedIds)) {
            $placeholders = implode(',', array_fill(0, count($allowedIds), '?'));
            $count_q .= " AND id IN ($placeholders)";
            $data_q .= " AND id IN ($placeholders)";
        } else {
            $count_q .= " AND 1=0";
            $data_q .= " AND 1=0";
        }
    }

    $stmt_count = $pdo->prepare($count_q);
    if ($allowedIds !== null && !empty($allowedIds)) {
        $stmt_count->execute($allowedIds);
    } else {
        $stmt_count->execute();
    }
    $total_records = (int)$stmt_count->fetchColumn();
    $total_pages = ceil($total_records / $limit);

    $data_q .= " ORDER BY start_date ASC LIMIT ? OFFSET ?";
    $stmt_ev = $pdo->prepare($data_q);
    
    $bindIdx = 1;
    if ($allowedIds !== null && !empty($allowedIds)) {
        foreach ($allowedIds as $idVal) {
            $stmt_ev->bindValue($bindIdx++, $idVal, PDO::PARAM_INT);
        }
    }
    $stmt_ev->bindValue($bindIdx++, $limit, PDO::PARAM_INT);
    $stmt_ev->bindValue($bindIdx++, $offset, PDO::PARAM_INT);
    $stmt_ev->execute();
    
    $response['events'] = $stmt_ev->fetchAll(PDO::FETCH_ASSOC) ?: [];
    $response['total_pages'] = max(1, $total_pages);
    $response['page'] = $page;
} catch (PDOException $e) {
    $response['success'] = false;
}

echo json_encode($response);
