<?php
// includes/config.php
date_default_timezone_set('Asia/Kolkata');

// Simple .env parser
function loadEnv($path) {
    if (!file_exists($path)) return;
    $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        if (strpos(trim($line), '#') === 0) continue;
        if (strpos($line, '=') !== false) {
            list($name, $value) = explode('=', $line, 2);
            $name = trim($name);
            $value = trim($value);
            if (!defined($name)) {
                define($name, $value);
            }
        }
    }
}

// Load from project root
loadEnv(__DIR__ . '/../env.php');

// Provide fallbacks to avoid breaking if .env is missing temporarily
defined('DB_HOST') or define('DB_HOST', 'localhost');
defined('DB_USER') or define('DB_USER', 'root');
defined('DB_PASS') or define('DB_PASS', '');
defined('DB_NAME') or define('DB_NAME', 'famgateway');
defined('CRON_SECRET') or define('CRON_SECRET', 'secret');
defined('TURNSTILE_SITE_KEY') or define('TURNSTILE_SITE_KEY', '');
defined('TURNSTILE_SECRET_KEY') or define('TURNSTILE_SECRET_KEY', '');

function getDB() {
    static $pdo = null;
    if ($pdo === null) {
        $dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4';
        $options = [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES   => false,
        ];
        try {
            $pdo = new PDO($dsn, DB_USER, DB_PASS, $options);
        } catch (\PDOException $e) {
            throw new \PDOException($e->getMessage(), (int)$e->getCode());
        }
    }
    return $pdo;
}
