<?php

namespace App\Core;

/**
 * ITSWEBER CMS – Database
 *
 * PDO wrapper with prepared statement support.
 */
class Database
{
    private \PDO $pdo;
    private string $prefix;

    public function __construct(array $config)
    {
        $dsn = sprintf(
            'mysql:host=%s;port=%s;dbname=%s;charset=utf8mb4',
            $config['host'] ?? '127.0.0.1',
            $config['port'] ?? '3306',
            $config['name'] ?? ''
        );

        $this->pdo = new \PDO($dsn, $config['user'] ?? '', $config['password'] ?? '', [
            \PDO::ATTR_ERRMODE            => \PDO::ERRMODE_EXCEPTION,
            \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
            \PDO::ATTR_EMULATE_PREPARES   => false,
        ]);

        $this->prefix = $config['prefix'] ?? 'iw_';
    }

    /**
     * Execute a query with optional parameters.
     */
    public function query(string $sql, array $params = []): \PDOStatement
    {
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($params);
        return $stmt;
    }

    /**
     * Fetch all rows.
     */
    public function fetchAll(string $sql, array $params = []): array
    {
        return $this->query($sql, $params)->fetchAll();
    }

    /**
     * Fetch a single row.
     */
    public function fetch(string $sql, array $params = []): ?array
    {
        $result = $this->query($sql, $params)->fetch();
        return $result ?: null;
    }

    /**
     * Alias for fetch() – returns a single row.
     */
    public function fetchOne(string $sql, array $params = []): ?array
    {
        return $this->fetch($sql, $params);
    }

    /**
     * Fetch a single value.
     */
    public function fetchColumn(string $sql, array $params = [], int $column = 0): mixed
    {
        return $this->query($sql, $params)->fetchColumn($column);
    }

    /**
     * Insert a row and return the last insert ID.
     */
    public function insert(string $table, array $data): int
    {
        $columns = implode(', ', array_keys($data));
        $placeholders = implode(', ', array_map(fn($k) => ':' . $k, array_keys($data)));
        $sql = "INSERT INTO {$table} ({$columns}) VALUES ({$placeholders})";
        $this->query($sql, $data);
        return (int) $this->pdo->lastInsertId();
    }

    /**
     * Update rows matching conditions.
     */
    public function update(string $table, array $data, array $where): int
    {
        $setParts = array_map(fn($k) => "{$k} = :set_{$k}", array_keys($data));
        $whereParts = array_map(fn($k) => "{$k} = :where_{$k}", array_keys($where));

        $sql = "UPDATE {$table} SET " . implode(', ', $setParts)
             . " WHERE " . implode(' AND ', $whereParts);

        $params = [];
        foreach ($data as $k => $v) {
            $params["set_{$k}"] = $v;
        }
        foreach ($where as $k => $v) {
            $params["where_{$k}"] = $v;
        }

        $stmt = $this->query($sql, $params);
        return $stmt->rowCount();
    }

    /**
     * Delete rows matching conditions.
     */
    public function delete(string $table, array $where): int
    {
        $whereParts = array_map(fn($k) => "{$k} = :{$k}", array_keys($where));
        $sql = "DELETE FROM {$table} WHERE " . implode(' AND ', $whereParts);
        $stmt = $this->query($sql, $where);
        return $stmt->rowCount();
    }

    /**
     * Get the table prefix.
     */
    public function prefix(): string
    {
        return $this->prefix;
    }

    /**
     * Get prefixed table name.
     */
    public function table(string $name): string
    {
        return $this->prefix . $name;
    }

    /**
     * Get the last insert ID from the most recent INSERT.
     */
    public function lastInsertId(): string
    {
        return $this->pdo->lastInsertId();
    }

    /**
     * Get the raw PDO instance.
     */
    public function pdo(): \PDO
    {
        return $this->pdo;
    }

    /**
     * Begin a transaction.
     */
    public function beginTransaction(): void
    {
        $this->pdo->beginTransaction();
    }

    /**
     * Commit a transaction.
     */
    public function commit(): void
    {
        $this->pdo->commit();
    }

    /**
     * Rollback a transaction.
     */
    public function rollback(): void
    {
        $this->pdo->rollBack();
    }

    /**
     * Test the database connection.
     */
    public static function testConnection(array $config): bool
    {
        try {
            new self($config);
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }
}
