<?php
declare(strict_types=1);

namespace App\Config;

use PDO;
use Exception;
use App\Core\Response;

/**
 * PDO Singleton Connection
 */
class Database
{
    private static ?PDO $instance = null;

    private function __construct()
    {
    }

    public static function getInstance(): PDO
    {
        if (self::$instance === null) {
            $host = $_SERVER['DB_HOST'] ?? getenv('DB_HOST') ?: 'localhost';
            $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;port=$port;dbname=$db;charset=$charset";
            $options = [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false,
            ];

            try {
                self::$instance = new PDO($dsn, $user, $pass, $options);
            } catch (Exception $e) {
                Response::error("Database connection failed", ['msg' => $e->getMessage()], 500);
            }
        }
        return self::$instance;
    }
}
