<?php
declare(strict_types=1);

/**
 * SMI Core Periods — central configuration.
 */

$localConfigFile = __DIR__ . '/config.local.php';
$local = is_file($localConfigFile) ? require $localConfigFile : [];
if (!is_array($local)) {
    $local = [];
}

if (!function_exists('smiEnv')) {
    function smiEnv(string $key, mixed $default = null): mixed
    {
        $value = getenv($key);
        return $value === false ? $default : $value;
    }
}

if (!function_exists('smiDetectBaseUrl')) {
    function smiDetectBaseUrl(): string
    {
        if (PHP_SAPI === 'cli') {
            return 'http://localhost/student-gateway';
        }
        $https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
            || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https');
        $scheme = $https ? 'https' : 'http';
        $host = preg_replace('/[^a-zA-Z0-9.\-:\[\]]/', '', (string)($_SERVER['HTTP_HOST'] ?? 'localhost'));
        $script = str_replace('\\', '/', (string)($_SERVER['SCRIPT_NAME'] ?? ''));
        $marker = '/student-gateway/';
        $pos = strpos($script, $marker);
        $basePath = $pos !== false ? substr($script, 0, $pos + strlen('/student-gateway')) : rtrim(dirname($script), '/.');
        return $scheme . '://' . $host . ($basePath === '/' ? '' : $basePath);
    }
}

$appDebug = filter_var(
    smiEnv('SMI_APP_DEBUG', $local['app_debug'] ?? false),
    FILTER_VALIDATE_BOOL
);
$baseUrl = rtrim((string)smiEnv('SMI_BASE_URL', $local['base_url'] ?? smiDetectBaseUrl()), '/');
$timezone = (string)smiEnv('SMI_TIMEZONE', $local['timezone'] ?? 'Asia/Aden');
$db = is_array($local['database'] ?? null) ? $local['database'] : [];

const APP_NAME = 'SMI Student Gateway';
const APP_AR_NAME = 'بوابة الفترات الأساسية';
const APP_OWNER = 'Superior Multiskills Institution';

define('APP_DEBUG', $appDebug);
define('BASE_URL', $baseUrl);
define('APP_URL', $baseUrl); // Backward compatibility.
define('DB_HOST', (string)smiEnv('SMI_DB_HOST', $db['host'] ?? 'localhost'));
define('DB_PORT', (int)smiEnv('SMI_DB_PORT', $db['port'] ?? 3306));
define('DB_NAME', (string)smiEnv('SMI_DB_NAME', $db['name'] ?? ''));
define('DB_USER', (string)smiEnv('SMI_DB_USER', $db['user'] ?? ''));
define('DB_PASS', (string)smiEnv('SMI_DB_PASS', $db['pass'] ?? ''));
define('DB_CHARSET', (string)smiEnv('SMI_DB_CHARSET', $db['charset'] ?? 'utf8mb4'));

define('ROOT_PATH', dirname(__DIR__));
define('INCLUDES_PATH', ROOT_PATH . '/includes');
define('UPLOADS_PATH', ROOT_PATH . '/uploads');
define('ASSETS_PATH', ROOT_PATH . '/assets');
define('ASSETS_URL', BASE_URL . '/assets');

define('STUDENT_CARD_PREFIX', 'SMI-ELD-');
define('EXAM_CODE_PREFIX', 'SMI-ExamsUnit-');
define('MAX_FINAL_GRADE', 100);
define('DEFAULT_COURSE_DURATION_DAYS', 28);
define('DEFAULT_OBSTACLE_DURATION_DAYS', 7);
define('DEFAULT_SHADOWING_COUNT', 20);

// Canonical attendance policy: present >= 40 minutes, late 20–39, absent < 20.
define('ATTENDANCE_PRESENT_MINUTES', 40);
define('ATTENDANCE_LATE_MINUTES', 20);
define('ATTENDANCE_PRESENT_WINDOW_MINUTES', 10);
define('ATTENDANCE_SESSION_DURATION', 120);
define('SESSION_IDLE_TIMEOUT', 8 * 60 * 60);

