<?php
/**
* @version	$Id: gift_certificates_eh.php 16516 2017-01-20 14:12: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 GiftCertificateEventHandler extends kDBEventHandler {

	/**
	 * Allows to override standard permission mapping
	 *
	 * @return void
	 * @access protected
	 * @see kEventHandler::$permMapping
	 */
	protected function mapPermissions()
	{
		parent::mapPermissions();

		$permissions = Array (
			'OnItemBuild' => Array ('self' => true),
		);

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

	/**
	 * Prepare temp tables for creating new item
	 * but does not create it. Actual create is
	 * done in OnPreSaveCreated
	 *
	 * @param kEvent $event
	 * @return void
	 * @access protected
	 */
	protected function OnPreCreate(kEvent $event)
	{
		parent::OnPreCreate($event);

		/** @var kDBItem $object */
		$object = $event->getObject();

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

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

	/**
	 * Occurs before updating item
	 *
	 * @param kEvent $event
	 * @return void
	 * @access protected
	 */
	protected function OnBeforeItemUpdate(kEvent $event)
	{
		parent::OnBeforeItemUpdate($event);

		$this->itemChanged($event);
	}

	/**
	 * Occurs before creating item
	 *
	 * @param kEvent $event
	 * @return void
	 * @access protected
	 */
	protected function OnBeforeItemCreate(kEvent $event)
	{
		parent::OnBeforeItemCreate($event);

		$this->itemChanged($event);

		/** @var kDBItem $object */
		$object = $event->getObject();

		$object->SetDBField('Debit', $object->GetDBField('Amount'));
	}

	/**
	 * Occurs before item is changed
	 *
	 * @param kEvent $event
	 */
	function itemChanged($event)
	{
		/** @var kDBItem $object */
		$object = $event->getObject();

		$amount = abs($object->GetDBField('Amount'));
		$debit = abs($object->GetDBField('Debit'));

		if ( $debit > $amount ) {
			$debit = $amount;
		}

		$object->SetDBField('Amount', $amount);
		$object->SetDBField('Debit', $debit);

		if ( $object->GetDBField('SendVia') == 1 ) {
			// by postal mail
			if ( $this->Application->GetVar('email_certificate') == 0 ) {
				$object->setRequired('RecipientEmail', false);
			}

			/** @var kCountryStatesHelper $cs_helper */
			$cs_helper = $this->Application->recallObject('CountryStatesHelper');

			if ( !$cs_helper->CountryHasStates($object->GetDBField('RecipientCountry')) ) {
				$object->setRequired('RecipientState', false);
			}

			$cs_helper->CheckStateField($event, 'RecipientState', 'RecipientCountry');
		}
		else {
			$non_required_fields = Array (
				'RecipientState', 'RecipientCity', 'RecipientCountry', 'RecipientZipcode',
				'RecipientAddress1', 'RecipientFirstname', 'RecipientLastname'
			);

			$object->setRequired($non_required_fields, false);
		}
	}

	/**
	 * Print current gift certificate
	 *
	 * @param kEvent $event
	 * @return void
	 * @access protected
	 */
	protected function OnSave(kEvent $event)
	{
		parent::OnSave($event);

		if ( $event->status != kEvent::erSUCCESS || !$this->Application->GetVar('print_certificate') ) {
			return ;
		}

		/** @var kDBItem $object */
		$object = $event->getObject();

		// get object id by unique field Code
		$sql = 'SELECT ' . $object->IDField . '
				FROM ' . $this->Application->GetLiveName($object->TableName) . '
				WHERE Code = ' . $this->Conn->qstr( $object->GetDBField('Code') );
		$id = $this->Conn->GetOne($sql);

		$this->Application->StoreVar('print_certificate_id', $id);
	}

	/**
	 * Email selected gift certificate
	 *
	 * @param kEvent $event
	 */
	function OnEmailGiftCertificate($event)
	{
		$ids = $this->StoreSelectedIDs($event);
		if (!$ids) {
			return ;
		}

		/** @var kDBItem $object */
		$object = $event->getObject( Array ('skip_autoload' => true) );

		foreach ($ids as $id) {
			$object->Load($id);

			$send_params = Array (
				'from_email' => $this->Application->ConfigValue('DefaultEmailSender'),
				'from_name' => $object->GetDBField('Purchaser'),
				'message' => $object->GetDBField('Message'),
				'amount' => $object->GetField('Amount'),
				'gifcert_id' => $object->GetDBField('Code'),
			);

			$this->Application->emailAdmin('USER.GIFTCERTIFICATE', null, $send_params);

			$send_params['to_email'] = $object->GetDBField('RecipientEmail');
			$send_params['to_name'] = $object->GetDBField('Recipient');
			$this->Application->emailUser('USER.GIFTCERTIFICATE', null, $send_params);
		}

		$this->clearSelectedIDs($event);
	}

}