<?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 BookingModelPeriodYearly extends BookingModelPeriod
{

    protected function _calculate()
    {
        $weeks = array();

        $year = $this->beginDay->format('Y');
        $first = JFactory::getDate($year . '-' . $this->item->period_month . '-01');

        while ($first->toUnix() < $this->endDayUnix) { // check all months in period
            $weeks[$year] = $first->format('W') + $this->item->period_week - 1; // required month week in period
            $year++;
            $first = JFactory::getDate($year . '-' . $this->item->period_month . '-01');
        }

        $day = $this->beginDayUnix;
        $jump = 86400; // until find first jump for day
        while ($day < $this->endDayUnix) {

            if ($this->item->period_end == PERIOD_END_TYPE_AFTER && $this->item->period_total == $this->item->period_occurrences)
                break;

            $currentDate = JFactory::getDate($day);

            if ($currentDate->format('N') == $this->item->period_day && in_array((int)$currentDate->format('W'), $weeks)) { // day equals to period week day and month week
                $this->item->period_total++;
                $this->item->period[] = $day;
                $jump = 604800; // since find first jump for week
            }
            $day += $jump; // next day or week
        }
    }
}