<?php
// config.php - simple .env loader and DB connector for PHP 7.4

function env_path() {
    $paths = [__DIR__ . '/.env', __DIR__ . '/../.env', __DIR__ . '/../../.env'];
    foreach ($paths as $p) {
        if (file_exists($p)) return $p;
    }
    return null;
}

function load_env($path) {
    if (!$path) return;
    $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        if (strpos(trim($line), '#') === 0) continue;
        $parts = explode('=', $line, 2);
        if (count($parts) == 2) {
            $key = trim($parts[0]);
            $val = trim($parts[1]);
            if (!getenv($key)) {
                putenv("$key=$val");
                $_ENV[$key] = $val;
            }
        }
    }
}

load_env(env_path());

function envv($key, $default = null) {
    $v = getenv($key);
    return $v !== false ? $v : $default;
}

// Database connection (PDO)
function db() {
    static $pdo = null;
    if ($pdo) return $pdo;
    $host = envv('DB_HOST', '127.0.0.1');
    $port = envv('DB_PORT', '3306');
    $db   = envv('DB_NAME', 'chatgpt3');
    $user = envv('DB_USER', 'mupeng');
    $pass = envv('DB_PASS', 'mupeng');
    $dsn = "mysql:host=$host;port=$port;dbname=$db;charset=utf8mb4";
    try {
        $pdo = new PDO($dsn, $user, $pass, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4"
        ]);
    } catch (Exception $e) {
        http_response_code(500);
        header('Content-Type: application/json');
        echo json_encode(['error' => 'DB connection failed', 'message' => $e->getMessage()]);
        exit;
    }
    return $pdo;
}

function ensure_storage() {
    $dir = __DIR__ . '/storage/uploads';
    if (!is_dir($dir)) {
        @mkdir($dir, 0777, true);
    }
    return realpath($dir);
}

function json_out($arr, $code = 200) {
    http_response_code($code);
    header('Content-Type: application/json');
    echo json_encode($arr);
    exit;
}

function ok($arr = []) { json_out($arr); }
function bad($msg, $code = 400) { json_out(['error' => $msg], $code); }
