<?php
namespace Incoviba\Repository\Venta\Reservation;

use Incoviba\Common;
use Incoviba\Model;
use Incoviba\Repository;

class State extends Common\Ideal\Repository
{
    public function __construct(Common\Define\Connection $connection, protected Repository\Venta\Reservation $reservationRepository)
    {
        parent::__construct($connection);
    }

    public function getTable(): string
    {
        return 'reservation_states';
    }

    public function create(?array $data = null): Model\Venta\Reservation\State
    {
        $map = (new Common\Implement\Repository\MapperParser(['type']))
            ->register('reservation_id', (new Common\Implement\Repository\Mapper())
                ->setProperty('reservation')
                ->setFunction(function($data) use ($data) {
                    return $this->reservationRepository->fetchById($data['reservation_id']);
                }))
            ->register('date', new Common\Implement\Repository\Mapper\DateTime('date'));
        return $this->parseData(new Model\Venta\Reservation\State(), $data, $map);
    }
    public function save(Common\Define\Model $model): Model\Venta\Reservation\State
    {
        $model->id = $this->saveNew(
            ['reservation_id', 'date', 'type'],
            [$model->reservation->id, $model->date->format('Y-m-d'), $model->type]
        );
        return $model;
    }
    public function edit(Common\Define\Model $model, array $new_data): Model\Venta\Reservation\State
    {
        return $this->update($model, ['reservation_id', 'date', 'type'], $new_data);
    }

    public function fetchByReservation(int $reservation_id): array
    {
        $query = $this->connection->getQueryBuilder()
            ->select()
            ->from($this->getTable())
            ->where('reservation_id = :reservation_id');
        return $this->fetchMany($query, ['reservation_id' => $reservation_id]);
    }
    public function fetchActiveByReservation(int $reservation_id): array
    {
        $query = $this->connection->getQueryBuilder()
            ->select()
            ->from($this->getTable())
            ->where('reservation_id = :reservation_id AND type = :type');
        return $this->fetchMany($query, ['reservation_id' => $reservation_id, 'type' => Model\Venta\Reservation\State\Type::ACTIVE]);
    }
}
