<?php
include_once(PS_ADMIN_DIR.'/../classes/AdminTab.php');
include_once('./tabs/AdminPayment.php');

class Cart2Order extends PaymentModule
{
	private	$_html = '';
	private	$_email = 'paypal@leewaterman.com';
	private $_postErrors = array();
	public $installedPaymentModules = array();

	
	public function __construct()
	{
		$this->name = 'cart2order';
		$this->tab = 'Lee Waterman Development';
		$this->version = '0.4';

        parent::__construct();

		$this->page = basename(__FILE__, '.php');
        $this->displayName = $this->l('Cart 2 Order');
        $this->description = $this->l('Manually change a cart to an order. leewaterman.com');
		
	}
	
	public function install()
	{
		if (!parent::install()
			OR !Configuration::updateValue('CART2ORDER_TEMP', 1)
			OR !$this->registerHook('payment')
			OR !$this->registerHook('paymentReturn')
		 	OR !$this->installModuleTab('AdminCart2Order', array(1=>'Cart 2 Order', 2=>'Panier 2 Commande'), 2))
			return false;
		return true;
	}
	
	
	public function uninstall()
	{
		if (!Configuration::deleteByName('CART2ORDER_TEMP')
			OR !$this->uninstallModuleTab('AdminCart2Order')
			OR !parent::uninstall())
			return false;
		return true;
	}

	private function installModuleTab($tabClass, $tabName, $idTabParent)
	{
		@copy(_PS_MODULE_DIR_.$this->name.'/logo.gif', _PS_IMG_DIR_.'t/'.$tabClass.'.gif');
		$tab = new Tab();
		$tab->name = $tabName;
		$tab->class_name = $tabClass;
		$tab->module = $this->name;
		$tab->id_parent = $idTabParent;
		if(!$tab->save())
			return false;
		return true;
	}
	
	private function uninstallModuleTab($tabClass)
	{
		$idTab = Tab::getIdFromClassName($tabClass);
		if($idTab != 0)
		{
			$tab = new Tab($idTab);
			$tab->delete();
			@unlink(_PS_IMG_DIR_.'t/'.$tabClass.'.gif');
			return true;
		}
		return false;
	}
	
	public function getContent()
	{
		$this->_html = '<h2>'.$this->displayName.'</h2>';

		$this->checkConvert();
		$this->getInstalledPaymentModules();
		$this->displayCart2Order();
		$this->displayList();
		
		return $this->_html;
	}

	public function getInstalledPaymentModules()
	{
		$payment = new AdminPayment;
		foreach ($payment->paymentModules as $module)
		{
			if ($module->id && $module->active)
				$this->installedPaymentModules[] = $module;
		}	
	}	
	
	public function checkConvert()
	{
		$id_cart = $_POST['id_cart'];
		
		if ($id_cart) {
			$cart = new Cart($id_cart);

			$paymentMethod = $_POST['payment_displayName'];
			$message = NULL;
			$extraVars = array();
			$currency_special = NULL;
			$dont_touch_amount = false;
			$amountPaid = round($cart->getOrderTotal(),2);
			
			// add try catch here
			$this->validateOrder($id_cart, _PS_OS_PAYMENT_, $amountPaid, $paymentMethod, $message, $extraVars, $currency_special, true);		
		
			$message = ' '.$this->l('Cart #').$id_cart.' '.$this->l('was successfully converted to an order');
			$this->_html .= '<div class="conf confirm"><img src="../img/admin/ok.gif" alt="'.$this->l('Confirmation').'" />'.$this->l($message).'</div>';
		}
	}
	
	
	public function displayCart2Order()
	{

		$this->_html .= 
<<<HTML
		<div style="float: right; width: 440px; height: 140px; border: dashed 1px #666; padding: 8px; margin-left: 12px;">
			<h2>{$this->l('Make a Donation')}</h2>
			<div style="clear: both;"></div>
			<p>{$this->l('If you found this module useful and would like to make a small donation, click the Donate button below. ')}</p>
			<form name="_xclick" action="https://www.paypal.com/cgi-bin/webscr" method="post">
			<input type="hidden" name="cmd" value="_xclick">
			<input type="hidden" name="business" value="{$this->_email}">
			<input type="hidden" name="item_name" value="Donation">
			<input type="hidden" name="currency_code" value="USD">
			<input type="hidden" name="item_number" value="Donation">
			<input type="hidden" name="no_shipping" value="1">

			$ 
			<input type="text" name="amount" size="10" value="20.00" style="font-size:16px;"> <br /><br />
			<input type="image" src="http://www.paypal.com/en_US/i/btn/btn_donate_LG.gif" border="0" name="submit" alt="Make payments with PayPal - it's fast, free and secure!">
			</form>
			<div style="clear: right;"></div>
		</div>

		<b>{$this->l('This module allows you convert a customer cart into an order')}</b><br /><br />
		<div style="clear:both;">&nbsp;</div>
HTML;

	}
	
