<?php 
namespace Core;

use PDO;
use PDOException;

class Database{
    private static ?PDO $instance = null;
    private array $config;

    public function __construct(array $config){
        $this->config = $config;
    }

    public function getConnection(): PDO {
        if(self::$instance === null){
            $dsn = "{$this->config['driver']}:host={$this->config['host']};port={$this->config['port']};dbname={$this->config['database']};charset={$this->config['charset']}";

            try {
                self::$instance = new PDO(
                    $dsn,
                    $this->config['username'],
                    $this->config['password'],
                    [
                        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION, // Throw exceptions on errors
                        PDO::ATTR_DEFAULT_FETCH_MODE => $this->config['fetch_mode'] ?? PDO::FETCH_ASSOC, // Default fetch mode
                        PDO::ATTR_EMULATE_PREPARES   => false, // Disable emulation for real prepared statements
                    ]
                );
            } catch (PDOException $e) {
                // Log the error (e.g., to a file, or use a logging library)
                error_log("Database Connection Error: " . $e->getMessage());
                // In a production environment, you might show a generic error page
                // In development, you can re-throw for debugging
                throw new PDOException("Could not connect to the database. Check your configuration.", (int)$e->getCode(), $e);
            }
        }
        return self::$instance;
    }
}
?>