<?php
require_once __DIR__ . '/env.php';

function app_config(): array {
    static $cfg = null;
    if ($cfg !== null) return $cfg;

    $root = dirname(__DIR__);
    $envPath = $root . '/.env';
    if (!file_exists($envPath) && file_exists($root . '/.env.example')) {
        // fallback for local dev without .env
        $envPath = $root . '/.env.example';
    }
    $env = env_load($envPath);

    $cfg = [
        'APP_NAME' => $env['APP_NAME'] ?? 'Utile',
        'BASE_URL' => $env['BASE_URL'] ?? 'http://localhost/utile_vendor_app/public',
        'DB_HOST' => $env['DB_HOST'] ?? 'localhost',
        'DB_NAME' => $env['DB_NAME'] ?? 'bosvesedst_utile',
        'DB_USER' => $env['DB_USER'] ?? 'bosvesedst_root',
        'DB_PASS' => $env['DB_PASS'] ?? 'filemakrxpert@123',
        'DEMO_OTP' => $env['DEMO_OTP'] ?? '1234',
        'COMPLETION_OTP' => $env['COMPLETION_OTP'] ?? '5678',
        'JWT_SECRET' => $env['JWT_SECRET'] ?? 'change_this',
        'UPLOAD_DIR' => $env['UPLOAD_DIR'] ?? '../uploads',
        'RAZORPAY_KEY_ID' => $env['RAZORPAY_KEY_ID'] ?? '',
        'RAZORPAY_KEY_SECRET' => $env['RAZORPAY_KEY_SECRET'] ?? '',
    ];
    return $cfg;
}

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

    $cfg = app_config();
    $dsn = "mysql:host={$cfg['DB_HOST']};dbname={$cfg['DB_NAME']};charset=utf8mb4";
    $pdo = new PDO($dsn, $cfg['DB_USER'], $cfg['DB_PASS'], [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
    return $pdo;
}
