<?php
// ─── Load .env ────────────────────────────────
function loadEnv() {
    // .env is in the same folder as index.php (api/)
    // config/ is a subfolder, so go up one level
    $path = __DIR__ . '/../.env';
    if (!file_exists($path)) {
        // fallback: same directory as this file
        $path = __DIR__ . '/.env';
    }
    if (!file_exists($path)) return false;
    foreach (file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
        $line = trim($line);
        if ($line === '' || $line[0] === '#') continue;
        if (strpos($line, '=') === false) continue;
        [$key, $val] = explode('=', $line, 2);
        $key = trim($key);
        $val = trim($val, " \t\n\r\0\x0B\"'");
        $_ENV[$key] = $val;
        putenv("$key=$val");
    }
    return true;
}
loadEnv();

// ─── DB Connection ────────────────────────────
function getDB() {
    static $pdo = null;
    if ($pdo) return $pdo;
    try {
        $host = getenv('DB_HOST') ?: 'localhost';
        $port = getenv('DB_PORT') ?: '3306';
        $name = getenv('DB_NAME');
        $user = getenv('DB_USER');
        $pass = getenv('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,
        ]);
    } catch (Exception $e) {
        http_response_code(500);
        header('Content-Type: application/json');
        die(json_encode(['error' => 'DB error: ' . $e->getMessage()]));
    }
    return $pdo;
}

function query($sql, $params = []) {
    $stmt = getDB()->prepare($sql);
    $stmt->execute($params);
    return $stmt->fetchAll();
}

function queryOne($sql, $params = []) {
    $stmt = getDB()->prepare($sql);
    $stmt->execute($params);
    return $stmt->fetch() ?: null;
}

function execute($sql, $params = []) {
    $stmt = getDB()->prepare($sql);
    $stmt->execute($params);
    return $stmt;
}

function lastId() {
    return getDB()->lastInsertId();
}

// ════════════════════════════════════════════════════════
// ADDED FOR USER MANAGEMENT API COMPATIBILITY
// Make $pdo available globally for direct access
// ════════════════════════════════════════════════════════
$pdo = getDB();
?>
