<?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';

$db = JFactory::getDbo();
$db->setQuery('SHOW FIELDS FROM #__booking_reservation WHERE Field = ' . $db->quote('username'));
if (!$db->loadObject()) {
    $this->_addSQL('ALTER TABLE `#__booking_reservation` ADD `username` VARCHAR( 150 ) NOT NULL AFTER `customer`');
}

$db->setQuery('SHOW FIELDS FROM #__booking_subject WHERE Field = ' . $db->quote('location_use_parent'));
if (!$db->loadObject()) {
    $this->_addSQL('ALTER TABLE `#__booking_subject` ADD `location_use_parent` TINYINT( 1 ) NOT NULL AFTER `google_calendar`');
}

$db->setQuery('SHOW FIELDS FROM #__booking_subject WHERE Field = ' . $db->quote('location_content'));
if (!$db->loadObject()) {
    $this->_addSQL('ALTER TABLE `#__booking_subject` ADD `location_content` TEXT NOT NULL AFTER `google_calendar`');
}

$this->_addSQL('CREATE TABLE IF NOT EXISTS `#__booking_field` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(100) NOT NULL,
  `type` varchar(10) NOT NULL,
  `required` tinyint(1) NOT NULL,
  `options` text NOT NULL,
  `template` text NOT NULL,
  `special` tinyint(1) NOT NULL,
  `show_in_table` tinyint(1) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;');


$fields = (array) @unserialize(JComponentHelper::getParams('com_booking')->get('fields'));
if ($fields) {
    $q = 'INSERT INTO #__booking_field (title, type, required, options, template, special, show_in_table) VALUES ';
    foreach ($fields as $f) {
        $q .= '(' . $db->q($f['title']) . ', ' . $db->q($f['type']) . ', ' . (int) $f['required'] . ', ' . $db->q(json_decode($f['options'])) . ', ' . $db->q(json_encode($f['template'])) . ',' . (int) @$f['special'] . ',' . (int) @$f['show_in_table'] . '),';
    }
    $this->_addSQL(rtrim($q, ','));
}

$db->setQuery('SHOW FIELDS FROM #__booking_customer WHERE Field = ' . $db->quote('email'));
if (!$db->loadObject()) {
    $this->_addSQL("ALTER TABLE `#__booking_customer` ADD `email` VARCHAR(100) NOT NULL DEFAULT ''");
}

JInstaller::getInstance()->install(dirname(__FILE__) . '/../admin/extensions/payment_methods/paypalpdt');