<?php
declare(strict_types=1);

if (basename(__FILE__) === basename($_SERVER['SCRIPT_FILENAME'] ?? '')) {
    http_response_code(403);
    exit('Forbidden');
}

define('DB_HOST', getenv('FQS_DB_HOST') ?: 'localhost');
define('DB_NAME', getenv('FQS_DB_NAME') ?: 'fortunes_quotation');
define('DB_USER', getenv('FQS_DB_USER') ?: 'root');   // XAMPP default
define('DB_PASS', getenv('FQS_DB_PASS') ?: '');       // XAMPP default (no password)

define('APP_NAME', 'EMS Solar Quotation System');
define('APP_SESSION_SECURE', filter_var(getenv('FQS_SESSION_SECURE') ?: 'false', FILTER_VALIDATE_BOOLEAN));
$scriptName = str_replace('\\', '/', $_SERVER['SCRIPT_NAME'] ?? '/Fortunes_Quotation/public/index.php');
$publicPos = strpos($scriptName, '/public/');
$appBase = $publicPos !== false ? substr($scriptName, 0, $publicPos + 7) : rtrim(dirname($scriptName), '/');
define('APP_BASE', $appBase === '/' ? '' : $appBase);

function db(): PDO
{
    static $pdo = null;
    if ($pdo instanceof PDO) {
        return $pdo;
    }

    $dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4';
    $pdo = new PDO($dsn, DB_USER, DB_PASS, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]);

    return $pdo;
}
