<?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 Coinpayments_IpnController extends Core_Controller_Action_Standard {

  public function indexAction() {
    
    $ipnLogFile = APPLICATION_PATH . '/temporary/log/coinpayment-ipn.log';
    
    $data = file_get_contents('php://input');
    $json = json_decode($data, true);

    include_once APPLICATION_PATH . "/application/libraries/Engine/Service/Coinpayment/vendor/autoload.php";
    $params = $json ? $json : $this->_getAllParams();
		
    file_put_contents($ipnLogFile,
        date('c') . ': ' .
        print_r($params, true),
        FILE_APPEND);
        
    if(empty($params["type"]) || $params["type"] != "InvoicePaid"){
      file_put_contents($ipnLogFile,
        date('c') . ': ' .
        'invalid type'.$params["type"],
        FILE_APPEND);
        echo 'invalid type'.$params["type"];
        exit(1);
    }
    $params["order_id"] = $params["invoice"]["invoiceId"];
    $order = Engine_Api::_()->getItem('payment_order',$params['order_id']);
    $gatewayId = $order->gateway_id;
		$gateway = Engine_Api::_()->getItem($order->gateway_type ? $order->gateway_type : 'payment_gateway', $gatewayId);
		$gatewayPlugin = $gateway->getPlugin();

    if(!empty($order->gateway_transaction_id)){
       echo "already processed";
        exit(1);
    }

    // Action matches end of plugin
    if( $gatewayType &&
        substr(strtolower($gateway->plugin), - strlen($gatewayType)) == strtolower($gatewayType) ) {
      $activeGateway = $gateway;
    } else if( $gatewayId && $gatewayId == $gateway->gateway_id ) {
      $activeGateway = $gateway;
    } else if( method_exists($gatewayPlugin, 'detectIpn') &&
        $gatewayPlugin->detectIpn($params) ) {
      $activeGateway = $gateway;
    }

    // Gateway could not be detected
    if(!$activeGateway ) {
      file_put_contents($ipnLogFile,
          date('c') . ': ' .
          'Active gateway could not be detected.',
          FILE_APPEND);
      echo 'ERR';
      exit(1);
    }
     // Your keys (from config/db)
    $clientId = $gateway->config['public_key'];
    $clientSecret = $gateway->config['private_key'];
    // Init API
    $apiHelper = new ApiHelper($clientId, $clientSecret);
    $response = $apiHelper->sendApiRequest('GET', '/api/v1/currencies');
    $currencyMap = [];
    foreach ($response as $currency) {
        $currencyMap[$currency['id']] = $currency['symbol'];
    }
    $invoice = $params["invoice"];
    $params["currency1"] = $currencyMap[$invoice["amount"]["currency"]["id"]]; 
    $params["amount1"] = round($invoice["amount"]["subtotal"]/100,2); 
    $params["txn_id"] = $invoice["id"];
    // Process IPN
    try {
      $gatewayPlugin->onTransactionIpn($order,$params);
    } catch( Exception $e ) {
      // IPN validation failed
      file_put_contents($ipnLogFile,
          date('c') . ': ' .
          'IPN processing failed: ' . $e->__toString(),
          FILE_APPEND);
      echo 'ERR';
      exit(1);
    }
    // Exit
    echo 'OK';
    exit(0);
  }
}
