<?php
namespace App\Config;

use PDO;
use PDOException;

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

    public static function getConnection(): PDO {
        if (self::$instance === null) {
            Config::load();

            $host = Config::get('DB_HOST', '127.0.0.1');
            $port = Config::get('DB_PORT', '3306');
            $db   = Config::get('DB_DATABASE', 'whatsapp_crm');
            $user = Config::get('DB_USERNAME', 'root');
            $pass = Config::get('DB_PASSWORD', '');

            $dsn = "mysql:host={$host};port={$port};dbname={$db};charset=utf8mb4";

            $options = [
                PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES   => false,
                PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci"
            ];

            try {
                self::$instance = new PDO($dsn, $user, $pass, $options);
            } catch (PDOException $e) {
                // If database connection fails, log or show friendly setup error
                if (Config::get('APP_DEBUG', true)) {
                    die("<div style='font-family: sans-serif; padding: 2rem; background: #fee2e2; color: #991b1b; border-radius: 8px;'>
                        <h2>Database Connection Failed</h2>
                        <p>{$e->getMessage()}</p>
                        <p>Have you run the installer? <a href='/database/installer.php' style='color: #2563eb; font-weight: bold;'>Click here to run Installer Wizard</a></p>
                    </div>");
                } else {
                    die("Database connection failed. Please contact administrator.");
                }
            }
        }

        return self::$instance;
    }
}
