<?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';

$response = [
    'is_logged_in' => isLoggedIn(),
    'csrf_token' => getCSRFToken(),
    'user' => null,
    'unread_notifications' => 0,
    'site_name' => 'EventPortal',
    'logo_url' => ''
];

try {
    // Fetch site configurations
    $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'] ?? '';

    if ($response['is_logged_in']) {
        $userSession = getCurrentUser();
        if ($userSession) {
            $stmt_user = $pdo->prepare("SELECT id, username, email, role, status, profile_picture_url FROM users WHERE id = ?");
            $stmt_user->execute([$userSession['id']]);
            $user = $stmt_user->fetch(PDO::FETCH_ASSOC);
            
            if ($user && $user['status'] === 'active') {
                $response['user'] = [
                    'id' => $user['id'],
                    'username' => $user['username'],
                    'email' => $user['email'],
                    'role' => $user['role'],
                    'status' => $user['status'],
                    'profile_picture_url' => $user['profile_picture_url']
                ];
                
                // Fetch unread notifications count
                $stmt_count = $pdo->prepare("
                    SELECT COUNT(*) FROM notifications 
                    WHERE user_id = ? AND channels_sent LIKE '%in_app%' AND is_read = FALSE
                ");
                $stmt_count->execute([$user['id']]);
                $response['unread_notifications'] = (int)$stmt_count->fetchColumn();
            } else {
                // Invalidate session if user status changed from active
                session_unset();
                session_destroy();
                $response['is_logged_in'] = false;
                $response['user'] = null;
            }
        }
    }
} catch (PDOException $e) { }

echo json_encode($response);
