<?php
/**
  * Ahead WebSoft Technologies Pvt Ltd.
  * @copyright  Copyright 2006-2026 Ahead WebSoft Technologies Pvt Ltd.
  * @license    https://www.socialengine.com/policies
*/


include_once APPLICATION_PATH . "/application/libraries/Engine/Service/Coinpayment/vendor/autoload.php";
require_once APPLICATION_PATH . '/application/libraries/Engine/Service/Coinpayment/src/Helpers/ApiHelper.php';
require_once APPLICATION_PATH . '/application/libraries/Engine/Service/Coinpayment/src/Helpers/QrCodeHelper.php';

use CoinPaymentsApiExamples\Helpers\ApiHelper;
use CoinPaymentsApiExamples\Helpers\QrCodeHelper;
use Endroid\QrCode\Color\Color;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Writer\PngWriter;
class Payment_Plugin_Gateway_Verification_Coinpayment extends Engine_Payment_Plugin_Abstract
{

  protected $_gatewayInfo;
  protected $_gateway;
  
  // General

  /**
   * Constructor
   */
  public function __construct(Zend_Db_Table_Row_Abstract $gatewayInfo)
  {
    $this->_gatewayInfo = $gatewayInfo;
  }

  /**
   * Get the service API
   *
   * @return Engine_Service_PayPal
   */
  public function getService()
  {
    return $this->getGateway()->getService();
  }

  /**
   * Get the gateway object
   *
   * @return Engine_Payment_Gateway
   */
  public function getGateway()
  {
    // var_dump((array) $this->_gatewayInfo);die;
    if (null === $this->_gateway) {
      $class = 'Engine_Payment_Gateway_Coinpayment';
      Engine_Loader::loadClass($class);
      $gateway = new $class(array(
        'config' => (array) $this->_gatewayInfo->config,
        'testMode' => $this->_gatewayInfo->test_mode,
        'currency' => Engine_Api::_()->getApi('settings', 'core')->getSetting('payment.currency', 'USD'),
      ));
      if (!($gateway instanceof Engine_Payment_Gateway)) {
        throw new Engine_Exception('Plugin class not instance of Engine_Payment_Gateway');
      }
      $this->_gateway = $gateway;
    }

    return $this->_gateway;
  }

  // Actions
  /**
   * Create a transaction object from specified parameters
   *
   * @return Engine_Payment_Transaction
   */
  public function createTransaction(array $params)
  {
    $transaction = new Engine_Payment_Transaction($params);
    $transaction->process($this->getGateway());
    return $transaction;
  }

  /**
   * Create an ipn object from specified parameters
   *
   * @return Engine_Payment_Ipn
   */
  public function createIpn(array $params)
  {
    $ipn = new Engine_Payment_Ipn($params);
    $ipn->process($this->getGateway());
    return $ipn;
  }

  // SEv4 Specific

  /**
   * Create a transaction for a subscription
   *
   * @param User_Model_User $user
   * @param Zend_Db_Table_Row_Abstract $subscription
   * @param Zend_Db_Table_Row_Abstract $package
   * @param array $params
   * @return Engine_Payment_Gateway_Transaction
   */
  public function createSubscriptionTransaction(User_Model_User $user, Zend_Db_Table_Row_Abstract $subscription, Payment_Model_Package $package, array $params = array()) {}

