<?php

/******************************************************************************
 *  
 *  PROJECT: Flynax Classifieds Software
 *  VERSION: 4.5.2
 *  LICENSE: FL4HLD2A8696 - http://www.flynax.com/license-agreement.html
 *  PRODUCT: Real Estate Classifieds
 *  DOMAIN: savingrack.com
 *  FILE: RL2CO.CLASS.PHP
 *  
 *  The software is a commercial product delivered under single, non-exclusive,
 *  non-transferable license for one domain or IP address. Therefore distribution,
 *  sale or transfer of the file in whole or in part without permission of Flynax
 *  respective owners is considered to be illegal and breach of Flynax License End
 *  User Agreement.
 *  
 *  You are not allowed to remove this information from the file without permission
 *  of Flynax respective owners.
 *  
 *  Flynax Classifieds Software 2017 | All copyrights reserved.
 *  
 *  http://www.flynax.com/
 ******************************************************************************/

class rl2co extends rlGateway
{
	/**
	* @var $api_host
	*/
    protected $api_host;

    public function __construct()
    {
        parent::__construct();
        $this->setTestMode($GLOBALS['config']['2co_testmode'] ? true : false);

        $mode = $this->isTestMode() ? 'sandbox' : 'www';
        $this->api_host = 'https://'.$mode.'.2checkout.com/checkout/purchase';
    }
    
    public function call()
    {
        $this->beforeProcess();
        $this->buildPage($this->buildForm());    
    }
    
    public function callBack()
    {
        return $this->afterProcess();    
    }
    
    protected function beforeProcess()
    {
        $this->setOption('sid', $GLOBALS['config']['2co_id']);
        $this->setOption('cart_order_id', $this->rlPayment->getTransactionID());
        $this->setOption('item_number', $this->rlPayment->buildItemData());
        $this->setOption('product_id', $this->rlPayment->getOption('item_id'));
        $this->setOption('total', $this->rlPayment->getOption('total'));
        $this->setOption('quantity', '1');
        $this->setOption('credit_card_processed', 'Y');
        $this->setOption('x_receipt_link_url', $this->rlPayment->getNotifyURL() . '?gateway=2co');
        $this->setOption('c_name', $this->rlPayment->getOption('item_name'));
        $this->setOption('c_description', $this->rlPayment->getOption('item_name'));
        
        if ($this->isTestMode()) {
            $this->setOption('demo', 'Y');
        }
    }
    
    protected function afterProcess()
    {
        if (strtolower($_SERVER['REQUEST_METHOD']) == 'post' || strtolower($_SERVER['REQUEST_METHOD']) == 'get') {
            $errors = false;

            if ($_REQUEST['item_number']) {
                $total = (float)$_REQUEST['total'];
                $txn_gateway = $GLOBALS['rlValid']->xSql($_REQUEST['order_number']);
				$hash = strtoupper(md5($GLOBALS['config']['2co_secret_word'] . $GLOBALS['config']['2co_id'] . ($this->isTestMode() || $_REQUEST['demo'] == 'Y' ? '1' : $_REQUEST['order_number']) . $_REQUEST['total']));

                $items = $this->explodeItems($_REQUEST['item_number']); 

                $crypted_sum = $items[3];
                $callback_class = $items[4];
                $callback_method = $items[5];
                $cancel_url = $items[6];
                $success_url = $items[7];
                $lang_code = $items[8];
                $callback_plugin = $items[9] ? $items[9] : false;

                $response = array(
                        'plan_id' => $items[0],
                        'item_id' => $items[1],
                        'account_id' => $items[2],
                        'total' => $total,
                        'txn_id' => (int)$items[10],
                        'txn_gateway' => $txn_gateway,
                        'params' => $items[12]
                    );

                define('RL_LANG_CODE', $lang_code);
                define('RL_DATE_FORMAT', $this->reefless->getOne('Date_format', "`Code` = '{$lang_code}'", 'languages'));

                $seo_base = RL_URL_HOME;
                $seo_base .= $lang_code == $config['lang'] ? '' : $lang_code;

                $lang = $this->rlLang->getLangBySide('frontEnd', RL_LANG_CODE);
                $GLOBALS['lang'] = $lang;

                if (trim($_REQUEST['key']) != $hash) {
					$errors = true;
					$this->rlDebug->logger("2checkout: Hash code invalid [{$_REQUEST['key']} != {$hash}]");	
                }

                if (empty($items[1]) || empty($total)) {
                    $errors = true;
                }

                if (!$errors) {
                	$this->rlPayment->complete($response, $callback_class, $callback_method, $callback_plugin);
                    $this->reefless->redirect(null, $success_url);
                } else {
                    $this->reefless->redirect(null, $cancel_url);
                }
            } else {
				$cancel_url = SEO_BASE;
				$cancel_url .= $GLOBALS['config']['mod_rewrite'] ? $GLOBALS['pages']['payment'] .'/'. rlPayment::FAIL_URL .'.html' : '?page='. $GLOBALS['pages']['payment'] .'&rlVareables='. rlPayment::FAIL_URL;
				$this->reefless->redirect(null, $cancel_url);
			}
        }
    }

    protected function buildForm()
    {
        $form = '<form name="payment_form" action="'. $this->api_host .'" method="post">';

        foreach ($this->request_data as $key => $value) {
            $form .= '<input type="hidden" name="' . $key . '" value="' . $value . '" />';
        }
        
        $form .= '</form>';

        echo $form;
    }
	
	/**
	* check if 2co configured
	* 
	* @return boolean
	*/
	public static function isConfigured()
	{
		if ($GLOBALS['config']['2co_id']) {
			return true;
		}
		return false;
	}
}