<?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_Clickbank extends XenCentral_PaymentApi_Method
{
    protected $_responseRequired = true;

    protected $_validSettings = array(
        'security_key' => array(
            'title' => 'Security Key',
            'required' => 1
        ),
        'productId' => array(
            'title' => 'Product ID',
            'required' => 1
        ),
        'vendorId' => array(
            'title' => 'Vendor ID',
            'required' => 1
        )
    );

    protected $_validFields = array();

    protected function _generateTransactionHash()
    {
        return md5(serialize($this->_settings) . rand(1, time()));
    }

    protected function _getDebugFormURL()
    {
        return "http://{$this->_settings[productId]}.{{$this->_settings[vendorId]}}.pay.clickbank.net";
    }

    protected function _getLiveFormURL()
    {
        return "http://{$this->_settings[productId]}.{$this->_settings[vendorId]}.pay.clickbank.net";
    }

    protected function _getFormMethod()
    {
        return 'GET';
    }

    protected function _getFormHiddenFields()
    {
        $this->_info['transactionhash'] = $this->_additionalInfo['transactionhash'];

        return XenCentral_Framework_Helper_Html::constructHiddenCode($this->_info);
    }

    public function getMethodIdentifier($formatted = false)
    {
        if ($formatted) {
            return 'ClickBank';
        }

        return 'clickbank';
    }

    protected function _getTransactionHashFromRequest()
    {
        return $this->_validatePaymentHash($_REQUEST['transactionhash']);
    }

    protected function _validateRequest()
    {
        $key = $this->_settings['security_key']['value'];
        $rcpt = $_REQUEST['cbreceipt'];
        $time = $_REQUEST['time'];
        $item = $_REQUEST['item'];
        $cbpop = $_REQUEST['cbpop'];

        $xxpop = sha1("$key|$rcpt|$time|$item");
        $xxpop = strtoupper(substr($xxpop, 0, 8));

        if ($cbpop == $xxpop) return 1;

        $this->_setError('authentication_error', "Could not authenticate the request.");
        return false;
    }

    public function sendSuccessResponse()
    {

    }

    protected function _setTransactionIdFromRequest()
    {
        return $this->setTransactionId($_REQUEST['cbreceipt']);
    }

    protected function _setTypeFromRequest()
    {
        $this->setType('payment');
    }
}