<?php

/**
 * @version        $Id$
 * @package        ARTIO Booking
 * @subpackage  models
 * @copyright    Copyright (C) 2010 ARTIO s.r.o.. All rights reserved.
 * @author        ARTIO s.r.o., http://www.artio.net
 * @license     GNU/GPL http://www.gnu.org/copyleft/gpl.html
 * @link        http://www.artio.net Official website
 */
class BookingModelDailyFixedLimit extends JModelLegacy
{

    /**
     * @var JDate
     */
    protected $from;
    /**
     * @var JDate
     */
    protected $to;
    /**
     * @var TableReservationType
     */
    protected $rtype;
    /**
     * @var BookingService[]
     */
    protected $services = array();

    public function __construct($config = array())
    {
        $this->from = clone $config[0];
        $this->to = clone $this->from;
        $this->rtype = $config[1];
        $this->to->modify('+ ' . $this->rtype->realFix . ' days');
    }

    /**
     * Add service which covers the fixed limit.
     *
     * @param BookingService $service
     */
    public function addService($service)
    {
        if ($this->rtype->id == $service->rtypeId && $this->from->toUnix() <= $service->fromUts && $this->to->toUnix() >= $service->toUts) {
            $this->services[] = $service;
        }
    }

    public function __toString()
    {
        return $this->from->format('Y-m-d') . ' - ' . $this->to->format('Y-m-d');
    }

    /**
     * Check if the fixed limit is bookable.
     */
    public function check()
    {
        $now = JFactory::getDate();
        foreach ($this->services as $service) {
            if ($service->isInThePast($now) || (!$service->canReserve && !$service->nonFixed) || $service->closed) {
                return $this->disable();
            }
        }
        return $this->enable();
    }

    /**
     * Disable the fixed limit is some service is not enabled by another fixed limit.
     */
    protected function disable()
    {
        foreach ($this->services as $service) {
            if (!$service->isFixed && $service->canReserve) {
                $service->canReserve = false;
                $service->nonFixed = true;
            }
        }
    }

    /**
     * Enable the fixed limit if some service is disabled by another fixed limit.
     */
    protected function enable()
    {
        foreach ($this->services as $service) {
            if ($service->nonFixed) {
                $service->canReserve = true;
            }
            $service->isFixed = true;
        }
    }
}