<?php
/**
* @version	$Id: coupons_event_handler.php 12739 2009-10-20 19:38:22Z alex $
* @package	In-Commerce
* @copyright	Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license	Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/

defined('FULL_PATH') or die('restricted access!');

class CouponsEventHandler extends kDBEventHandler {

	/**
	 * Allows to override standart permission mapping
	 *
	 */
	function mapPermissions()
	{
		parent::mapPermissions();
		$permissions = Array(
			'OnItemBuild' => Array('self' => true),
		);

		$this->permMapping = array_merge($this->permMapping, $permissions);
	}


	function OnApplyClone(&$event)
	{
		$item = &$event->getObject();
		$clone_count = $this->Application->GetVar('clone_items_count');
		$table = $this->Application->getUnitOption($event->Prefix, 'TableName');
		if ($clone_count && $clone_count>0){
			$this->Application->StoreVar('CoupLastCloneCount', $clone_count);
			for ($i=0; $i<$clone_count; $i++)			{
				$this->SetNewCode($item);

				$item->SetField('Expiration_date', $this->Application->GetVar('clone_exp_date'));
				$item->SetField('Expiration_time', $this->Application->GetVar('clone_exp_time'));
				$item->NameCopy();
				$validated = $item->Create();


			}
		}

		if ($validated){
			$this->finalizePopup($event);
		}else{
			$event->redirect = false;
		}
	}

	function SetNewCode(&$item)
	{
		do{
			$new_code = $this->RandomCouponCode(10);
			$exists = $this->Conn->GetOne('SELECT COUNT(*) FROM '.TABLE_PREFIX.'ProductsCoupons WHERE Code='.$this->Conn->qstr($new_code));
			if ($exists){
				$new_code = false;
			}
		} while (!$new_code);

		$item->SetDBField('Code', $new_code);
	}

	function RandomCouponCode($size)
	{
		$rand_code = "";
		for ($i=0; $i<10; $i++){
			$is_letter = rand(0,1);
			if ($is_letter){
				$rand_char = chr(rand(65,90));
			}else{
				$rand_char = rand(0,9);
			}
			$rand_code .= $rand_char;
		}
		return $rand_code;
	}

	/**
	 * Enter description here...
	 *
	 * @param kEvent $event
	 */
	function OnApplyCoupon(&$event)
	{
		$code = $this->Application->GetVar('coupon_code');
		if ($code == '') {
			return ;
		}

		$object =& $event->getObject(Array('skip_autoload' => true));
		$object->Load($code, 'Code');

		if (!$object->isLoaded()) {
			$event->status = erFAIL;
			$this->Application->SetVar('set_checkout_error', 4);
			$event->redirect = false; // check!!!
			return ;
		}
//		$object->IDField = $this->Application->getUnitOption($event->Prefix, 'IDField');
//		$object->ID = $object->GetDBField( $object->IDField );

		$expire_date = $object->GetDBField('Expiration');
		$number_of_use = $object->GetDBField('NumberOfUses');
		if(	$object->GetDBField('Status') != 1 || ($expire_date && $expire_date < adodb_mktime()) ||
			(isset($number_of_use) && $number_of_use <= 0))
		{
			$event->status = erFAIL;
			$this->Application->SetVar('set_checkout_error', 5);
			$event->redirect->false;
			return ;
		}

		$last_used = adodb_mktime();
		$object->SetDBField('LastUsedBy', $this->Application->RecallVar('user_id'));
		$object->SetDBField('LastUsedOn_date', $last_used);
		$object->SetDBField('LastUsedOn_time', $last_used);
		if(isset($number_of_use))
		{
			$object->SetDBField('NumberOfUses', $number_of_use - 1);
			if($number_of_use == 1)
			{
				$object->SetDBField('Status', 2);
			}
		}
		$object->Update();

		$this->Application->setUnitOption('ord', 'AutoLoad', true);
		$order =& $this->Application->recallObject('ord');
		$order->SetDBField('CouponId', $object->GetDBField('CouponId'));
		$order->Update();

		$this->Application->SetVar('set_checkout_error', 10);
	}

	/**
	 * Enter description here...
	 *
	 * @param kEvent $event
	 */
	function OnPreCreate(&$event){

		parent::OnPreCreate($event);

		$object = &$event->getObject();
		$exp_date = adodb_mktime();

		$default_duration = $this->Application->ConfigValue('Comm_DefaultCouponDuration');

		if ($default_duration && $default_duration>0){
			$exp_date += (int)$default_duration*86400;
		}
		$object->SetDBField('Expiration_date', $exp_date);
	}

	function OnBeforeItemUpdate(&$event)
	{
		$object =& $event->getObject();
		$object->SetDBField( 'Amount', abs($object->GetDBField('Amount')) );
	}

	function OnBeforeItemCreate(&$event)
	{
		$this->OnBeforeItemUpdate($event);
	}
}