<?php

// HTTPS redirect
if (!isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTP_HOST']) && strpos($_SERVER['HTTP_HOST'], 'localhost') === false && strpos($_SERVER['HTTP_HOST'], '127.0.0.1') === false) {
    header('Location: https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
    exit;
}

// Load .env if available
$envFile = __DIR__ . '/../.env';
if (file_exists($envFile)) {
    $lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        if (strpos(trim($line), '#') === 0) continue;
        if (strpos($line, '=') !== false) {
            list($key, $value) = explode('=', $line, 2);
            $key = trim($key);
            $value = trim($value);
            // strip surrounding quotes
            if ((strpos($value, '"') === 0 && strrpos($value, '"') === strlen($value)-1) ||
                (strpos($value, "'") === 0 && strrpos($value, "'") === strlen($value)-1)) {
                $value = substr($value, 1, -1);
            }
            putenv("$key=$value");
            $_ENV[$key] = $value;
        }
    }
}

define('APP_BASE_URL', getenv('APP_BASE_URL') ?: '/');

// Mail Configuration
define('MAIL_HOST', getenv('MAIL_HOST') ?: 'smtp.gmail.com');
define('MAIL_USERNAME', getenv('MAIL_USERNAME') ?: '');
define('MAIL_PASSWORD', getenv('MAIL_PASSWORD') ?: '');
define('MAIL_ENCRYPTION', getenv('MAIL_ENCRYPTION') ?: 'tls');
define('MAIL_PORT', getenv('MAIL_PORT') ?: 587);
define('MAIL_FROM_ADDRESS', getenv('MAIL_FROM_ADDRESS') ?: 'noreply@ghanaanaesthesia.com');
define('MAIL_FROM_NAME', getenv('MAIL_FROM_NAME') ?: 'Ghana Anaesthesiologists Society');

// Environment
$env = getenv('APP_ENV') ?: 'development';
if ($env === 'development') {
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
} else {
    error_reporting(E_ALL);
    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
}

require_once __DIR__ . '/vendor/autoload.php';

use App\Helpers\Auth;
use App\Helpers\Url;
use App\Core\Router;

Auth::start();

require_once __DIR__ . '/../routes/web.php';

$uri = $_SERVER['REQUEST_URI'];
$method = $_SERVER['REQUEST_METHOD'];

$baseUrl = Url::getBaseUrl();
if ($baseUrl && strpos($uri, $baseUrl) === 0) {
    $uri = substr($uri, strlen($baseUrl));
}
$uri = '/' . ltrim($uri, '/');

Router::dispatch($uri, $method);