<?php

/**
 * App Bootstrap - Auth and config loader for UI pages
 *
 * Include this at the top of every app page (except login.php).
 * It handles:
 * - Loading configuration
 * - Initializing authentication
 * - Redirecting unauthenticated users to login
 * - Exposing config values to JavaScript
 */

declare(strict_types=1);

// Load config
$configPath = __DIR__ . '/config.php';
if (!file_exists($configPath)) {
    die('Configuration file not found');
}
$config = require $configPath;

// Load auth class
require_once __DIR__ . '/src/auth.php';

// Initialize auth
$auth = new \Notifier\Auth($config);

// Check if this is the login page (don't require auth on login page)
$currentPage = basename($_SERVER['PHP_SELF']);
$isLoginPage = $currentPage === 'login.php';

if (!$isLoginPage) {
    // Require authentication - redirect to login if not authenticated
    if (!$auth->isAuthenticated()) {
        header('Location: /notifier/login/');
        exit;
    }
}

// App configuration to expose to JavaScript
$appConfig = [
    'timezone' => $config['display_timezone'] ?? 'America/Mexico_City',
    'apiBase' => '/notifier/api',
    'uploadMaxSize' => $config['upload_max_size'] ?? (5 * 1024 * 1024),
];

/**
 * Output the app config as a JavaScript variable.
 * Call this in the <head> section of pages.
 */
function renderAppConfig(): void
{
    global $appConfig;
    echo '<script>window.__APP_CONFIG__ = ' . json_encode($appConfig, JSON_UNESCAPED_SLASHES) . ';</script>';
}

/**
 * Get the current page name for navigation highlighting.
 */
function getCurrentPage(): string
{
    return basename($_SERVER['PHP_SELF'], '.php');
}

/**
 * Check if a nav item is active.
 */
function isNavActive(string $page): bool
{
    return getCurrentPage() === $page;
}
