<?php
declare(strict_types=1);

// Christo Lochenberg Developments | info@christodev.co.za | +27 61 523 9126

// Start the session securely
session_start();

// Load the security helper globally
require_once 'security_helper.php';

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

// Check if the currently logged-in user has admin privileges
function isAdmin(): bool {
    return isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'admin';
}

// Check if the currently logged-in user is a staff member
function isStaff(): bool {
    return isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'staff';
}

// Check if the currently logged-in user is a client
function isClient(): bool {
    return isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'client';
}

// Check if the currently logged-in user is a partner/agency
function isPartner(): bool {
    return isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'partner';
}

// Generate a self-hosted math captcha
function generateMathCaptcha(): array {
    $num1 = random_int(1, 10);
    $num2 = random_int(1, 10);
    $_SESSION['captcha_answer'] = $num1 + $num2;
    return ['num1' => $num1, 'num2' => $num2];
}

// Validate the self-hosted math captcha
function validateCaptcha(string $answer): bool {
    if (!isset($_SESSION['captcha_answer'])) {
        return false;
    }

    $isValid = (int)$answer === (int)$_SESSION['captcha_answer'];
    
    // Prevent reuse of the same captcha answer (stops replay attacks)
    unset($_SESSION['captcha_answer']);
    
    return $isValid;
}