<?php

$envPath = dirname(__DIR__) . DIRECTORY_SEPARATOR . '.env';
if (!is_file($envPath) || !is_readable($envPath)) {
    http_response_code(500);
    header('Content-Type: application/javascript; charset=utf-8');
    echo 'throw new Error("Website environment file is missing or unreadable");';
    exit;
}

$websiteEnvironment = parse_ini_file($envPath, false, INI_SCANNER_RAW);
$environmentApiBaseUrl = getenv('DAV_API_BASE_URL');
$apiBaseUrl = $environmentApiBaseUrl !== false && trim($environmentApiBaseUrl) !== ''
    ? $environmentApiBaseUrl
    : ($websiteEnvironment['DAV_API_BASE_URL'] ?? '');

if (trim($apiBaseUrl) === '') {
    http_response_code(500);
    header('Content-Type: application/javascript; charset=utf-8');
    echo 'throw new Error("DAV_API_BASE_URL is not configured in the website environment");';
    exit;
}

$apiBaseUrl = rtrim(trim($apiBaseUrl), '/') . '/';
if (!filter_var($apiBaseUrl, FILTER_VALIDATE_URL) || !in_array(parse_url($apiBaseUrl, PHP_URL_SCHEME), ['http', 'https'], true)) {
    http_response_code(500);
    header('Content-Type: application/javascript; charset=utf-8');
    echo 'throw new Error("DAV_API_BASE_URL must be a valid HTTP or HTTPS URL");';
    exit;
}

header('Content-Type: application/javascript; charset=utf-8');
header('Cache-Control: no-store');
?>
(function (window) {
  const apiBaseUrl = <?= json_encode($apiBaseUrl, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;

  window.DAV_CONFIG = Object.freeze({
    apiBaseUrl,
    apiEndpoints: Object.freeze({
      activeHomeBanners: "homebannerapis/get_active",
      activeNotices: "announcementapis/get_notices",
      activeEvents: "announcementapis/get_events",
      futureEvents: "announcementapis/get_future_events",
      paginatedNotices: "announcementapis/get_notices_paginated",
      paginatedEvents: "announcementapis/get_events_paginated",
      publicCommonSettings: "commonsettingsapis/get_public"
    })
  });
})(window);
