<?php

/**
 * Occupancy types list model.
 * 
 * @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
 */

defined('_JEXEC') or die('Restricted access');

define('OTYPES_PREFIX', 'otype-');

//import needed Joomla! libraries
jimport('joomla.application.component.model');
//import needed JoomLIB helpers
AImporter::helper('model');

class BookingModelOccupancyTypes extends AModel
{
    
    /**
     * @var TableOccupancyType
     */
    var $_table;
    /**
     * @var TableSubject
     */
    protected $_subject;

    public function __construct($subject = array())
    {
        parent::__construct();
        $this->_table = $this->getTable('occupancytype');
        $this->_subject = $subject;
    }
    
    public function getData($key = 'id', $class = 'stdClass')
    {
    	$query = $this->_db->getQuery(true)
            ->select('*')
            ->from('#__booking_occupancy_type')
            ->where('subject = ' . (int) $this->_subject->id)
            ->order('type');

        $items = $this->_db->setQuery($query)->loadObjectList($key, $class);

        $standard = $extra = 0;
        foreach($items as $item) {
            $item->type == 0 ? $standard++ : $extra++;
        }

        foreach($items as $item) {
            if ($item->type == 0 && $standard == 1) { // only standard occupancy type
                $item->min = $this->_subject->standard_occupancy_min;
                $item->emptyOption = false;
            } else if ($item->type == 1 && $extra == 1) { // only extra occupancy type
                $item->min = $this->_subject->extra_occupancy_min;
                $item->emptyOption = false;
            } else {
                $item->min = 1;
                $item->emptyOption = true;
            }
            $item->max = $item->type == 0 ? $this->_subject->standard_occupancy_max : $this->_subject->extra_occupancy_max;
        }

        return $items;
    }
    
    public function store(&$subject, &$data, $foreignKeys = null, $dataPrefix = null, &$data2 = null)
    {
    	if (empty($data[OTYPES_PREFIX . 'title']))
    		$data[OTYPES_PREFIX . 'title'] = $data[OTYPES_PREFIX . 'type'] = array();
    	return parent::store($this->_db, $this->_table, array('subject' => $subject), OTYPES_PREFIX, $data);
    }
}