<?php
/**
 * Cincinnati Fire Department Portal - Database Connection
 * PDO singleton with .env-based configuration.
 */

date_default_timezone_set('America/New_York');

/**
 * Parse .env file and return key-value array.
 */
function loadEnv() {
    static $env = null;
    if ($env !== null) return $env;

    $envFile = __DIR__ . '/../.env';
    if (!file_exists($envFile)) {
        throw new RuntimeException('.env file not found at: ' . $envFile);
    }

    $env = [];
    $lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        $line = trim($line);
        if ($line === '' || $line[0] === '#') continue;
        $pos = strpos($line, '=');
        if ($pos === false) continue;
        $key = trim(substr($line, 0, $pos));
        $value = trim(substr($line, $pos + 1));
        $env[$key] = $value;
    }
    return $env;
}

/**
 * Get environment variable from .env.
 */
function env($key, $default = null) {
    $env = loadEnv();
    return $env[$key] ?? $default;
}

/**
 * Get MySQL PDO connection (singleton).
 */
function getDB() {
    static $pdo = null;
    if ($pdo === null) {
        $host = env('DB_HOST', '127.0.0.1');
        $port = env('DB_PORT', '3306');
        $name = env('DB_NAME', 'cincinnatifire_db');
        $user = env('DB_USER', 'cincfire_user');
        $pass = env('DB_PASS', '');

        $dsn = "mysql:host={$host};port={$port};dbname={$name};charset=utf8mb4";
        $pdo = new PDO($dsn, $user, $pass, [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES   => false,
        ]);
    }
    return $pdo;
}

/**
 * Return JSON response and exit.
 */
function jsonResponse($data, $code = 200) {
    http_response_code($code);
    header('Content-Type: application/json');
    header('Cache-Control: no-store');
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}
