<?php
declare(strict_types=1);

/** PDO singleton. One connection per request. */
final class Database
{
    private static ?PDO $pdo = null;

    private function __construct() {}

    public static function pdo(): PDO
    {
        if (self::$pdo instanceof PDO) {
            return self::$pdo;
        }

        // DB_HOST 'localhost' uses the unix socket on Linux; an IP forces TCP.
        $dsn = sprintf('mysql:host=%s;port=%d;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,
            PDO::ATTR_STRINGIFY_FETCHES  => false,
        ];

        /**
         * PHP 8.4 moved the driver constants to Pdo\Mysql and deprecated the
         * PDO::MYSQL_* aliases in 8.5. Pick whichever this build understands so
         * the same file runs on 8.1 through 8.5 without a deprecation notice.
         */
        $initCommand = "SET SESSION sql_mode='STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION'";
        if (class_exists('Pdo\\Mysql')) {
            $options[\Pdo\Mysql::ATTR_INIT_COMMAND] = $initCommand;
        } else {
            $options[PDO::MYSQL_ATTR_INIT_COMMAND] = $initCommand;
        }

        if (!in_array('mysql', PDO::getAvailableDrivers(), true)) {
            self::fail('The pdo_mysql extension is not loaded in this PHP build.',
                'Install it (on Ubuntu: apt install php-mysql) and reload the web server.');
        }

        try {
            self::$pdo = new PDO($dsn, DB_USER, DB_PASS, $options);
        } catch (PDOException $e) {
            error_log('[db] ' . $e->getMessage());
            self::fail('The database is not reachable.', $e->getMessage());
        }

        return self::$pdo;
    }

    /**
     * Stop with a useful message. The underlying error is only shown when
     * APP_DEBUG is on - in production it goes to the log and the visitor sees
     * nothing that describes the server.
     */
    private static function fail(string $message, string $detail): never
    {
        http_response_code(503);

        if (PHP_SAPI === 'cli') {
            fwrite(STDERR, $message . "\n" . $detail . "\n");
            exit(1);
        }

        header('Content-Type: text/html; charset=utf-8');
        echo '<div style="font:15px/1.6 system-ui,sans-serif;max-width:60ch;margin:3rem auto;padding:0 1rem">';
        echo '<h1 style="font-size:1.1rem;margin:0 0 .5rem">' . htmlspecialchars($message) . '</h1>';

        if (defined('APP_DEBUG') && APP_DEBUG) {
            echo '<p style="margin:0 0 1rem;color:#555">Shown because APP_ENV is development.</p>';
            echo '<pre style="background:#f5f7f9;border:1px solid #d5dce4;border-radius:3px;'
               . 'padding:.75rem;font:13px/1.5 ui-monospace,monospace;white-space:pre-wrap">'
               . htmlspecialchars($detail) . '</pre>';
            echo '<p style="color:#555">Run <code>php tools/dbcheck.php</code> on the server '
               . 'for a full diagnosis.</p>';
        } else {
            echo '<p style="color:#555">The details are in the error log.</p>';
        }

        echo '</div>';
        exit;
    }

    public static function all(string $sql, array $params = []): array
    {
        $st = self::pdo()->prepare($sql);
        $st->execute($params);
        return $st->fetchAll();
    }

    public static function one(string $sql, array $params = []): ?array
    {
        $st = self::pdo()->prepare($sql);
        $st->execute($params);
        $row = $st->fetch();
        return $row === false ? null : $row;
    }

    public static function scalar(string $sql, array $params = []): mixed
    {
        $st = self::pdo()->prepare($sql);
        $st->execute($params);
        $v = $st->fetchColumn();
        return $v === false ? null : $v;
    }

    public static function run(string $sql, array $params = []): int
    {
        $st = self::pdo()->prepare($sql);
        $st->execute($params);
        return $st->rowCount();
    }

    public static function lastId(): int
    {
        return (int) self::pdo()->lastInsertId();
    }

    /** Key/value map from a two-column query. */
    public static function pairs(string $sql, array $params = []): array
    {
        $out = [];
        foreach (self::all($sql, $params) as $row) {
            $vals = array_values($row);
            $out[$vals[0]] = $vals[1];
        }
        return $out;
    }

    public static function transaction(callable $fn): mixed
    {
        $pdo = self::pdo();
        $pdo->beginTransaction();
        try {
            $result = $fn($pdo);
            $pdo->commit();
            return $result;
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            throw $e;
        }
    }
}
