<?php
/**
 * Security Core for Rev. Dr. Sally Julie Armah Memorial Website
 * Handles: Session Hardening, Security Headers, CSRF & XSS Protection
 */

// 1. Session Hardening
// Set session cookie parameters for better security
$is_https = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') || 
             (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https');

$session_params = [
    'lifetime' => 0, // Session expires when browser closes
    'path' => '/',
    'domain' => '',
    'secure' => $is_https, // Only transmit over HTTPS if available
    'httponly' => true,    // Prevent JavaScript access to session cookie
    'samesite' => 'Lax'     // Mitigate CSRF
];

if (session_status() === PHP_SESSION_NONE) {
    session_set_cookie_params($session_params);
    session_start();
}

// Regenerate session ID periodically to prevent session fixation
if (!isset($_SESSION['last_regeneration']) || time() - $_SESSION['last_regeneration'] > 1800) {
    session_regenerate_id(true);
    $_SESSION['last_regeneration'] = time();
}

// 2. Security Headers
// Prevent site from being embedded (Clickjacking)
header('X-Frame-Options: DENY');
// Prevent MIME-type sniffing
header('X-Content-Type-Options: nosniff');
// Basic Referrer Policy
header('Referrer-Policy: strict-origin-when-cross-origin');
// Content Security Policy (Adjust based on your needs)
// This allow scripts from your site and common CDNs used in this project
header("Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://cdnjs.cloudflare.com https://unpkg.com; style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com https://cdnjs.cloudflare.com https://unpkg.com; font-src 'self' https://fonts.gstatic.com https://cdnjs.cloudflare.com; img-src 'self' data: https:; frame-src https://www.google.com;");

// 3. XSS Protection Utility
/**
 * Shorthand for htmlspecialchars to prevent XSS.
 * @param string $data The string to escape
 * @return string The escaped string
 */
function h($data) {
    return htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
}

// 4. CSRF Protection
/**
 * Generates a CSRF token and stores it in the session if not present.
 * @return string The CSRF token
 */
function get_csrf_token() {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

/**
 * Validates a CSRF token from a request.
 * @param string $token The token to validate
 * @return bool True if valid
 */
function verify_csrf_token($token) {
    if (!isset($_SESSION['csrf_token']) || empty($token)) {
        return false;
    }
    return hash_equals($_SESSION['csrf_token'], $token);
}
