<?php
declare(strict_types=1);

function start_session(): void {
    if (session_status() !== PHP_SESSION_ACTIVE) {
        // Set secure session cookie parameters
        ini_set('session.cookie_httponly', '1'); // Prevents JavaScript access to session cookie
        
        // Dynamic secure cookie based on HTTPS
        $secure = (defined('IS_HTTPS') && IS_HTTPS) ? '1' : '0';
        ini_set('session.cookie_secure', $secure);
        
        ini_set('session.use_strict_mode', '1'); // Prevents the use of uninitialized session IDs
        ini_set('session.cookie_samesite', 'Lax'); // Protects against CSRF

        session_start();
    }
}

function e(string $v): string {
    return htmlspecialchars($v, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function sanitize_str(?string $v): string {
    return trim((string)$v);
}

function valid_email(string $v): bool {
    return filter_var($v, FILTER_VALIDATE_EMAIL) !== false;
}

function is_post(): bool {
    return ($_SERVER['REQUEST_METHOD'] ?? '') === 'POST';
}

function redirect(string $path): void {
    if (strpos($path, 'http') !== 0 && strpos($path, '/') === 0) {
        $path = url($path);
    }
    header('Location: ' . $path);
    exit;
}

function csrf_token(): string {
    start_session();
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function csrf_field(): string {
    return '<input type="hidden" name="csrf_token" value="'.e(csrf_token()).'">';
}

function verify_csrf(?string $token): bool {
    start_session();
    return !empty($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token ?? '');
}

function get_or_create_guest_id(): string {
    start_session();
    if (empty($_SESSION['guest_id'])) {
        $_SESSION['guest_id'] = 'guest_' . uniqid() . '_' . bin2hex(random_bytes(4));
    }
    return $_SESSION['guest_id'];
}

function ensure_csrf(): void {
    if (!verify_csrf($_POST['csrf_token'] ?? null)) {
        http_response_code(400);
        exit;
    }
}

function money(float $n): string {
    return number_format($n, 2, '.', ',');
}

function save_uploaded_file(array $file, array $allowedExts, int $maxBytes, string $destDir): ?string {
    if (!isset($file['error']) || is_array($file['error'])) {
        return null;
    }
    if ($file['error'] !== UPLOAD_ERR_OK) {
        return null;
    }
    if ($file['size'] > $maxBytes) {
        return null;
    }
    $name = (string)$file['name'];
    $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
    if (!in_array($ext, $allowedExts, true)) {
        return null;
    }
    if (!is_dir($destDir)) {
        mkdir($destDir, 0775, true);
    }
    $basename = bin2hex(random_bytes(16)) . '.' . $ext;
    $target = rtrim($destDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $basename;
    $tmp = $file['tmp_name'];
    if (!is_uploaded_file($tmp)) {
        return null;
    }
    if (!move_uploaded_file($tmp, $target)) {
        return null;
    }
    return $basename;
}

function current_user() {
    start_session();
    return $_SESSION['user'] ?? null;
}

function set_flash(string $type, string $msg): void {
    start_session();
    $_SESSION['flash'][$type][] = $msg;
}

function get_flashes(): array {
    start_session();
    $f = $_SESSION['flash'] ?? [];
    unset($_SESSION['flash']);
    return $f;
}

function has_flash(): bool {
    start_session();
    return !empty($_SESSION['flash']);
}

function get_flash_message(): string {
    start_session();
    $flashes = $_SESSION['flash'] ?? [];
    if (empty($flashes)) return '';
    
    // Get the first message from the first type
    foreach ($flashes as $type => $messages) {
        if (!empty($messages)) {
            return $messages[0];
        }
    }
    return '';
}

function get_flash_type(): string {
    start_session();
    $flashes = $_SESSION['flash'] ?? [];
    if (empty($flashes)) return 'info';
    
    // Return the type of the first message
    foreach ($flashes as $type => $messages) {
        if (!empty($messages)) {
            return $type;
        }
    }
    return 'info';
}

/**
 * Generate a full URL for a given path
 */
function url(string $path = ''): string {
    $base = defined('BASE_URL') ? rtrim(BASE_URL, '/') : '';
    $path = ltrim($path, '/');
    return $base . '/' . $path;
}

function slugify(string $text): string {
    // Replace non-letter or digits by -
    $text = preg_replace('~[^\pL\d]+~u', '-', $text);
    // Transliterate
    $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
    // Remove unwanted characters
    $text = preg_replace('~[^-\w]+~', '', $text);
    // Trim
    $text = trim($text, '-');
    // Remove duplicate -
    $text = preg_replace('~-+~', '-', $text);
    // Lowercase
    $text = strtolower($text);
    if (empty($text)) return 'n-a';
    return $text;
}

/**
 * Smart CTA URL: Returns the target path if logged in, 
 * otherwise returns a registration link with a redirect return.
 */
function cta_url(string $path): string {
    if (current_user()) {
        return url($path);
    }
    return url('register.php?redirect=' . urlencode($path));
}

