<?php

namespace Magento\Billdesk\Controller\Payment;

require_once(__DIR__ . '/../../vendor/autoload.php');

use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\Message;
use io\billdesk\client\hmacsha256\BillDeskJWEHS256Client;
use io\billdesk\client\hmacsha256\JWEHS256Helper;
use io\billdesk\client\hmacsha256\Config as BilldeskClientConfig;
use Magento\Billdesk\Model\Config as MagentoConfig;

use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\FirePHPHandler;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\App\ObjectManager;
use Magento\Store\Model\StoreManagerInterface;

class TestOrder  extends \Magento\Billdesk\Controller\BaseController
{
    protected $_pageFactory;
    protected $_config;
    protected $jsonResultFactory;
    protected $customerSession;
    protected $checkoutSession;
    protected $_storeManager;
    protected $_directory;

    public function __construct(
        Context $context,
        PageFactory $pageFactory,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Checkout\Model\Session $checkoutSession,
        MagentoConfig $config,
        JsonFactory $jsonResultFactory,
        StoreManagerInterface $storeManager
    ) {
        parent::__construct($context, $pageFactory, $customerSession, $checkoutSession);
        $this->_pageFactory = $pageFactory;
        $this->_config = $config;
        $this->jsonResultFactory = $jsonResultFactory;
        $this->customerSession = $customerSession;
        $this->checkoutSession = $checkoutSession;
        $this->_directory = ObjectManager::getInstance()->get(\Magento\Framework\Filesystem\DirectoryList::class);
        $this->_storeManager = $storeManager;
    }

    public function execute()
    {

        $log = new Logger('name');
        $log->pushHandler(new StreamHandler($this->_directory->getPath('log') . '/BillDesk/magento_billdesk_' . Date('Y_m_d') . '.log'));
        $log->pushProcessor(function ($record) {
            $record['extra']['user'] = get_current_user();
            return $record;
        });

        $log->info('--- Incoming Request ---');
        $log->info('GET Params: ' . json_encode($this->getRequest()->getParams()));
        $log->info('POST Params: ' . json_encode($this->getRequest()->getPost()->toArray()));
        $log->info('Raw Body: ' . $this->getRequest()->getContent());
        $log->info('------------------------');

        $signingKey = $this->getRequest()->getPost('signing_key');
        $encryptionKey = $this->getRequest()->getPost('encryption_key');
        $client_id = $this->getRequest()->getPost('client_id');
        $key_id = $this->getRequest()->getPost('key_id');
        $merchant_id = $this->getRequest()->getPost('merchant_id');
        $itemcode = $this->getRequest()->getPost('itemcode');
        $env = $this->getRequest()->getPost('env');
        
        $params = $this->getRequest()->getParams();
        $log->info('Incoming Params: ' . json_encode($params));
        $currency_value = $this->_storeManager->getStore()->getCurrentCurrency()->getCode();
        $arr = array(
            'INR' => '356', 'USD' => '840', 'EUR' => '978', 'JPY' => '392',
            'AUD' => '36', 'HKD' => '344', 'MYR' => '458', 'SGD' => '702',
            'NZD' => '554'
        );
        $currency = $arr[$currency_value];
        $ip = getenv('HTTP_CLIENT_IP') ?:
            getenv('HTTP_X_FORWARDED_FOR') ?:
            getenv('HTTP_X_FORWARDED') ?:
            getenv('HTTP_FORWARDED_FOR') ?:
            getenv('HTTP_FORWARDED') ?:
            getenv('REMOTE_ADDR');
        $ipaddress = strtok($ip, ",");
        $userAgent = $_SERVER['HTTP_USER_AGENT'];
        $returnUrl = $this->_url->getUrl('billdesk/Payment/orderprocesswithoutchildwindow');


         $returnUrl = $this->_url->getUrl('billdesk/Payment/orderprocesswithoutchildwindow');

        $baseUrl = $env === 'UAT' ? 'https://uat1.billdesk.com/u2' : 'https://api.billdesk.com';

        // ✅ Create JOSE config object
        $config = new BilldeskClientConfig();
               $config->setMerchantId($merchant_id);
               $config->setClientId($client_id);
               $config->setEncryptionKeyBase64($encryptionKey);
               $config->setSigningKeyBase64($signingKey);
               $config->setEncryptionKeyId($key_id);
               $config->setSigningKeyId("AES_DIR");


               $client = new BillDeskJWEHS256Client($config, $baseUrl);
               $client->setLogger($log);
        try {
            $request = array(
                'mercid' => $merchant_id,
                'orderid' => uniqid(),
                'amount' =>  100,
                'order_date' => date_format(new \DateTime(), DATE_W3C),
                'currency' => $currency,
                'ru' =>  $returnUrl,
                'itemcode' => $itemcode,
                'device' => array(
                    'init_channel' => 'internet',
                    'ip' => $ipaddress,
                    'user_agent' => $userAgent
                ),
            );
            $response = $client->createOrder($request);
            $results = $response->getResponse();
            $res =  json_decode(json_encode($results), true);
            $log->info('Create Test order response: ', $res);
            $resultJson = $this->jsonResultFactory->create();
            return $resultJson->setData($results);
        } catch (RequestException $ex) {
            if ($ex->hasResponse()) {
                $log->error("Server responded with error: " . Message::toString($ex->getResponse()));
                return true;
            }
        }
    }
}
