<?php
// CoreFlux/core/Database/Connection.php

namespace Core\Database;

use PDO;
use Exception;

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

    private function __construct() {}
    private function __clone() {}

    public static function init(array $config): PDO
    {
        if (self::$instance === null) {
            try {
                $dsn = "{$config['driver']}:host={$config['host']};port={$config['port']};dbname={$config['database']};charset={$config['charset']}";
                self::$instance = new PDO($dsn, $config['username'], $config['password'], [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                    PDO::ATTR_EMULATE_PREPARES => false,
                ]);
            } catch (\PDOException $e) {
                throw new Exception("Database connection failed: " . $e->getMessage());
            }
        }
        return self::$instance;
    }

    public static function getInstance(): ?PDO
    {
        return self::$instance;
    }

    public static function reconnect(array $config): PDO
    {
        self::$instance = null;
        return self::init($config);
    }

    public static function execute(string $sql, array $params = []): int
    {
        if (!self::$instance) {
            throw new Exception("No database connection initialized. Call Connection::init() first.");
        }
        $stmt = self::$instance->prepare($sql);
        $stmt->execute($params);
        return $stmt->rowCount();
    }
    
    public static function fetch(string $sql, array $params = [])
    {
        if (!self::$instance) {
            throw new Exception("No database connection initialized.");
        }
        $stmt = self::$instance->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetch();
    }
    
    public static function fetchAll(string $sql, array $params = []): array
    {
        if (!self::$instance) {
            throw new Exception("No database connection initialized.");
        }
        $stmt = self::$instance->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchAll();
    }

    /**
     * Get the current database/schema name
     */
    public static function getDatabaseName(): string
    {
        if (!self::$instance) {
            throw new Exception("No database connection initialized.");
        }
        return (string) self::$instance->query("SELECT DATABASE()")->fetchColumn();
    }

    /**
     * Check if a table exists in the current database
     */
    public static function tableExists(string $table): bool
    {
        try {
            $dbName = self::getDatabaseName();
            $sql = "SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES 
                    WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?";
            $result = self::fetch($sql, [$dbName, $table]);
            return !empty($result) && (int)array_values($result)[0] > 0;
        } catch (Exception $e) {
            return false;
        }
    }
}
