<?php
namespace Core;
use Core\Database\Connection;

class QueryBuilder
{
    protected string $table;
    protected array $wheres = [];
    protected array $params = [];
    protected string $orderBy = '';
    protected string $limit = '';

    public function __construct(string $table)
    {
        $this->table = $table;
    }

    public function where(string $column, mixed $value, string $operator = '=')
    {
        $this->wheres[] = "`{$column}` {$operator} ?";
        $this->params[] = $value;
        return $this;
    }

    public function orderBy(string $column, string $direction = 'ASC')
    {
        $this->orderBy = " ORDER BY `{$column}` {$direction}";
        return $this;
    }

    public function limit(int $count)
    {
        $this->limit = " LIMIT {$count}";
        return $this;
    }

    public function get(): array
    {
        $sql = "SELECT * FROM `{$this->table}`";

        if (!empty($this->wheres)) {
            $sql .= " WHERE " . implode(" AND ", $this->wheres);
        }

        $sql .= $this->orderBy . $this->limit;

        return Connection::fetchAll($sql, $this->params);
    }

    public function first(): array|null
    {
        $this->limit(1);
        $result = $this->get();
        return $result[0] ?? null;
    }
}
