<?php
/**
 * User Authentication Module
 * Handles session verification, access control restrictions, and user data retrieval.
 */

// Ensure this file is not accessed directly
if (!defined('DS')) {
    exit('Direct access not permitted.');
}

/**
 * Checks if a user is currently logged in.
 *
 * @return bool True if logged in, false otherwise.
 */
function is_logged_in() {
    return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
}

/**
 * Enforces login requirement for a page.
 * If the user is not logged in, they are redirected to the login page.
 */
function require_login() {
    if (!is_logged_in()) {
        set_flash_message('error', 'You must be logged in to access that page.');
        redirect(SITE_URL . '/login.php');
    }
}

/**
 * Enforces guest-only access (e.g., for login/register pages).
 * If the user is already logged in, they are redirected to their account page.
 */
function require_guest() {
    if (is_logged_in()) {
        redirect(SITE_URL . '/account.php');
    }
}

/**
 * Securely retrieves the currently logged-in user's full record from the database.
 *
 * @param PDO $pdo The PDO database connection instance.
 * @return array|false Associative array of user data on success, or false if not found.
 */
function get_logged_in_user($pdo) {
    if (!is_logged_in()) {
        return false;
    }

    try {
        $stmt = $pdo->prepare("SELECT id, name, email, role, status, created_at FROM users WHERE id = :id LIMIT 1");
        $stmt->bindParam(':id', $_SESSION['user_id'], PDO::PARAM_INT);
        $stmt->execute();
        
        $user = $stmt->fetch();

        // If user is found but their status is 'blocked', force logout immediately
        if ($user && $user['status'] === 'blocked') {
            perform_logout();
            set_flash_message('error', 'Your account has been blocked by an administrator.');
            redirect(SITE_URL . '/login.php');
        }

        return $user;

    } catch (PDOException $e) {
        // Log the error securely and return false
        error_log("Error fetching logged in user: " . $e->getMessage());
        return false;
    }
}

/**
 * Safely destroys the user session and logs them out.
 * Clears the session array, destroys the session cookie, and ends the session.
 */
function perform_logout() {
    // Unset all of the session variables
    $_SESSION = array();

    // If it's desired to kill the session, also delete the session cookie
    if (ini_get("session.use_cookies")) {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000,
            $params["path"], $params["domain"],
            $params["secure"], $params["httponly"]
        );
    }

    // Finally, destroy the session
    session_destroy();
}