<?php
// elms/includes/app.php
declare(strict_types=1);

if (session_status() === PHP_SESSION_NONE) {
  session_start();
}

/* ----------------------- Base path detection -----------------------
   Example request: /admin.edencampus.lk/elms/student/modules.php
   We want BASE_URL = /admin.edencampus.lk/elms
------------------------------------------------------------------- */
if (!defined('BASE_URL')) {
  $script = str_replace('\\','/', $_SERVER['SCRIPT_NAME'] ?? '');
  // Try to capture ".../elms" prefix no matter which sub-page we’re on
  if (preg_match('#^(.*/elms)(?:/.*)?$#', $script, $m)) {
    $base = rtrim($m[1], '/');                // “…/elms”
  } else {
    $base = rtrim(dirname($script), '/');     // fallback
  }
  define('BASE_URL', $base ?: '');
}

/* ----------------------- URL helpers ----------------------------- */
if (!function_exists('app_url')) {
  /** Build an app-relative URL; accepts "file.php" or "/file.php". */
  function app_url(string $path = ''): string {
    if ($path !== '' && $path[0] !== '/') $path = '/'.$path;
    return rtrim(BASE_URL, '/').$path;
  }
}

/* Keep compatibility if some files call url_for() instead of app_url() */
if (!function_exists('url_for')) {
  function url_for(string $path = ''): string {
    return app_url($path);
  }
}

/* ----------------------- (optional) DB/helpers ------------------- */
/* If your project needs these here, keep them; otherwise remove. */
$__inc = __DIR__;
if (is_file($__inc.'/db.php'))      require_once $__inc.'/db.php';
if (is_file($__inc.'/helpers.php')) require_once $__inc.'/helpers.php';

 
// /elms/includes/app.php
if (!defined('BASE_URL')) {
  // Always HTTPS. Adjust host if different in staging.
  define('BASE_URL', 'https://admin.edencampus.lk/elms');
}

if (!function_exists('app_url')) {
  function app_url(string $path = ''): string {
    // Normalize path
    $p = ($path !== '' && $path[0] !== '/') ? '/'.$path : $path;

    // Absolute links pass through untouched
    if (preg_match('~^https?://~i', $p)) return preg_replace('~^http://~i','https://',$p);

    // Force https even if BASE_URL was mis-set
    $base = preg_replace('~^http://~i','https://', rtrim(BASE_URL, '/'));

    return $base . $p;
  }
}





