<?php
namespace App\Core;

use PDO;
use PDOException;

class DB
{
    private static $pdo;

    public static function pdo(): PDO
    {
        if (!self::$pdo) {
            $cfg = db_config();
            $dsn = sprintf('mysql:host=%s;port=%d;dbname=%s;charset=%s', $cfg['host'], $cfg['port'], $cfg['database'], $cfg['charset']);
            try {
                self::$pdo = new PDO($dsn, $cfg['username'], $cfg['password'], [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                ]);
            } catch (PDOException $e) {
                http_response_code(500);
                echo 'Database connection failed.';
                exit;
            }
        }
        return self::$pdo;
    }
}
