<?php 

/**
 * @version		$Id$
 * @package		ARTIO Booking
 * @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');

/* @var $this BookingModelUpgrade */

require_once dirname(__FILE__) . '/reinstall.php';

$this->_addSql("ALTER TABLE `#__booking_price` ADD `deposit_type` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `deposit`");
$this->_addSql("ALTER TABLE `#__booking_price` ADD `deposit_include_supplements` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `deposit_capacity_multiply`");

$this->_addSql("CREATE TABLE IF NOT EXISTS `#__booking_notification` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(100) NOT NULL,
`event` varchar(30) NOT NULL,
`template` int(11) NOT NULL,
`prereserved` tinyint(1) NOT NULL,
`reserved` tinyint(1) NOT NULL,
`cancelled` tinyint(1) NOT NULL,
`unpaid` tinyint(1) NOT NULL,
`deposit` tinyint(1) NOT NULL,
`paid` tinyint(1) NOT NULL,
`days` int(11) NOT NULL,
`weeks` int(11) NOT NULL,
`hours` int(11) NOT NULL,
`minutes` int(11) NOT NULL,
`checked_out` int(11) NOT NULL,
`checked_out_time` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `checked_out` (`checked_out`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8");

$this->_addSql("CREATE TABLE IF NOT EXISTS `#__booking_notification_queue` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`reservation_item_id` int(11) NOT NULL,
`notification_id` int(11) NOT NULL,
`email_subject` varchar(100) NOT NULL,
`email_body` text NOT NULL,
`email_receiver` varchar(100) NOT NULL,
`email_mode` tinyint(1) NOT NULL,
`status` tinyint(1) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8");

$db = JFactory::getDbo();
 
$rule = array();
$rule[] = 'booking.mailing.new.reservation';
$rule[] = 'booking.mailing.change.reservation';
$rule[] = 'booking.mailing.cancel.reservation';
 
// load existing rules
$query = $db->getQuery(true);
$query->select('rules')->from('#__assets')->where("name = 'com_booking'");
$db->setQuery($query);
$rules = $db->loadResult();
 
$rules = json_decode($rules);
 
// initialize with fresh installation
if (!is_object($rules))
	$rules = new stdClass();
 
foreach ($rule as $r)
	if (empty($rules->$r))
		$rules->$r = new stdClass();
 
// load all usergroups
$query = $db->getQuery(true);
$query->select('id')->from('#__usergroups');
$db->setQuery($query);
$userGroups = $db->loadColumn();
 
// allow rules for each usergroup
foreach ($userGroups as $userGroup)
	foreach ($rule as $r)
		$rules->$r->$userGroup = 1;
 
// save rules back
$rules = json_encode($rules);
$rules = $db->quote($rules);
 
$query = $db->getQuery(true);
$query->update('#__assets')->set("rules = $rules")->where("name = 'com_booking'");
$db->setQuery($query);
$db->query();