<?php
require 'config.php';

session_start();

// Check if user is logged in
function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

// Redirect to login if not authenticated
function requireLogin() {
    if (!isLoggedIn()) {
        header("Location: login.html");
        exit();
    }
}

// Get current user data from session
function getCurrentUser() {
    if (!isLoggedIn()) {
        return null;
    }
    return $_SESSION['user_data'] ?? null;
}

// Return session data as JSON (for AJAX requests)
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    header('Content-Type: application/json');
    if (isLoggedIn()) {
        echo json_encode(['authenticated' => true, 'user_data' => $_SESSION['user_data'], 'role' => $_SESSION['user_role'] ?? 'user']);
    } else {
        echo json_encode(['authenticated' => false]);
    }
}
?>