define('MAX_HOMEWORK_WEIGHT', 10);
define('MAX_PARTICIPATION_WEIGHT', 5);
define('MAX_EXAM_WEIGHT', 100);
define('MAX_UPLOAD_SIZE', 20 * 1024 * 1024);
define('ALLOWED_FILE_TYPES', ['pdf', 'doc', 'docx', 'jpg', 'jpeg', 'png', 'webp', 'mp3', 'wav', 'mp4']);
define('ALLOWED_UPLOAD_MIMES', [
    'pdf' => ['application/pdf'],
    'doc' => ['application/msword', 'application/octet-stream'],
    'docx' => ['application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/zip'],
    'jpg' => ['image/jpeg'],
    'jpeg' => ['image/jpeg'],
    'png' => ['image/png'],
    'webp' => ['image/webp'],
    'mp3' => ['audio/mpeg', 'audio/mp3'],
    'wav' => ['audio/wav', 'audio/x-wav'],
    'mp4' => ['video/mp4', 'application/octet-stream'],
]);

define('PRIMARY_COLOR', '#2563eb');
define('SECONDARY_COLOR', '#1d4ed8');
define('SUCCESS_COLOR', '#16a34a');
define('DANGER_COLOR', '#dc2626');

date_default_timezone_set($timezone);

if (PHP_SAPI !== 'cli' && session_status() === PHP_SESSION_NONE) {
    $isSecure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
        || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https');
    ini_set('session.use_strict_mode', '1');
    ini_set('session.use_only_cookies', '1');
    ini_set('session.cookie_httponly', '1');
    ini_set('session.cookie_samesite', 'Lax');
    if ($isSecure) {
        ini_set('session.cookie_secure', '1');
    }
    session_name('SMI_CORE_SESSION');
    session_start();
}

ini_set('display_errors', APP_DEBUG ? '1' : '0');
ini_set('display_startup_errors', APP_DEBUG ? '1' : '0');
error_reporting(E_ALL);

if (!isset($_SESSION['lang'])) {
    $_SESSION['lang'] = 'en';
}

if (!function_exists('url')) {
    function url(string $path = ''): string
    {
        if (preg_match('#^https?://#i', $path)) {
            return $path;
        }
        return rtrim(BASE_URL, '/') . '/' . ltrim($path, '/');
    }
}

if (!function_exists('redirect')) {
    function redirect(string $path): never
    {
        header('Location: ' . url($path), true, 302);
        exit;
    }
}

if (!function_exists('redirectTo')) {
    function redirectTo(string $path): never
    {
        redirect($path);
    }
}

if (!function_exists('themeColor')) {
    function themeColor(string $type): string
    {
        return match ($type) {
            'secondary' => SECONDARY_COLOR,
            'success' => SUCCESS_COLOR,
            'danger' => DANGER_COLOR,
            default => PRIMARY_COLOR,
        };
    }
}

/* Runtime compatibility for shared-hosting PHP builds without mbstring. */
if (!function_exists('mb_substr')) {
    function mb_substr(string $string, int $start, ?int $length = null, ?string $encoding = null): string
    {
        return $length === null ? substr($string, $start) : substr($string, $start, $length);
    }
}
if (!function_exists('mb_strtolower')) {
    function mb_strtolower(string $string, ?string $encoding = null): string { return strtolower($string); }
}
if (!function_exists('mb_strtoupper')) {
    function mb_strtoupper(string $string, ?string $encoding = null): string { return strtoupper($string); }
}
if (!function_exists('mb_strlen')) {
    function mb_strlen(string $string, ?string $encoding = null): int { return strlen($string); }
}
if (!function_exists('mb_strimwidth')) {
    function mb_strimwidth(string $string, int $start, int $width, string $trimMarker = '', ?string $encoding = null): string
    {
        $slice = substr($string, $start, $width);
        return strlen($string) > ($start + $width) ? rtrim($slice) . $trimMarker : $slice;
    }
}

/* Baseline response hardening for every public PHP entry point. */
if (PHP_SAPI !== 'cli' && !headers_sent()) {
    header('X-Frame-Options: SAMEORIGIN');
    header('X-Content-Type-Options: nosniff');
    header('Referrer-Policy: strict-origin-when-cross-origin');
    header('Permissions-Policy: camera=(), geolocation=(), microphone=(self)');
    header("Content-Security-Policy: default-src 'self'; img-src 'self' data: https://api.qrserver.com https:; media-src 'self' https: blob:; frame-src 'self' https://www.youtube.com https://youtube.com https://zoom.us https://*.zoom.us; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com data:; script-src 'self' 'unsafe-inline' https://unpkg.com; connect-src 'self' https://unpkg.com; form-action 'self'; base-uri 'self'; frame-ancestors 'self'; object-src 'none'");
    if ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https')) {
        header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
    }
}
