<?php
namespace Indeed\Ulp\PaymentService;
if (!defined('ABSPATH')) exit();
if (!interface_exists('Ulp_Payment_Service_Interface')) require_once ULP_PATH . 'classes/Payment_Services/Ulp_Payment_Service_Interface.php';

class TwoCheckout implements \Ulp_Payment_Service_Interface
{
  private $_metas = [];
  private $_transaction_details = [];

  public function __construct()
  {
      $this->_metas = \DbUlp::getOptionMetaGroup('2checkout');
  }

  public function setTransactionDetails($transaction_details=array())
  {
      $this->_transaction_details = $transaction_details;
      return $this;
  }

  public function pay()
  {
    $checkoutAccountNumber = get_option('ulp_2checkout_account_number');
  	$params = [
  			'sid'                => $checkoutAccountNumber,
  			'mode'               => '2CO',
  			'pay_method'         => 'CC',
  			'li_0_type'          => 'product',
  			'li_0_name'          => urlencode($this->_transaction_details['course_label']),
  			'li_0_product_id'    => $this->_transaction_details['course_id'],
  			'li_0_quantity'      => 1,
  			'li_0_price'         => urlencode($this->_transaction_details['amount']),
  			'li_0_tangible'      => 'N',
  			'li_0_description'   => json_encode([
                                  'uid'       => $this->_transaction_details['uid'],
                                  'course_id' => $this->_transaction_details['course_id'],
                                  'order_id'  => $this->_transaction_details['order_id'],
        ]),
  			'currency_code'      => $this->_transaction_details['currency'],
  			'x_receipt_link_url' => get_site_url() . "?ulp_action=2checkout",
  			'purchase_step'      => 'billing-information',
  	];

    $sandbox = get_option('ulp_2checkout_sandbox_on');
  	if ($sandbox){
  		$baseUrl = "sandbox.2checkout.com";
  		$params['demo'] = 'Y';
  	} else {
  		$baseUrl = "www.2checkout.com";
  	}

  	$paramsStr = '';
  	foreach ($params as $k=>$v){
  		if (empty($paramsStr)){
  			$paramsStr .= '?';
  		} else {
  			$paramsStr .= '&';
  		}
  		$paramsStr .= urlencode($k) . "=" . urlencode($v);
  	}
  	$redirectUrl = 'https://' . $baseUrl . '/checkout/purchase' . $paramsStr;
  	wp_redirect($redirectUrl);
  	exit();
  }

  public function ipn()
  {
    if (isset($_POST['message_type'])){
    	# we've got md5_hash
    	if (!isset($_POST['md5_hash'])) {
          exit;
    	}
      # Validate the Hash
      $hashSecretWord = get_option('ulp_2checkout_secret_word'); # Input your secret word
      $hashSid = $_POST['vendor_id'];
      $hashOrder = $_POST['sale_id'];
      $hashInvoice = $_POST['invoice_id'];
      $StringToHash = strtoupper(md5($hashOrder . $hashSid . $hashInvoice . $secretWord));
      if ($StringToHash != $_POST['md5_hash']) {
          exit;
      }
      $_POST['li_0_description'] = esc_sql( $_POST['li_0_description'] );
      $transaction_custom_data = json_decode(stripslashes($_POST['li_0_description']), true);
      $UlpOrder = new \UlpOrder();
      $unique = $UlpOrder->getUniqueByOrderId($transaction_custom_data['order_id']);

      switch ($_POST['message_type']) {
        case 'ORDER_CREATED':
        case 'RECURRING_INSTALLMENT_SUCCESS':
          # Do something when sale passes fraud review.
          $UlpOrder->modify_status($unique, 'ulp_complete');
          break;
        case 'RECURRING_INSTALLMENT_FAILED':
          # Do something when sale fails fraud review.
          $UlpOrder->modify_status($unique, 'ulp_fail');
          break;
      }
    } else if (isset($_POST['key'])){
    	$hashSecretWord = get_option('ulp_2checkout_secret_word'); # Input your secret word
    	$hashSid = get_option('ulp_2checkout_account_number'); # Input your seller ID (2Checkout account number)
    	$hashTotal = $_POST['total']; # Sale total to validate against

    	if (!empty($_POST['demo']) && $_POST['demo']=='Y'){
    		$hashOrder = 1;
    	} else {
    		$hashOrder = $_POST['order_number'];
    	}

    	$StringToHash = strtoupper(md5($hashSecretWord . $hashSid . $hashOrder . $hashTotal));
    	if ($StringToHash == $_POST['key']) {
          $transaction_custom_data = json_decode(stripslashes($_POST['li_0_description']), true);
          $UlpOrder = new \UlpOrder();
          $unique = $UlpOrder->getUniqueByOrderId($transaction_custom_data['order_id']);
          $UlpOrder->modify_status($unique, 'ulp_complete');
    	}
    }

    wp_redirect(get_home_url());
    exit;
  }

}
