<?php
// ============================================================================
// config/session.php
// ============================================================================
// Session Configuration
// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Session Helper Functions
function isLoggedIn() {
    return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
}

function getUserId() {
    return $_SESSION['user_id'] ?? null;
}

function getUserType() {
    return $_SESSION['user_type'] ?? null;
}

function getUserName() {
    return $_SESSION['full_name'] ?? 'Guest';
}

function getUserPhone() {
    return $_SESSION['phone_number'] ?? null;
}

function setUserSession($user) {
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['phone_number'] = $user['phone_number'];
    $_SESSION['full_name'] = $user['full_name'];
    $_SESSION['user_type'] = $user['user_type'];
    $_SESSION['profile_picture'] = $user['profile_picture'];
    $_SESSION['language_preference'] = $user['language_preference'];
    $_SESSION['last_activity'] = time();
}

function destroySession() {
    $_SESSION = array();
    if (isset($_COOKIE[session_name()])) {
        setcookie(session_name(), '', time()-42000, '/');
    }
    session_destroy();
}

function checkSessionTimeout() {
    if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > SESSION_LIFETIME)) {
        destroySession();
        return false;
    }
    $_SESSION['last_activity'] = time();
    return true;
}

function requireLogin() {
    if (!isLoggedIn() || !checkSessionTimeout()) {
        header('Location: ' . APP_URL . '/auth/login.php');
        exit();
    }
}

function requireAdmin() {
    requireLogin();
    if (getUserType() !== 'admin') {
        header('Location: ' . APP_URL . '/dashboard/');
        exit();
    }
}

// CSRF Token Functions
function generateCSRFToken() {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function verifyCSRFToken($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}
?>