<?php

declare(strict_types=1);

if (!defined('BASE_PATH')) {
    define('BASE_PATH', __DIR__);
}

if (!defined('APP_PATH')) {
    define('APP_PATH', BASE_PATH . '/app');
}

if (!defined('CONFIG_PATH')) {
    define('CONFIG_PATH', BASE_PATH . '/config');
}

if (!defined('PUBLIC_PATH')) {
    define('PUBLIC_PATH', BASE_PATH . '/public');
}

if (!defined('STORAGE_PATH')) {
    define('STORAGE_PATH', BASE_PATH . '/storage');
}

/*
|--------------------------------------------------------------------------
| Environment
|--------------------------------------------------------------------------
*/

$environmentFile = BASE_PATH . '/.env.php';

if (!is_file($environmentFile)) {
    die('Missing .env.php file at: ' . htmlspecialchars($environmentFile));
}

$environment = require $environmentFile;

if (!is_array($environment)) {
    die('.env.php must return an array.');
}

$GLOBALS['environment'] = $environment;

/*
|--------------------------------------------------------------------------
| Error reporting
|--------------------------------------------------------------------------
*/

$debug = filter_var(
    $environment['APP_DEBUG'] ?? false,
    FILTER_VALIDATE_BOOL
);

ini_set('display_errors', $debug ? '1' : '0');
ini_set('display_startup_errors', $debug ? '1' : '0');
ini_set('log_errors', '1');

error_reporting(
    E_ALL
    & ~E_DEPRECATED
    & ~E_USER_DEPRECATED
);

/*
|--------------------------------------------------------------------------
| Timezone
|--------------------------------------------------------------------------
*/

date_default_timezone_set(
    (string) ($environment['APP_TIMEZONE'] ?? 'Africa/Johannesburg')
);

/*
|--------------------------------------------------------------------------
| Autoload App namespace
|--------------------------------------------------------------------------
*/

spl_autoload_register(function (string $class): void {
    $prefix = 'App\\';

    if (!str_starts_with($class, $prefix)) {
        return;
    }

    $relativeClass = substr($class, strlen($prefix));

    $file = APP_PATH
        . '/'
        . str_replace('\\', '/', $relativeClass)
        . '.php';

    if (is_file($file)) {
        require_once $file;
    }
});

/*
|--------------------------------------------------------------------------
| Helpers
|--------------------------------------------------------------------------
*/

$helpersFile = APP_PATH . '/Helpers/functions.php';

if (!is_file($helpersFile)) {
    die('Missing helper file at: ' . htmlspecialchars($helpersFile));
}

require_once $helpersFile;

if (!defined('PHPMAILER_PATH')) {
    define(
        'PHPMAILER_PATH',
        BASE_PATH . '/PHPMailer-master'
    );
}

if (!defined('QRCODE_PATH')) {
    define(
        'QRCODE_PATH',
        BASE_PATH . '/phpqrcode'
    );
}

if (!defined('DOMPDF_PATH')) {
    define(
        'DOMPDF_PATH',
        BASE_PATH . '/dompdf-master'
    );
}