<?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
 */

/**
 * Tries "safeL SQL query, if not set previous error
 * @param unknown_type $dberr
 * @param unknown_type $db
 * @param unknown_type $query
 * @param unknown_type $errorTxt
 */
function BookingUpgradeTryQuery(&$dberr,&$db,$query,$errorTxt) {
	
	if (!$dberr) {
		$db->setQuery($query);
		if (!$db->query()){
			$dberr=true;
			JError::raiseWarning(0,'Upgrade error: '.$errorTxt.': '.$db->getErrorMsg());
		}
	}
}

function BookingUpgradeTryQueryItems(&$dberr,&$db,$query,$errorTxt) {
	
	if (!$dberr) {
		$db->setQuery($query);
		if (!$db->query()){
			$dberr=true;
			JError::raiseWarning(0,'Upgrade error: '.$errorTxt.': '.$db->getErrorMsg());
			$db->setQuery('DROP TABLE `#__booking_reservation_items`'); //resert items upgrade to initial state (delete)
			if (!$db->query())
				JError::raiseWarning(0,'Cannot delete #__booking_reservation_items: '.$db->getErrorMsg());
		}
	}
}

if (file_exists(($installer = ($admin = dirname(__FILE__) . DS . '..' . DS . 'admin' . DS) . 'install.booking.php'))) {
    include_once ($installer);
    
    //this part should be performed only when upgrading to 1.3.0, 
    //but will be performed always when `#__booking_reservation_items` table not exists
    //DB update which add new items table and split old reservations between old and new ones
    $dberr=false;
    $itemsTableAdded=false;
    
	$db = JFactory::getDBO();
	$mainframe = JFactory::getApplication();
	
	//determmine if new items table not exists yet...
	$db->setQuery('SHOW TABLES LIKE \'#__booking_reservation_items\'');
	$table = $db->loadResult();

	//create items table
	if (empty($table)){
		//create exact copy of reservation table with indexes
		$db->setQuery('CREATE TABLE IF NOT EXISTS `#__booking_reservation_items` LIKE `#__booking_reservation`');
		if (!$db->query()){
			JError::raiseWarning(0,'Upgrade error: #__booking_reservation_items not created');
			$dberr=true;}
		else
			$itemsTableAdded = true;
	}
		
	if ($itemsTableAdded){
		
		$db->setQuery('SELECT count(*) FROM `#__booking_reservation`');
		$reservations = $db->loadResult();
	
		//copy old reservations to new table
		if ($reservations)
			BookingUpgradeTryQueryItems($dberr,$db,'INSERT INTO `#__booking_reservation_items` SELECT * FROM `#__booking_reservation`','#__booking_reservation_items not filled with #__booking_reservation');
		
		//add reservation_id field
		BookingUpgradeTryQueryItems($dberr,$db,'ALTER TABLE `#__booking_reservation_items` ADD `reservation_id` INT(11) NOT NULL AFTER `id`','reservation_id not added');
		
		//add new price fields
		BookingUpgradeTryQueryItems($dberr,$db,'ALTER TABLE `#__booking_reservation_items` ADD `fullDeposit` FLOAT NOT NULL DEFAULT \'0\' AFTER `price`','fullDeposit not added');
		BookingUpgradeTryQueryItems($dberr,$db,'ALTER TABLE `#__booking_reservation_items` ADD `fullPriceSupplements` FLOAT NOT NULL DEFAULT \'0\' AFTER `price`','fullPriceSupplements not added');
		BookingUpgradeTryQueryItems($dberr,$db,'ALTER TABLE `#__booking_reservation_items` ADD `fullPrice` FLOAT NOT NULL DEFAULT \'0\' AFTER `price`','fullPrice not added');

		//set reserved item id same as reservation id and fill new price columns with former ones
		BookingUpgradeTryQueryItems($dberr,$db,'UPDATE `#__booking_reservation_items` SET `reservation_id` = `id`, `fullPrice` = `price`, `fullPriceSupplements` = `price`, `fullDeposit` = `deposit`','new fields in #__booking_reservation_items not updated by old ones ');
		
		//reservation suplements table stys the same, only will be pointing to #__booking_reservation_items table which have same ids at this point

		//upgrade reservation supplements: add full price and set initial values to price
		$db->setQuery('SHOW COLUMNS FROM `#__booking_reservation_supplement`');
		$columns = $db->loadObjectList('Field');
		if (!isset($columns['fullPrice'])){
			BookingUpgradeTryQuery($dberr,$db,'ALTER TABLE `#__booking_reservation_supplement` ADD `fullPrice` FLOAT NOT NULL DEFAULT \'0\' AFTER `price`','Cannot add fullPrice to reservation supplements');
			BookingUpgradeTryQuery($dberr,$db,'UPDATE `#__booking_reservation_supplement` SET `fullPrice` = `price`','Cannot set fullPrice ssme as price in supplements');
		}
		if (!isset($columns['capacity']))
			BookingUpgradeTryQuery($dberr,$db,'ALTER TABLE `#__booking_reservation_supplement` ADD `capacity` INT(11) NOT NULL DEFAULT \'1\' AFTER `fullPrice`','Cannot add capacity to reservation supplements');		
	}
	
	//now we can perform regular db update witch deletes unnecessary columns from both tables and update rest of db changes
	if (!$dberr)
		BookingInstaller::update($admin . 'sql' . DS . 'install.mysql.utf8.sql');
	else
		JError::raiseWarning(0,'Error during db update script. Database not updated');

    BookingInstaller::rename();
}

?>