<?php
/*
 * $RCSfile: Confirm.inc,v $
 *
 * Gallery - a web based photo album viewer and editor
 * Copyright (C) 2000-2004 Bharat Mediratta
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

/**
 * 
 * @package Checkout
 * @subpackage UserInterface
 * @author Daniel Leaberry <leaberry@gmail.com>
 * @author Matthew Turnbull <matthew.turnbull@messagescan.net>
 */

/**
 * Required classes
 */
GalleryCoreApi::requireOnce('modules/checkout/classes/CheckoutHelper.class');
GalleryCoreApi::requireOnce('modules/checkout/classes/CheckoutItemHelper.class');
GalleryCoreApi::requireOnce('modules/checkout/classes/CheckoutTransactionHelper.class');

/**
 * This controller will handle the Checkout things
 *
 * @package Checkout
 * @subpackage UserInterface
 *
 */
class ConfirmController extends GalleryController {

    /**
     * @see GalleryController::handleRequest()
     */
    function handleRequest($form) {
	global $gallery;
	$nextViewisUrl = false;
						
	if (isset($form['action']['continue'])) { 
	    $session =& $gallery->getSession();

	    /* Call the helper to update the item records based on the form */
	    $ret = CheckoutHelper::updateCart($form);
	    if ($ret) {
		return array($ret->wrap(__FILE__, __LINE__), null);
	    }
	    
	    /* Load the required info from the cart */
	    list ($ret, $items) = CheckoutHelper::fetchCheckoutItems();
	    if ($ret) {
		return array($ret->wrap(__FILE__, __LINE__), null);
	    }

	    list ($ret, $itemList) = CheckoutHelper::loadCheckoutItems();
	    if ($ret) {
		return array($ret->wrap(__FILE__, __LINE__), null);
	    }

	    list ($ret, $product, $price) = CheckoutHelper::fetchProducts();
	    if ($ret) {
		return array($ret->wrap(__FILE__, __LINE__), null);
	    }

	    list ($ret, $paper) = CheckoutHelper::fetchPapers();
	    if ($ret) {
		return array($ret->wrap(__FILE__, __LINE__), null);
	    }

	    /* Load the required parameters from the module */
	    list ($ret, $postage) = GalleryCoreApi::getPluginParameter('module', 'checkout', 'postage');
	    if ($ret) {
		return array($ret->wrap(__FILE__, __LINE__), null);
	    }
	    
	    /* Tidy up by purging any dead transaction records now */
	    list($ret) = CheckoutTransactionHelper::purgeDeadTransactions();
	    if ($ret) {
		return array($ret->wrap(__FILE__, __LINE__), null);
	    }
	    
	    /* Create a GalleryCheckoutTransaction entity */
	    list ($ret, $transaction) =
		GalleryCoreApi::newFactoryInstance('GalleryEntity', 'GalleryCheckoutTransaction');
	    if ($ret) {
		return array($ret->wrap(__FILE__, __LINE__), null);
	    }
	    if (!isset($transaction)) {
		return array(GalleryCoreApi::error(ERROR_MISSING_OBJECT, __FILE__, __LINE__), null);
	    }
	    $ret = $transaction->create();
	    if ($ret) {
		return array($ret->wrap(__FILE__, __LINE__), null);
	    }

            /*
             * First purge any existing CheckoutItems for this transaction
             * then add new entries for everything in the cart
             */
            $ret = CheckoutItemHelper::purgeCheckoutItems($transaction->getId());
            if ($ret) {
                return array($ret->wrap(__FILE__, __LINE__), null);
            }
            
	    $total=0;
	    $allowCheckout = False;
	    foreach ($itemList as $item) {
	    	$subtotal = 0;
		for($x=0;$x<count($product);$x++) {
		    if ( isset($items[$item->getId()]['quant'][$x]) ) {
		    	$allowCheckout = True;
			/* Create the item entry */
			list ($ret, $txnItem) =
			    GalleryCoreApi::newFactoryInstance('GalleryEntity', 'GalleryCheckoutItem');
			if ($ret) {
			    return array($ret->wrap(__FILE__, __LINE__), null);
			}
			if (!isset($txnItem)) {
			    return array(GalleryCoreApi::error(ERROR_MISSING_OBJECT, __FILE__, __LINE__), null);
			}
			$ret = $txnItem->create($transaction->getId());
			if ($ret) {
			    return array($ret->wrap(__FILE__, __LINE__), null);
			}
			$txnItem->setItem($item->getId());
			$txnItem->setItemName($item->getPathComponent());
			$txnItem->setProduct($x);
			$txnItem->setProductName($product[$x]);
			$txnItem->setQty($items[$item->getId()]['quant'][$x]);
		    	if (isset($items[$item->getId()]['itemPrices'][$x])) {
			    $txnItem->setPriceEach($items[$item->getId()]['itemPrices'][$x]);
			    $txnItem->setPriceTotal(
					number_format($items[$item->getId()]['quant'][$x] *
							$items[$item->getId()]['itemPrices'][$x],
						      2, '.', ','));
			    $subtotal += ($items[$item->getId()]['quant'][$x] *
			    		  $items[$item->getId()]['itemPrices'][$x]);
			} else {
			    $txnItem->setPriceEach($price[$x]);
			    $txnItem->setPriceTotal(
					number_format($items[$item->getId()]['quant'][$x] *
						      $price[$x], 2, '.', ','));		    	
			    $subtotal += ($items[$item->getId()]['quant'][$x] * $price[$x]);
			}

			if ( isset($items[$item->getId()]['paper']) ) {
			    $txnItem->setNotes('Paper: ' . $items[$item->getId()]['paper']);
			}
			$ret = $txnItem->save();
			if ($ret) {
			    return array($ret->wrap(__FILE__, __LINE__), null);
			}			    

		    }
		}
		$total += $subtotal;
		$items[$item->getId()]['subtotal'] = number_format($subtotal, 2, '.', ',');
	    }
	    $total += $postage;
	    $total = number_format($total, 2, '.', ',');

	    /* Set and save the data */
	    $transaction->setdate(time());
	    $transaction->sethost(GalleryUtilities::getRemoteHostAddress());
	    $transaction->setbuyerId($gallery->getActiveUserId());
	    /* Because the G2 storage API only handles INTEGER numeric storage, store as string */
	    $transaction->setamount($total);
	    $transaction->setpostage($postage);
	    $ret = $transaction->save();
	    if ($ret) {
	        return array($ret->wrap(__FILE__, __LINE__), null);
	    }

	    $session->put('checkout.transactionId', serialize($transaction->getId()));
	    $session->put('checkout.total', serialize($total));
	    $ret = CheckoutHelper::setCheckoutItems($items);
	    if ($ret) {
		return array($ret->wrap(__FILE__, __LINE__), null);
	    }
	    
	    if ( $allowCheckout) {
		$nextView = 'checkout.ConfirmPhotos';
	    } else {
		$nextView = 'checkout.SelectProducts';
	    }

	}

	if (isset($form['action']['modify'])) {
	    $nextView = 'checkout.SelectProducts';			
	}

	if (isset($form['action']['emptycart'])) {
	    /* Call the helper to update the item records based on the form */
	    $ret = CheckoutHelper::emptycart($form);
	    if ($ret) {
		return array($ret->wrap(__FILE__, __LINE__), null);
	    }
	    $nextView = 'checkout.SelectProducts';
	}

	if (isset($form['action']['continueshopping'])) {
	    /* Call the helper to update the item records based on the form */
	    $ret = CheckoutHelper::updateCart($form);
	    if ($ret) {
		return array($ret->wrap(__FILE__, __LINE__), null);
	    }
	    if (isset($form['returnUrl'])) {
	    	$nextView = $form['returnUrl'];
		$nextViewisUrl = true;
	    } else {
	    	$nextView = 'core.ShowItem';
	    }
	}

	if (isset($form['action']['savechanges'])) {

        /* Call the helper to update the item records based on the form */
        $ret = CheckoutHelper::updateCart($form);
        if ($ret) {
            return array($ret->wrap(__FILE__, __LINE__), null);
        }
	    
        $nextView = 'checkout.SelectProducts';			
	}

	if ( $nextViewisUrl ) {
	    $results['redirect']['href'] = $nextView;
	} else {
	    $results['redirect']['view'] = $nextView;
	}
    
	if (isset($form['returnUrl'])) {
	    $results['status'] = array( 'returnUrl' => $form['returnUrl'] );
	} else {
	    $results['status'] = array( 'returnUrl' => '' );
	}
	$results['error'] = array();
	$results['isError'] = false;
	$errorView = '';

	return array(null, $results);

    }
}
?>