<?php

declare(strict_types=1);

/**
 * Authentication Helpers
 *
 * Provides functions for managing user authentication state,
 * role-based access control, and session management for
 * the Gmind Institute application.
 *
 * Roles (per users.role ENUM):
 *   - super_admin   : Full system owner. Access to /super-admin/* panel.
 *   - admin         : Existing website admin. Access to /admin/* panel
 *                     (manages frontage: sliders, courses, gallery, blog, etc.).
 *   - branch_admin  : Branch owner. Access to /branch/* panel
 *                     (manages admissions, students, fees, exams, certificates).
 *   - staff         : Branch staff (future use).
 *   - student       : Student. Access to /dashboard and student features.
 */

/**
 * Check if a user is currently logged in.
 */
function isLoggedIn(): bool
{
    return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
}

/**
 * Check if the currently logged-in user has the super_admin role.
 */
function isSuperAdmin(): bool
{
    return isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'super_admin';
}

/**
 * Check if the currently logged-in user has the admin role (existing website admin).
 * Also returns true for super_admin (super_admin has access to everything).
 */
function isAdmin(): bool
{
    return isset($_SESSION['user_role']) && in_array($_SESSION['user_role'], ['admin', 'super_admin'], true);
}

/**
 * Check if the currently logged-in user has the branch_admin role.
 */
function isBranchAdmin(): bool
{
    return isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'branch_admin';
}

/**
 * Check if the currently logged-in user has the student role.
 */
function isStudent(): bool
{
    return isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'student';
}

/**
 * Get the currently authenticated user's data from the session.
 */
function getCurrentUser(): ?array
{
    if (!isLoggedIn()) {
        return null;
    }

    return [
        'id'          => $_SESSION['user_id'] ?? null,
        'name'        => $_SESSION['user_name'] ?? '',
        'email'       => $_SESSION['user_email'] ?? '',
        'role'        => $_SESSION['user_role'] ?? '',
        'avatar'      => $_SESSION['user_avatar'] ?? null,
        'branch_id'   => $_SESSION['branch_id'] ?? null,
        'branch_code' => $_SESSION['branch_code'] ?? null,
        'logged_in'   => $_SESSION['login_time'] ?? null,
    ];
}

/**
 * Get the current branch ID (for branch_admin users).
 * Returns null for non-branch users.
 */
function getCurrentBranchId(): ?int
{
    $bid = $_SESSION['branch_id'] ?? null;
    return $bid !== null ? (int) $bid : null;
}

/**
 * Get the current branch code (for branch_admin users).
 * Returns null for non-branch users.
 */
function getCurrentBranchCode(): ?string
{
    $code = $_SESSION['branch_code'] ?? null;
    return $code !== null && $code !== '' ? (string) $code : null;
}

/**
 * Require that a user is logged in.
 */
function requireLogin(): void
{
    if (!isLoggedIn()) {
        flash('error', 'Please log in to access this page.');
        redirect(BASE_PATH . '/login');
    }
}

/**
 * Require that the logged-in user has the admin role (existing website admin).
 */
function requireAdmin(): void
{
    if (!isAdmin()) {
        flash('error', 'You do not have permission to access this page.');
        redirect(BASE_PATH . '/');
    }
}

/**
 * Require that the logged-in user has the super_admin role.
 */
function requireSuperAdmin(): void
{
    if (!isSuperAdmin()) {
        flash('error', 'Super Admin access required.');
        redirect(BASE_PATH . '/super-admin/login');
    }
}

/**
 * Require that the logged-in user has the branch_admin role.
 */
function requireBranchAdmin(): void
{
    if (!isBranchAdmin()) {
        flash('error', 'Branch Admin access required.');
        redirect(BASE_PATH . '/branch/login');
    }
}

/**
 * Log in a user by setting session variables.
 *
 * Stores standard fields (id, name, email, role) plus branch_id and branch_code
 * for branch_admin users (used throughout the branch panel for filtering).
 */
function login(array $user): void
{
    session_regenerate_id(true);

    $_SESSION['user_id']      = $user['id'];
    $_SESSION['user_name']    = $user['name'] ?? '';
    $_SESSION['user_email']   = $user['email'] ?? '';
    $_SESSION['user_role']    = $user['role'] ?? 'student';
    $_SESSION['user_avatar']  = $user['avatar'] ?? null;
    $_SESSION['login_time']   = time();
    $_SESSION['branch_id']    = $user['branch_id'] ?? null;
    $_SESSION['branch_code']  = $user['branch_code'] ?? null;
}

/**
 * Log out the current user.
 */
function logout(): never
{
    $_SESSION = [];

    if (ini_get('session.use_cookies')) {
        $params = session_get_cookie_params();
        setcookie(
            session_name(),
            '',
            time() - 42000,
            $params['path'],
            $params['domain'],
            $params['secure'],
            $params['httponly']
        );
    }

    session_destroy();
    redirect(BASE_PATH . '/');
}
