<?php
/**
* @package XenCentral Framework
* @author Skydevelop EU
* @copyright Drnoyan & Nalyan LDA, Portugal, EU
* @license http://www.dnf.pt/eula.html
* @link http://www.skydevelop.com
* @version 1.4.1
* @revision 125
*/

class XenCentral_PaymentApi_Methods_Manual extends XenCentral_PaymentApi_Method
{
    protected $_responseRequired = true;

	protected $_validSettings=array (
        'endpoint_url' => array(
            'title' => 'Endpoint URL for manual payment form',
            'required' => 1,
            'field' => 0
        ),
            'instructions_url' => array(
                    'title' => 'URL for manual payment instructions page',
                    'required' => 1,
                    'field' => 0
            ),
            'instructions' => array(
                    'title' => 'Instructions to show to user for manual payment',
                    'required' => 1,
                    'field' => 0
            ),

    );
	
	protected $_validFields=array (
			'currency_code' => array (
					'title' => 'Currency', 
					'required' => 0, 
					'default' => 'USD' 
			), 
			'amount' => array (
					'title' => 'Amount', 
					'required' => 1 
			),
        'item_name' => array(
            'title' => 'Item Name',
            'required' => 1
        ),
        'item_number' => array(
            'title' => 'Item Name',
            'required' => 1
        ),
        'return' => array (
					'title' => 'Return URL', 
					'required' => 0 
			)
	);
	
	protected function _generateTransactionHash()
	{
		return md5($this->_info['item_name'] . $this->_info['item_number'] . $this->_info['amount'] . rand(1, time()));
	}
	
	protected function _validateSettings()
	{
        if(!$this->_settings['endpoint_url']) {
            $this->_setError('endpoint_url', "Please set local endpoint URL.");
            return false;
        }
		return parent::_validateSettings();
	}
	
	protected function _validateInfo()
	{
		if(!$this->_info['amount'])
		{
			$this->_setError('amount', "Please specfiy payment amount");
			return false;
		}
		
		if(!$this->_info['currency_code'])
		{
			$this->_setError('currency_code', "Please specify currency code");
			return false;
		}
		
		if(!$this->_info['item_name'])
		{
			$this->_setError('item_name', "Please specify item name");
			return false;
		}
		
		return parent::_validateInfo();
	}
	
	protected function _getDebugFormURL()
	{
		return $this->getSetting('instructions_url');
	}
	
	protected function _getLiveFormURL()
	{
        return $this->getSetting('instructions_url');
	}
	
	protected function _getFormMethod()
	{
		return 'POST';
	}
	
	protected function _getFormHiddenFields()
	{
		$this->_info['custom']=$this->_additionalInfo['transactionhash'];
		$this->_info['txn_id']=XenForo_Model::create('XenCentral_Framework_Model_PaymentApi')->getNewManualTransactionId();

        return XenCentral_Framework_Helper_Html::constructHiddenCode($this->_info);
	}
	
	public function getMethodIdentifier($formatted=false)
	{
		if($formatted)
		{
			return 'Manual';
		}
		
		return 'manual';
	}
	
	protected function _getTransactionHashFromRequest()
	{
		return $this->_validatePaymentHash($this->getApi()->getRequest()->getParam('custom'));
	}
	
	protected function _validateRequest()
	{
        /*if(!XenForo_Visitor::getInstance()->hasAdminPermission('xcfw_can_manage_payments')) {
            throw new XenForo_Exception('Security error.');
        }*/

		return true;
	}
	
	public function sendSuccessResponse()
	{
		if(headers_sent($file, $line))
		{
			return;
		}

		$status_code='200 OK';
		
		// Paypal likes to get told its message has been received
		if(defined('SAPI_NAME') && (SAPI_NAME == 'cgi' or SAPI_NAME == 'cgi-fcgi'))
		{
			header('Status: ' . $status_code);
		}
		else
		{
			header('HTTP/1.1 ' . $status_code);
		}
	}
	
	public function sendFailResponse()
	{
	    if(headers_sent($file, $line))
		{
			return false;
		}
		
		if($this->getDebugMode())
		{
			return $this->sendSuccessResponse();
		}

		$status_code='503 Service Unavailable';
		// Paypal likes to get told its message has been received
		if(defined('SAPI_NAME') && (SAPI_NAME == 'cgi' or SAPI_NAME == 'cgi-fcgi'))
		{
			header('Status: ' . $status_code);
		}
		else
		{
			header('HTTP/1.1 ' . $status_code);
		}

        return true;
	}
	
	protected function _setTransactionIdFromRequest()
	{
		return $this->setTransactionId($this->getApi()->getRequest()->getParam('txn_id'));
	}
	
	protected function _setTypeFromRequest()
	{
        $this->setType('payment');
	}

    /**
     * Endpoint submit URL
     * @Required
     */
    function setSettingEndpointUrl($value)
    {
        $this->setSetting('endpoint_url', $value);
    }

    function setSettingInstructionsUrl($value)
    {
        $this->setSetting('instructions_url', $value);
    }

    function setSettingInstructions($value)
    {
        $this->setSetting('instructions', $value);
    }

    /**
     * Currency
     * @default USD
     */
    function setFieldCurrencyCode($value)
    {
        $this->setField('currency_code', $value);
    }

    /**
     * Amount
     * @Required
     */
    function setFieldAmount($value)
    {
        $this->setField('amount', $value);
    }

    /**
     * Item Name
     * @Required
     */
    function setFieldItemName($value)
    {
        $this->setField('item_name', $value);
    }

    /**
     * Item Number
     */
    function setFieldItemNumber($value)
    {
        $this->setField('item_number', $value);
    }

    /**
     * Item Number
     */
    function setFieldReturn($value)
    {
        $this->setField('return', $value);
    }
}