<?php

class Database {
    private $host;
    private $dbname;
    private $username;
    private $password;
    private $charset;
    private $port;
    private $pdo;
    private $error;

    public function __construct() {
        $config = require __DIR__ . '/../config/database.php';
        
        $this->host = $config['host'];
        $this->dbname = $config['dbname'];
        $this->username = $config['username'];
        $this->password = $config['password'];
        $this->charset = $config['charset'];
        $this->port = isset($config['port']) ? (int)$config['port'] : 3306;

        $dsn = "mysql:host=" . $this->host . ";port=" . $this->port . ";dbname=" . $this->dbname . ";charset=" . $this->charset;
        $options = [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES   => false,
        ];

        try {
            $this->pdo = new PDO($dsn, $this->username, $this->password, $options);
        } catch (\PDOException $e) {
            // Check if it's a "Unknown database" error
            if ($e->getCode() == 1049) {
                // Try connecting without dbname to create it
                $this->createDatabase();
            } else {
                $this->error = $e->getMessage();
                die("Database Connection Failed: " . $this->error);
            }
        }
    }

    private function createDatabase() {
        try {
            $dsn = "mysql:host=" . $this->host . ";port=" . $this->port . ";charset=" . $this->charset;
            $pdo = new PDO($dsn, $this->username, $this->password);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $pdo->exec("CREATE DATABASE IF NOT EXISTS `" . $this->dbname . "`");
            
            // Reconnect with dbname
            $dsn = "mysql:host=" . $this->host . ";port=" . $this->port . ";dbname=" . $this->dbname . ";charset=" . $this->charset;
            $this->pdo = new PDO($dsn, $this->username, $this->password, [
                PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES   => false,
            ]);
        } catch (\PDOException $e) {
            die("Database Creation Failed: " . $e->getMessage());
        }
    }

    public function connect() {
        return $this->pdo;
    }
}
