<?php
/* ============================================================
 * Larspeenghar Pedigree — database connection (PDO / MySQL)
 *
 * Reads DB credentials from config.php (NEVER overwritten on upgrade).
 * Returns a singleton PDO with sane, scale-friendly defaults:
 *   - persistent connections (cheaper under hundreds of concurrent users)
 *   - real prepared statements (not emulated) → safe + plan-cached
 *   - exceptions on error → no silent data corruption
 *   - utf8mb4 for full Pashto/Dari support
 * ============================================================ */

function lp_db() {
    static $pdo = null;
    if ($pdo !== null) return $pdo;

    $cfgFile = __DIR__ . '/config.php';
    $cfg = file_exists($cfgFile) ? include $cfgFile : [];
    if (!is_array($cfg)) $cfg = [];

    $db = isset($cfg['db']) && is_array($cfg['db']) ? $cfg['db'] : [];
    $host = $db['host'] ?? '127.0.0.1';
    $port = $db['port'] ?? 3306;
    $name = $db['name'] ?? '';
    $user = $db['user'] ?? '';
    $pass = $db['pass'] ?? '';
    $charset = $db['charset'] ?? 'utf8mb4';

    if ($name === '' || $user === '') {
        http_response_code(500);
        header('Content-Type: application/json');
        echo json_encode([
            'error' => 'Database is not configured. Edit config.php and fill in the "db" credentials.',
        ]);
        exit;
    }

    $dsn = "mysql:host=$host;port=$port;dbname=$name;charset=$charset";
    try {
        $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,
            PDO::ATTR_PERSISTENT         => true,
            // Wait up to 5s for a connection rather than erroring instantly
            // when the pool is briefly saturated under load.
            PDO::ATTR_TIMEOUT            => 5,
        ]);
    } catch (PDOException $e) {
        http_response_code(500);
        header('Content-Type: application/json');
        // Don't leak credentials/host details to clients.
        echo json_encode(['error' => 'Database connection failed.']);
        error_log('lp_db connect failed: ' . $e->getMessage());
        exit;
    }
    return $pdo;
}
