<?php
/**
 * Database Support Class
 */

declare(strict_types=1);

namespace App\Support;

use PDO;
use PDOStatement;

class Database
{
    private static ?PDO $connection = null;
    
    public static function setConnection(PDO $pdo): void
    {
        self::$connection = $pdo;
    }
    
    public static function getConnection(): PDO
    {
        if (self::$connection === null) {
            throw new \RuntimeException('Database connection not initialized');
        }
        return self::$connection;
    }
    
    public static function fetch(string $sql, array $params = []): ?array
    {
        $stmt = self::getConnection()->prepare($sql);
        $stmt->execute($params);
        $result = $stmt->fetch();
        return $result ?: null;
    }
    
    public static function fetchAll(string $sql, array $params = []): array
    {
        $stmt = self::getConnection()->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchAll();
    }
    
    public static function insert(string $table, array $data): string
    {
        $columns = implode(', ', array_keys($data));
        $placeholders = implode(', ', array_fill(0, count($data), '?'));
        
        $sql = "INSERT INTO {$table} ({$columns}) VALUES ({$placeholders}) RETURNING id";
        $stmt = self::getConnection()->prepare($sql);
        $stmt->execute(array_values($data));
        
        $result = $stmt->fetch();
        return $result['id'] ?? '';
    }
    
    public static function update(string $table, array $data, string $where, array $whereParams = []): int
    {
        $set = implode(' = ?, ', array_keys($data)) . ' = ?';
        $sql = "UPDATE {$table} SET {$set} WHERE {$where}";
        
        $stmt = self::getConnection()->prepare($sql);
        $stmt->execute([...array_values($data), ...$whereParams]);
        
        return $stmt->rowCount();
    }
    
    public static function delete(string $table, string $where, array $whereParams = []): int
    {
        $sql = "DELETE FROM {$table} WHERE {$where}";
        $stmt = self::getConnection()->prepare($sql);
        $stmt->execute($whereParams);
        
        return $stmt->rowCount();
    }
    
    public static function query(string $sql, array $params = []): PDOStatement
    {
        $stmt = self::getConnection()->prepare($sql);
        $stmt->execute($params);
        return $stmt;
    }
    
    public static function beginTransaction(): bool
    {
        return self::getConnection()->beginTransaction();
    }
    
    public static function commit(): bool
    {
        return self::getConnection()->commit();
    }
    
    public static function rollback(): bool
    {
        return self::getConnection()->rollBack();
    }
    
    public static function lastInsertId(): string
    {
        return self::getConnection()->lastInsertId();
    }
}