<?php
// includes/functions.php - small helper functions

function e($s) {
    return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8');
}

function flash_set($k, $v) {
    if (!session_id()) session_start();
    $_SESSION['flash'][$k] = $v;
}

function flash_get($k) {
    if (!session_id()) session_start();
    $v = $_SESSION['flash'][$k] ?? null;
    unset($_SESSION['flash'][$k]);
    return $v;
}

function get_setting(string $key, $default = null) {
    // lazy-load setting from DB if available
    $dbFile = __DIR__ . '/../data/school.db';
    if (!file_exists($dbFile)) return $default;
    try {
        $db = new PDO('sqlite:' . $dbFile);
        $stmt = $db->prepare('SELECT value FROM settings WHERE key = :k LIMIT 1');
        $stmt->execute([':k' => $key]);
        $v = $stmt->fetchColumn();
        return $v === false ? $default : $v;
    } catch (Exception $e) {
        return $default;
    }
}

function base_url(): string {
    // Try to detect the project's base path from the current script URL.
    // Example: when accessing /mygb/admin/dashboard.php this returns '/mygb'.
    $script = $_SERVER['SCRIPT_NAME'] ?? '';
    $parts = array_values(array_filter(explode('/', $script)));
    if (count($parts) >= 1) {
        // first segment is the project folder when served from a subfolder
        return '/' . $parts[0];
    }
    return '';
}

?>