<?php
declare(strict_types=1);

/**
 * --------------------------------------------------------------------------
 * SGAccount Global Helper Functions
 * --------------------------------------------------------------------------
 * Utilities for authentication, access control, CSRF protection,
 * flash messages, redirection, and sanitization.
 */

/* --------------------------------------------------------------------------
   SESSION INIT
-------------------------------------------------------------------------- */
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

/* --------------------------------------------------------------------------
   AUTHENTICATION HELPERS
-------------------------------------------------------------------------- */

/**
 * Redirect guests to login page if not logged in
 */
function require_login(): void
{
    if (empty($_SESSION['user_id'])) {
        redirect('/accounting/public/router.php?page=login');
    }
}

/**
 * Check if current user has one of the allowed roles
 *
 * Example: require_role('admin', 'manager');
 */
function require_role(string ...$roles): void
{
    $userRole = $_SESSION['role'] ?? null;

    if ($userRole === null || !in_array($userRole, $roles, true)) {
        http_response_code(403);
        echo "
        <!DOCTYPE html>
        <html lang='en'>
        <head>
          <meta charset='UTF-8'>
          <title>403 Access Denied | SGAccount</title>
          <link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/css/adminlte.min.css'>
          <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css'>
        </head>
        <body class='login-page bg-dark'>
          <div class='login-box'>
            <div class='card card-outline card-danger'>
              <div class='card-header text-center'>
                <h3><i class='fas fa-lock'></i> Access Denied</h3>
              </div>
              <div class='card-body text-center'>
                <p>You do not have permission to access this page.</p>
                <a href='/accounting/public/router.php?page=dashboard' class='btn btn-primary btn-block'>Return to Dashboard</a>
              </div>
            </div>
          </div>
        </body>
        </html>";
        exit;
    }
}

/**
 * Return true if a user is logged in
 */
function is_logged_in(): bool
{
    return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
}

/**
 * Safely log out user
 */
function logout_user(): void
{
    // Clear session data
    $_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();

    // Remove "remember_me" cookie if any
    if (isset($_COOKIE['remember_me'])) {
        setcookie('remember_me', '', time() - 3600, '/');
    }
}

/* --------------------------------------------------------------------------
   FLASH MESSAGES (Used for Toastr)
-------------------------------------------------------------------------- */

/**
 * Store flash message (auto-cleared on display)
 */
function set_flash(string $type, string $message): void
{
    $_SESSION["flash_{$type}"] = $message;
}

/**
 * Retrieve and clear a flash message
 */
function get_flash(string $type): ?string
{
    if (isset($_SESSION["flash_{$type}"])) {
        $msg = $_SESSION["flash_{$type}"];
        unset($_SESSION["flash_{$type}"]);
        return $msg;
    }
    return null;
}

/* --------------------------------------------------------------------------
   CSRF TOKEN UTILITIES
-------------------------------------------------------------------------- */

/**
 * Generate (or reuse) a CSRF token for the current session
 */
function csrf_token(): string
{
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }

    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }

    return $_SESSION['csrf_token'];
}

/**
 * Validate a CSRF token from a form or AJAX POST
 */
function validate_csrf($token): bool
{
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }

    if (!isset($_SESSION['csrf_token']) || empty($token)) {
        return false;
    }

    return hash_equals($_SESSION['csrf_token'], (string)$token);
}

/* --------------------------------------------------------------------------
   SANITIZATION HELPERS
-------------------------------------------------------------------------- */

/**
 * Escape string for HTML output
 */
function e(string $value): string
{
    return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}

/**
 * Safely get POST data (trimmed and sanitized)
 */
function post(string $key): ?string
{
    return isset($_POST[$key]) ? trim(htmlspecialchars($_POST[$key], ENT_QUOTES, 'UTF-8')) : null;
}

/**
 * Safely get GET data (trimmed and sanitized)
 */
function get(string $key): ?string
{
    return isset($_GET[$key]) ? trim(htmlspecialchars($_GET[$key], ENT_QUOTES, 'UTF-8')) : null;
}

/* --------------------------------------------------------------------------
   GENERAL UTILITIES
-------------------------------------------------------------------------- */

/**
 * Redirect safely and stop execution
 */
function redirect(string $url): void
{
    header("Location: {$url}");
    exit;
}
