<?php

function admin()
{
    return $_SESSION['admin_user'] ?? null;
}

function is_admin_logged_in()
{
    return isset($_SESSION['admin_user']);
}

function require_admin()
{
    if (!is_admin_logged_in()) {
        redirect(BASE_URL . '/admin/login.php');
    }

    if (function_exists('get_setting')) {
        $timeoutMinutes = (int) get_setting('admin_session_timeout', '60');

        if ($timeoutMinutes <= 0) {
            $timeoutMinutes = 60;
        }

        $timeoutSeconds = $timeoutMinutes * 60;
        $lastActivity = $_SESSION['admin_last_activity'] ?? time();

        if ((time() - $lastActivity) > $timeoutSeconds) {
            logout_admin();
            redirect(BASE_URL . '/admin/login.php?timeout=1');
        }

        $_SESSION['admin_last_activity'] = time();
    }
}
function login_admin($adminUser)
{
    $_SESSION['admin_user'] = [
        'id' => $adminUser['id'],
        'role_id' => $adminUser['role_id'],
        'full_name' => $adminUser['full_name'],
        'email' => $adminUser['email'],
    ];

    $_SESSION['admin_last_activity'] = time();

    session_regenerate_id(true);
}

function logout_admin()
{
    unset($_SESSION['admin_user']);
    unset($_SESSION['admin_last_activity']);

    session_regenerate_id(true);
}

function customer()
{
    return $_SESSION['customer_user'] ?? null;
}

function is_customer_logged_in()
{
    return isset($_SESSION['customer_user']);
}

function require_customer()
{
    if (!is_customer_logged_in()) {
        redirect(BASE_URL . '/public/login.php');
    }
}

function login_customer($customerUser)
{
    $_SESSION['customer_user'] = [
        'id' => $customerUser['id'],
        'first_name' => $customerUser['first_name'],
        'last_name' => $customerUser['last_name'],
        'email' => $customerUser['email'],
    ];

    session_regenerate_id(true);
}

function logout_customer()
{
    unset($_SESSION['customer_user']);
    session_regenerate_id(true);
}

function generate_referral_code($firstName = 'LOVEU')
{
    $prefix = strtoupper(substr(preg_replace('/[^a-zA-Z]/', '', $firstName), 0, 5));
    if ($prefix === '') {
        $prefix = 'LOVEU';
    }

    return $prefix . strtoupper(bin2hex(random_bytes(3)));
}