<?php

namespace App\Models;

use App\Models\BaseModel;
use Illuminate\Support\Collection;

class CiQueryResult extends Collection
{
    public function __construct($items = [])
    {
        if ($items instanceof Collection) {
            $items = $items->all();
        }

        parent::__construct(array_map([$this, 'castRow'], (array) $items));
    }

    protected function castRow($row): array
    {
        if ($row instanceof Model) {
            return $row->toArray();
        }

        if (is_object($row)) {
            return (array) $row;
        }

        return (array) $row;
    }

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

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

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

        if ($column === null) {
            return $row;
        }

        return $row[$column] ?? null;
    }
}