  /**
   * Create a transaction for a subscription
   *
   * @param User_Model_User $user
   * @param Zend_Db_Table_Row_Abstract $subscription
   * @param Zend_Db_Table_Row_Abstract $package
   * @param array $params
   * @return Engine_Payment_Gateway_Transaction
   */
  public function createVerificationTransaction(User_Model_User $user, array $params = array())
  {

    $recurrence = $params['recurrence'];
    $price = $params['price'];

    // Process description
    $desc = Engine_Api::_()->payment()->getPackageDescription(json_decode($recurrence), $price);
    if (strlen($desc) > 127) {
      $desc = substr($desc, 0, 124) . '...';
    } else if (!$desc || strlen($desc) <= 0) {
      $desc = 'N/A';
    }
    if (function_exists('iconv') && strlen($desc) != iconv_strlen($desc)) {
      // PayPal requires that DESC be single-byte characters
      $desc = @iconv("UTF-8", "ISO-8859-1//TRANSLIT", $desc);
    }

    $currentCurrency = Engine_Api::_()->payment()->getCurrentCurrency();
    $defaultCurrency = Engine_Api::_()->payment()->defaultCurrency();
    $currencyChangeRate = 1;
    if ($currentCurrency != $defaultCurrency) {
      $currencyData = Engine_Api::_()->getDbTable('currencies', 'payment')->getCurrency($currentCurrency);
      $currencyChangeRate = $currencyData->change_rate;
    }
    $price = $amount = @round(($price * $currencyChangeRate), 2);

    // This is a one-time fee
    if (Engine_Api::_()->payment()->isOneTime(json_decode($recurrence))) {

      $cps_api = new CoinpaymentsAPI($this->_gatewayInfo->config['private_key'], $this->_gatewayInfo->config['public_key'], 'json');

      $buyer_email = $user->email;
      $address = "";
      $item_name = $desc;
      $item_number = "";
      $custom = '';
      $invoice = '';
      $currency2 = $params["currency"];
      $buyer_name = $user->getTitle();

      $view = Zend_Registry::isRegistered('Zend_View') ? Zend_Registry::get('Zend_View') : null;

      $ipn_url = 'https://' . $_SERVER['HTTP_HOST'] . Zend_Controller_Front::getInstance()->getRouter()->assemble(array('module' => 'coinpayments', 'controller' => 'ipn', 'action' => 'index', 'order_id' => $params["order_id"], 'subscription_id' => $params['subscription_id']), 'default', true);

      $success_url = 'https://' . $_SERVER['HTTP_HOST'] . Zend_Controller_Front::getInstance()->getRouter()->assemble(array(), 'default', true);

      $cancel_url = 'https://' . $_SERVER['HTTP_HOST'] . Zend_Controller_Front::getInstance()->getRouter()->assemble(array(), 'default', true);

      // Your keys (from config/db)
      $clientId = $this->_gatewayInfo->config['public_key'];
      $clientSecret = $this->_gatewayInfo->config['private_key'];

      // Init API
      $apiHelper = new ApiHelper($clientId, $clientSecret);
      $payload = [
        "invoiceId" => $params["order_id"],
        "ipn_url" => $ipn_url,
        "success_url" => $success_url,
        "cancel_url" => $cancel_url,
        "items" => [
          [
            "name" => $item_name,
            "quantity" => [
              "value" => 1,
              "type" => 2
            ],
            "originalAmount" => (string) $amount,
            "amount" => (string) $amount
          ]
        ],
        "amount" => [
          "total" => (string) $amount
        ],
        "currency" => $currentCurrency,
        "payment" => [
          "refundEmail" => $buyer_email
        ]
      ];


      try {
        $transaction_response = $apiHelper->sendApiRequest(
          'POST',
          '/api/v2/merchant/invoices',
          $payload
        );
      } catch (Exception $e) {
        throw $e;
      }
      if (!empty($transaction_response['invoices']) && !empty($transaction_response['invoices'][0]) &&  !empty($transaction_response['invoices'][0]['id'])) {
        // Success!
      } else {

        // Something went wrong!
        $errors = "";
        if (!empty($transaction_response['errors'])) {
          foreach ($transaction_response['errors'] as $error) {
            $errors .= "Error: " . $error[0] . "\n";
          }
        }
        throw new Engine_Payment_Plugin_Exception($errors);
      }

      return $transaction_response;
    }
  }

  /**
   * Process return of subscription transaction
   *
   * @param Payment_Model_Order $order
   * @param array $params
   */
  public function onSubscriptionTransactionReturn(Payment_Model_Order $order, array $params = array()) {}

  /**
   * Process return of subscription transaction
   *
   * @param Payment_Model_Order $order
   * @param array $params
   */
  public function onVerificationTransactionReturn(Payment_Model_Order $order, array $params = array()) {}

  /**
   * Process ipn of subscription transaction
   *
   * @param Payment_Model_Order $order
   * @param Engine_Payment_Ipn $ipn
   */
  public function onSubscriptionTransactionIpn(
    Payment_Model_Order $order,
    Engine_Payment_Ipn $ipn
  ) {}


  /**
   * Cancel a subscription (i.e. disable the recurring payment profile)
   *
   * @params $transactionId
   * @return Engine_Payment_Plugin_Abstract
   */
  public function cancelSubscription($transactionId, $note = null)
  {
    return $this;
  }

  /**
   * Generate href to a page detailing the order
   *
   * @param string $transactionId
   * @return string
   */
  public function getOrderDetailLink($orderId)
  {
    return 'https://www.coinpayments.net/index.php?cmd=acct_pmt_details&id=' . $orderId;
  }

  /**
   * Generate href to a page detailing the transaction
   *
   * @param string $transactionId
   * @return string
   */
  public function getTransactionDetailLink($transactionId)
  {

    return 'https://www.coinpayments.net/index.php?cmd=acct_pmt_details&id=' . $transactionId;
  }

  /**
   * Get raw data about an order or recurring payment profile
   *
   * @param string $orderId
   * @return array
   */
  public function getOrderDetails($orderId)
  {
    try {
      return $this->getService()->detailRecurringPaymentsProfile($orderId);
    } catch (Exception $e) {
      echo $e;
    }

    try {
      return $this->getTransactionDetails($orderId);
    } catch (Exception $e) {
      echo $e;
    }

    return false;
  }

  /**
   * Get raw data about a transaction
   *
   * @param $transactionId
   * @return array
   */
  public function getTransactionDetails($transactionId)
  {
    return $this->getService()->detailTransaction($transactionId);
  }
  
  // Forms

  /**
   * Get the admin form for editing the gateway info
   *
   * @return Engine_Form
   */
  public function getAdminGatewayForm()
  {
    return new Coinpayments_Form_Admin_Gateway_Coinpayment();
  }