	public function displayList()
	{
		global $cookie;
		
		$result = Db::getInstance()->ExecuteS('
		SELECT cart.`id_cart`, cart.`date_upd`, c.`id_customer` AS id_customer, c.`lastname` AS customer_lastname, c.`firstname` AS customer_firstname,
		SUM(cp.`quantity`) AS nb_products,
		COUNT(cd.`id_cart`) AS nb_discounts
		FROM `'._DB_PREFIX_.'cart` cart
		LEFT JOIN `'._DB_PREFIX_.'cart_product` cp ON cart.`id_cart` = cp.`id_cart`
		LEFT JOIN `'._DB_PREFIX_.'cart_discount` cd ON cart.`id_cart` = cd.`id_cart`
		LEFT JOIN `'._DB_PREFIX_.'customer` c ON cart.`id_customer` = c.`id_customer`
		WHERE cart.`id_cart` NOT IN (SELECT `id_cart` FROM `'._DB_PREFIX_.'orders`)
		AND c.`id_customer` IS NOT NULL
		GROUP BY cart.`id_cart`, cp.`id_cart`, cd.`id_cart`
		ORDER BY cart.`date_upd` DESC');
		
		for ($i=0;$i<sizeof($result);$i++) {
			$cart = new Cart($result[$i]['id_cart']);
			$result[$i]['cart_total'] = round($cart->getOrderTotal(),2);		
		}

		$list = 
<<<HTML
			<form action="{$_SERVER['REQUEST_URI']}" method="post" style="clear: both;">
			<input type="hidden" name="payment_name" value="" />
			<input type="hidden" name="payment_displayName" value="" />		
			<input type="hidden" name="id_cart" value="" />
			<table class="table" cellpadding="0" cellspacing="0" align="center">
				<tr class="nodrag nodrop">
					<th style="width: 60px" class="center">{$this->l('CART ID')}</th>
					<th style="width: 160px">{$this->l('CUSTOMER')}</th>
					<th style="width: 100px" class="right">{$this->l('CART TOTAL')}</th>
					<th style="width: 160px" class="right">{$this->l('DATE')}</th>
					<th style="width: 100px" class="center">{$this->l('PAYMENT')}</th>
				</tr>
HTML;
		for ($i=0;$i<sizeof($result);$i++) 
		{
			if ($result[$i]['cart_total'] != 0) 
			{
				$j++;
				$class = ($j%2==0)?'alt_row':'';
				
				$actions = '';

				foreach ($this->installedPaymentModules as $module)
					if ($module->id && $module->active)
						$actions .= 
<<<HTML
<input
		type="image" 
		name="cart{$result[$i]['id_cart']}_{$module->name}" 
		src="../modules/{$module->name}/logo.gif" 
		onclick="if (confirm('{$this->l('Are you sure you want to convert cart')} #{$result[$i]['id_cart']} {$this->l('into an order from')} {$module->displayName}?')) {this.form.payment_name.value='{$module->name}';this.form.payment_displayName.value='{$module->displayName}';this.form.id_cart.value='{$result[$i]['id_cart']}';this.form.submit();}else{return false;}" /> 
HTML;

				$tokenCarts = Tools::getAdminToken('AdminCarts'.intval(Tab::getIdFromClassName('AdminCarts')).intval($cookie->id_employee));
				
				$list .= 
<<<HTML
					<tr class="{$class}">
						<td class="pointer center" onclick="document.location = '?tab=AdminCarts&id_cart={$result[$i]['id_cart']}&viewcart&token={$tokenCarts}'">{$result[$i]['id_cart']}</td>
						<td class="pointer" onclick="document.location = '?tab=AdminCarts&id_cart={$result[$i]['id_cart']}&viewcart&token={$tokenCarts}'">{$result[$i]['customer_lastname']}, {$result[$i]['customer_firstname']}</td>
						<td class="pointer right" onclick="document.location = '?tab=AdminCarts&id_cart={$result[$i]['id_cart']}&viewcart&token={$tokenCarts}'">{$result[$i]['cart_total']}</td>
						<td class="pointer right" onclick="document.location = '?tab=AdminCarts&id_cart={$result[$i]['id_cart']}&viewcart&token={$tokenCarts}'">{$result[$i]['date_upd']}</td>
						<td class="pointer center">
							{$actions}
						</td>
					</tr>
HTML;
			}
		}
		$list .= '</table></form>';

		$this->_html .= 
<<<HTML
		<form action="{$_SERVER['REQUEST_URI']}" method="post">
			<fieldset>
				<legend><img src="{$this->_path}logo.gif" alt="" title="" />{$this->l('Customer Carts')}</legend>
				<div>
				{$list}
				</div>
			</fieldset>
		</form>
HTML;
		
		return $this->_html;
		
	}	
	
	function validateOrder($id_cart, $id_order_state, $amountPaid, $paymentMethod = 'Unknown', $message = NULL, $extraVars = array(), $currency_special = NULL, $dont_touch_amount = false)
	{
		parent::validateOrder($id_cart, $id_order_state, $amountPaid, $paymentMethod, $message, $extraVars, $currency_special, true);
	}
}

?>