<?php
namespace Incoviba\Model\Venta;

use DateTimeInterface;
use Incoviba\Common;
use Incoviba\Model;

class Reservation extends Common\Ideal\Model
{
    public Model\Persona $buyer;
    public DateTimeInterface $date;
    public array $units = [];
    public array $promotions = [];
    public ?Model\Proyecto\Broker $broker = null;
    protected array $states = [];

    public function states(): array
    {
        if (!isset($this->states)) {
            $this->states = $this->runFactory('states');
        }
        return $this->states;
    }

    protected Model\Venta\Reservation\State $currentState;

    public function currentState(): Model\Venta\Reservation\State
    {
        if (!isset($this->currentState)) {
            $this->currentState = last($this->states());
        }
        return $this->currentState;
    }

    public function addUnit(Model\Venta\Unidad $unit, float $value): self
    {
        if (($i = $this->findUnit($unit->id)) !== null) {
            $this->units[$i]['value'] = $value;
            return $this;
        }
        $this->units[] = [
            'unit' => $unit,
            'value' => $value,
        ];
        return $this;
    }

    public function removeUnit(int $unit_id): self
    {
        if (($i = $this->findUnit($unit_id)) === null) {
            return $this;
        }
        unset($this->units[$i]);
        $this->units = array_values($this->units);
        return $this;
    }

    public function findUnit(int $unit_id): ?int
    {
        foreach ($this->units as $idx => $unit) {
            if ($unit['unit']->id == $unit_id) {
                return $idx;
            }
        }
        return null;
    }

    public function hasUnit(int $unit_id): bool
    {
        return $this->findUnit($unit_id) !== null;
    }

    protected function jsonComplement(): array
    {
        return [
            'buyer_rut' => $this->buyer->rut,
            'date' => $this->date->format('Y-m-d'),
            'units' => $this->units,
            'promotions' => $this->promotions,
            'broker_rut' => $this->broker?->rut,
        ];
    }
}
