<?php
// Start session securely
function secure_session_start() {
    $session_name = 'secure_session_id';
    $secure = true; // Set to true if using HTTPS
    $httponly = true; // Prevent JavaScript access to session ID
    
    ini_set('session.use_only_cookies', 1);
    $cookieParams = session_get_cookie_params();
    session_set_cookie_params([
        'lifetime' => $cookieParams["lifetime"],
        'path' => $cookieParams["path"],
        'domain' => $cookieParams["domain"],
        'secure' => $secure,
        'httponly' => $httponly,
        'samesite' => 'Strict'
    ]);
    
    session_name($session_name);
    session_start();
    session_regenerate_id(true);
}

// Only start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    secure_session_start();
}

// Generate CSRF token
function generate_csrf_token() {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
        $_SESSION['csrf_token_time'] = time();
    }
    return $_SESSION['csrf_token'];
}

// Validate CSRF token
function validate_csrf_token($token) {
    if (isset($_SESSION['csrf_token'], $_SESSION['csrf_token_time']) && hash_equals($_SESSION['csrf_token'], $token)) {
        $token_age = time() - $_SESSION['csrf_token_time'];
        if ($token_age <= 3600) {
            return true;
        }
    }
    return false;
}

// Message handling functions
function set_flash_message($type, $message) {
    $_SESSION['flash_messages'][$type][] = $message;
}

function display_flash_messages() {
    if (!empty($_SESSION['flash_messages'])) {
        foreach ($_SESSION['flash_messages'] as $type => $messages) {
            $alert_class = $type === 'error' ? 'bg-red-100 border-red-400 text-red-700' : 'bg-green-100 border-green-400 text-green-700';
            foreach ($messages as $message) {
                echo '<div class="border px-4 py-3 rounded relative mb-4 fade-in '.$alert_class.'" role="alert">
                    <i class="fas '.($type === 'error' ? 'fa-exclamation-circle' : 'fa-check-circle').' mr-2"></i>'
                    . htmlspecialchars($message) .
                    '</div>';
            }
        }
        unset($_SESSION['flash_messages']);
    }
}

// Generate CAPTCHA
function generate_captcha() {
    $captcha_code = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 6);
    $_SESSION['captcha'] = $captcha_code;
    $_SESSION['captcha_time'] = time();
    return $captcha_code;
}

// Validate CAPTCHA
function validate_captcha($input) {
    if (isset($_SESSION['captcha'], $_SESSION['captcha_time'])) {
        $captcha_age = time() - $_SESSION['captcha_time'];
        if ($captcha_age <= 600 && strtolower($input) === strtolower($_SESSION['captcha'])) {
            return true;
        }
    }
    return false;
}

// Always generate CSRF token when this file is included
generate_csrf_token();
?>