<?php

/**
 * Class CfSettings
 * Is used for work with cf_settings
 */
class CfSettings implements CfPdoInterface
{
    /** @var CfSettings */
    private static $instance = null;

    /** @var PDO $connection */
    private $connection;

    /**
     * CfSettings constructor.
     */
    private function __construct()
    {
        $this->connection = new PDO(
            "pgsql:host=" . OAUTH_DATABASE_HOST . "; dbname=" . OAUTH_DATABASE_NAME . ";port=" . OAUTH_DATABASE_PORT,
            OAUTH_DATABASE_USER,
            OAUTH_DATABASE_PASS
        );
    }

    /**
     * @return self
     */
    public static function getInstance(): CfPdoInterface
    {
        if (!self::$instance) {
            self::$instance = new CfSettings();
        }

        return self::$instance;
    }

    /**
     * @param $key
     * @return array
     */
    public function getSetting($key)
    {
        $sql = "SELECT * FROM settings WHERE settings.key = {$this->connection->quote($key)} LIMIT 1";
        $result = $this->connection->query($sql)->fetchAll(PDO::FETCH_KEY_PAIR);

        if (!$result) {
            return SettingsHelper::DEFAULTS[$key] ?? null;
        }

        $value = $result[$key];
        if (in_array($key, SettingsHelper::INTEGERS)) {
            $value = (int)$value;
        } elseif (in_array($key, SettingsHelper::BOOLEANS)) {
            $value = $value === 'true';
        }

        return $value;
    }

    public function getSettings()
    {
        return $this->connection->query('SELECT * FROM settings')->fetchAll(PDO::FETCH_KEY_PAIR);
    }

    /**
     * Return the host-cleanup only settings as a typed DTO, decoding JSON-string
     * values stored in the settings table and falling back to defaults.
     */
    public function getCleanupSettings(): HostsCleanupSettingsDTO
    {
        return HostsCleanupSettingsDTO::fromSettings($this->getSettings());
    }

    /**
     * @return PDO
     */
    public function getConnection(): PDO
    {
        return $this->connection;
    }
}
