<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;

class CiModelBuilder extends Builder
{
    protected array $setData = [];

    public function get($columns = ['*'])
    {
        return new CiQueryResult(parent::get($columns));
    }

    public function first($columns = ['*'])
    {
        $model = parent::first($columns);
        return $model;
    }

    public function findAll(int $limit = 0, int $offset = 0)
    {
        if ($limit > 0) {
            $this->limit($limit);
        }

        if ($offset > 0) {
            $this->offset($offset);
        }

        return $this->getResultArray();
    }

    public function getResultArray(): array
    {
        return $this->get()->getResultArray();
    }

    public function getRowArray(): ?array
    {
        return $this->get()->getRowArray();
    }

    public function getRow(?string $column = null)
    {
        return $this->get()->getRow($column);
    }

    public function countAllResults(): int
    {
        return $this->count();
    }

    public function like(string $column, $match, string $side = 'both')
    {
        $pattern = $this->wrapLike($match, $side);
        $this->query->where($column, 'like', $pattern);
        return $this;
    }

    public function set($key, $value = null, bool $escape = true)
    {
        if (is_array($key)) {
            $this->setData = array_merge($this->setData, $key);
        } else {
            $this->setData[$key] = $value;
        }

        return $this;
    }

    public function update(array $values = [])
    {
        $data = $values ?: $this->setData;
        $this->setData = [];

        return parent::update($data);
    }

    public function where($column, $operator = null, $value = null, $boolean = 'and')
    {
        if ($operator !== null && $value === null && preg_match('/^(.*)\\s(>=|<=|<>|!=|>|<)$/', $column, $matches)) {
            return parent::where(trim($matches[1]), $matches[2], $operator, $boolean);
        }

        return parent::where($column, $operator, $value, $boolean);
    }

    protected function wrapLike($match, string $side): string
    {
        $pattern = "%{$match}%";

        switch (strtolower($side)) {
            case 'before':
                $pattern = "%{$match}";
                break;
            case 'after':
                $pattern = "{$match}%";
                break;
        }

        return $pattern;
    }
}
