<?php
/*
 * $RCSfile: AddToCart.inc,v $
 *
 * Gallery - a web based photo album viewer and editor
 * Copyright (C) 2000-2005 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.
 */

/**
 * @version $Revision: 1.2 $ $Date: 2006/04/07 20:53:19 $
 * @package Cart
 * @subpackage UserInterface
 * @author Bharat Mediratta <bharat@menalto.com>
 * @author Matthew Turnbull <matthew.turnbull@messagescan.net>
 */

/**
 * Required classes
 */
GalleryCoreApi::requireOnce('modules/checkout/classes/CheckoutHelper.class');

/**
 * This controller will handle the addition of an item to the cart
 *
 * @package Checkout
 * @subpackage UserInterface
 */
class AddToCartController extends GalleryController {

    /**
     * @see GalleryController::handleRequest()
     */
    function handleRequest($form) {
	global $gallery;

	$itemId = GalleryUtilities::getRequestVariables('itemId');

	list ($ret, $item) = GalleryCoreApi::loadEntitiesById($itemId);
	if ($ret) {
	    return array($ret->wrap(__FILE__, __LINE__), null);
	}

	/* Figure out what ids we care about */
	if ($item->getCanContainChildren()) {
	    list ($ret, $ids) = GalleryCoreApi::fetchChildDataItemIds($item);
	    if ($ret) {
		return array($ret->wrap(__FILE__, __LINE__), null);
	    }
	} else {
	    $ids = array($item->getId());
	}

	$ret = CheckoutHelper::addItemsToCart($ids);
	if ($ret) {
	    return array($ret->wrap(__FILE__, __LINE__), null);
	}

	/* Prepare our results */
    list ($ret, $cartRedirect) = GalleryCoreApi::getPluginParameter(
            'module', 'checkout', 'cartredirect');
    if ($ret) {
        return array($ret->wrap(__FILE__, __LINE__), null);
    }
    $returnUrl = GalleryUtilities::getRequestVariables('return');
    if ( $cartRedirect == 1 ) {
	    $results['redirect']['view'] = 'checkout.SelectProducts';
        $results['status'] = array( 'returnUrl' => $returnUrl );
    } else {
        $results['redirect']['href'] = $returnUrl;
        $results['status'] = array( 'checkoutSuccess' => true );
    }
	$results['error'] = array();

	return array(null, $results);
    }
}
?>
