<?php
/**
 * includes/db.php — PDO database connection singleton
 * Returns the same PDO instance on every call — no multiple connections.
 */

function db(): PDO {
    static $pdo = null;
    if ($pdo !== null) return $pdo;

    $dsn = sprintf(
        'mysql:host=%s;port=%s;dbname=%s;charset=%s',
        DB_HOST, DB_PORT, DB_NAME, DB_CHARSET
    );

    $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) {
        // Show a safe error — never expose credentials
        error_log('DB connection failed: ' . $e->getMessage());
        die('<p style="font-family:sans-serif;padding:2rem;">
            Cannot connect to the database. Check config/config.php credentials.
        </p>');
    }

    return $pdo;
}
