<?php
/**
 * Security utilities for HSE Management API
 * Provides CSRF protection, input sanitization, and session validation
 */

// Initialize session if not already active
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

/**
 * Generate a CSRF token for the session
 */
function generateCSRFToken() {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

/**
 * Validate CSRF token from POST request
 */
function validateCSRFToken() {
    $token = $_POST['csrf_token'] ?? $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
    
    if (empty($token) || empty($_SESSION['csrf_token'])) {
        return false;
    }
    
    return hash_equals($token, $_SESSION['csrf_token']);
}

/**
 * Sanitize user input to prevent XSS
 */
function sanitizeInput($input) {
    if (is_array($input)) {
        return array_map('sanitizeInput', $input);
    }
    
    if (is_string($input)) {
        return htmlspecialchars($input, ENT_QUOTES, 'UTF-8');
    }
    
    return $input;
}

/**
 * Validate and return sanitized string
 */
function getSafeString($key, $default = '') {
    $value = $_POST[$key] ?? $default;
    return sanitizeInput(trim($value));
}

/**
 * Validate and return sanitized integer
 */
function getSafeInt($key, $default = 0) {
    $value = $_POST[$key] ?? $default;
    return (int) $value;
}

/**
 * Check if user session is valid
 */
function isSessionValid() {
    return !empty($_SESSION['user_id']) && !empty($_SESSION['username']);
}

/**
 * Get current user ID from session
 */
function getCurrentUserId() {
    return $_SESSION['user_id'] ?? null;
}

/**
 * Return error response
 */
function returnError($message, $code = 400) {
    http_response_code($code);
    echo json_encode(['success' => false, 'error' => $message]);
    exit;
}

/**
 * Return success response
 */
function returnSuccess($data = []) {
    echo json_encode(array_merge(['success' => true], $data));
    exit;
}
?>
