<?php
declare(strict_types=1);

namespace App\Core;

use PDO;
use App\Core\Response;

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

    private function __construct()
    {
        $host = $_SERVER['DB_HOST'] ?? getenv('DB_HOST') ?: '127.0.0.1';
        $db = $_SERVER['DB_NAME'] ?? getenv('DB_NAME') ?: 'billflow';
        $user = $_SERVER['DB_USER'] ?? getenv('DB_USER') ?: 'root';
        $pass = $_SERVER['DB_PASS'] ?? getenv('DB_PASS') ?: '';
        $port = $_SERVER['DB_PORT'] ?? getenv('DB_PORT') ?: '3306';
        $charset = 'utf8mb4';

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

        try {
            $this->connection = new PDO($dsn, $user, $pass, $options);
        } catch (\PDOException $e) {
            Response::error("Database connection failed: " . $e->getMessage(), [], 500);
        }
    }

    public static function getInstance(): PDO
    {
        if (self::$instance === null) {
            $dbObj = new self();
            self::$instance = $dbObj->connection;
        }
        return self::$instance;
    }
}