  public function processAdminGatewayForm(array $values)
  {
    return $values;
  }
  
  // IPN
  /**
   * Process an IPN
   *
   * @param Engine_Payment_Ipn $ipn
   * @return Engine_Payment_Plugin_Abstract
   */
  public function onIpn(Engine_Payment_Ipn $ipn) {}
  
  
  // IPN
  /**
   * Process an IPN
   *
   * @param Payment_Model_Order $order
   * @return Engine_Payment_Plugin_Abstract
   */
  public function onTransactionIpn(Payment_Model_Order $order,  $rawData)
  {

    if ($order->gateway_id != $this->_gatewayInfo->gateway_id) {
      throw new Engine_Payment_Plugin_Exception('Gateways do not match');
    }

    // Get related info
    $user = $order->getUser();
    $subscription = Engine_Api::_()->getItem('payment_subscription', $rawData['subscription_id']);
    $package = $order->getSource();

    $recurrence = $package->recurrence;
    $recurrence_type = $package->recurrence_type;
    $price = $package->price;

    $current_currency = strtoupper($rawData['currency1']);
    $currencyChangeRate = 1;
    $defaultCurrency = Engine_Api::_()->payment()->defaultCurrency();
    if ($current_currency != $defaultCurrency) {
      $currencyData = Engine_Api::_()->getDbTable('currencies', 'payment')->getCurrency($current_currency);
      $currencyChangeRate = $currencyData->change_rate;
    }
    $price = @round(($rawData["amount1"] / $currencyChangeRate), 2);

    // description
    $desc = $package->getPackageDescription();

    // expiration_date
    $expiration_date = date('Y-m-d H:i:s', $package->getExpirationDate());
    if ($expiration_date == '1970-01-01 00:00:00') {
      $expiration_date = '2099-12-30 00:00:00';
    }

    //Check subscription state
    $paymentStatus = 'okay';
    $orderStatus = 'complete';

    $transactionsTable = Engine_Api::_()->getDbtable('transactions', 'payment');

    // One-time
    if (Engine_Api::_()->payment()->isOneTime($recurrence)) {

      // Update order with profile info and complete status?
      $order->state = $orderStatus;
      $order->gateway_transaction_id = $rawData['txn_id'];
      $order->save();

      $params['gateway_transaction_id'] = $rawData['txn_id'];
      $params['state'] = $paymentStatus;
      $params['type'] = "payment verification";
      $params['expiration_date'] = $expiration_date;
      $params['currency'] = Engine_Api::_()->payment()->defaultCurrency(); //this is default currency set by admin
      $params['amount'] = $price; // @todo use this or gross (-fee)?
      $params['change_rate'] = $currencyChangeRate; //currency change rate according to default currency
      $params['current_currency'] = strtoupper($rawData["currency1"]); //currency which is user paid

      // Insert transaction
      $transaction_id = $transactionsTable->createTransaction($order, $subscription, $user, $params);
      $transaction = Engine_Api::_()->getItem('payment_transaction', $transaction_id);

      // Get benefit setting
      $giveBenefit = Engine_Api::_()->getDbtable('transactions', 'payment')
        ->getBenefitStatus($user);

      // Check payment status
      if (
        $paymentStatus == 'okay' ||
        ($paymentStatus == 'pending' && $giveBenefit)
      ) {

        // Payment success
        $package->onPaymentSuccess($transaction_id);

        $transaction->subscription_id = $subscription->getIdentity();
        $transaction->save();

        // Update subscription info
        $subscription->status = 'active';
        $subscription->active = 1;
        $subscription->expiration_date = $expiration_date;
        $subscription->gateway_profile_id = $params['gateway_transaction_id'];
        $subscription->order_id = $order->order_id;
        $subscription->resource_type = $order->source_type;
        $subscription->resource_id = $order->source_id;
        $subscription->save();

        // send notification
        //if( $subscription->didStatusChange() ) {
        Engine_Api::_()->getApi('mail', 'core')->sendSystem($user, 'payment_verification_active', array(
          'subscription_terms' => $desc,
          'object_link' => 'https://' . $_SERVER['HTTP_HOST'] . Zend_Controller_Front::getInstance()->getRouter()->assemble(array("module" => 'payment', 'controller' => "settings", "action" => "verification"), 'default', true),
        ));
        //}
        return 'active';
      } else if ($paymentStatus == 'pending') {

        // Payment pending
        $package->onPaymentPending($transaction);

        // send notification
        //if( $subscription->didStatusChange() ) {
        Engine_Api::_()->getApi('mail', 'core')->sendSystem($user, 'payment_verification_pending', array(
          'subscription_terms' => $desc,
          'object_link' => 'https://' . $_SERVER['HTTP_HOST'] . Zend_Controller_Front::getInstance()->getRouter()->assemble(array("module" => 'payment', 'controller' => "settings", "action" => "verification"), 'default', true),
        ));
        //}

        return 'pending';
      }
    }
  }

  function setConfig($params) {}

  function test() {}
}
