<?php

/**
 * Copyright © 2024 Mimocodes. All rights reserved.
 */

namespace Aman\AmanAccept\Block\Checkout;

use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\View\Element\Template\Context;
use Magento\Checkout\Model\Session;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\OrderFactory;
use Aman\AmanAccept\Logger\Logger;
use Magento\Framework\App\Response\Http;
use Magento\Sales\Model\Order\Payment\Transaction\Builder as TransactionBuilder;

use Aman\AmanAccept\Model\Adminhtml\Source\Environment;
use Aman\AmanAccept\Gateway\Config\AmanExpress\Config;
use Aman\AmanAccept\Model\Ui\AmanExpress\ConfigProvider;

/**
 * Billing agreement information on Order success page
 */
class Success extends \Magento\Framework\View\Element\Template
{

    /**
     * @var \Magento\Sales\Model\Order $order
     */
    protected $order;

    /**
     * @var \Magento\Checkout\Model\Session
     */
    protected $checkoutSession;

    /**
     * @var \Magento\Checkout\Model\OrderFactory
     */
    protected $orderFactory;

    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $storeManager;

    protected $transID;

    protected $urlBuilder;
    private $logger;
    protected $response;
    protected $amanExpressConfig;
    protected $messageManager;
    protected $transactionBuilder;
    protected $inbox;
    private $localeResolver;

    protected $adapterFactory;

    public function __construct(Context                    $context,
                                \Aman\AmanAccept\Gateway\Config\AmanExpress\Config $amanExpressConfig,
                                Session                                            $checkoutSession,
                                OrderFactory                                       $orderFactory,
                                Logger                                             $logger,
                                Http                                               $response,
                                TransactionBuilder                                 $tb,
                                \Aman\AmanAccept\Model\Adapter\AmanAdapterFactory  $adapterFactory,
                                \Magento\AdminNotification\Model\Inbox             $inbox,
                                \Magento\Framework\Pricing\Helper\Data             $priceHelper,
                                \Magento\Store\Model\StoreManagerInterface         $storeManager,
                                \Magento\Framework\Locale\ResolverInterface        $localeResolver
    ) {
        $this->amanExpressConfig = $amanExpressConfig;
        $this->checkoutSession = $checkoutSession;
        $this->orderFactory = $orderFactory;
        $this->response = $response;
        $this->transactionBuilder = $tb;
        $this->logger = $logger;
        $this->inbox = $inbox;
        $this->localeResolver = $localeResolver;

        $this->urlBuilder = \Magento\Framework\App\ObjectManager::getInstance()
            ->get('Magento\Framework\UrlInterface');

        $this->priceHelper = $priceHelper;
        $this->storeManager = $storeManager;

        $this->adapterFactory = $adapterFactory;

        parent::__construct($context);
    }

    protected function _prepareLayout()
    {
        $this->logger->info("_prepareLayout getTestData() ". $this->checkoutSession->getTestData() );

        if($this->renderAmanExpress(false) == 1)
        {
            $order = $this->getOrder();

            if($order == null)
                return;

            $method_data = array();

            if ($order)
            {
                $billing = $order->getBillingAddress();
                # check if mobile no to be updated.
                $updateTelephone = $this->getRequest()->getParam('telephone');
                if($updateTelephone)
                {
                    $billing->setTelephone($updateTelephone)->save();

                }
                $payment = $order->getPayment();

                $this->transID = mt_rand(100000000, 999999999);
                $payment->setTransactionId($this->transID);

                $payment->setAdditionalInformation(
                    [\Magento\Sales\Model\Order\Payment\Transaction::RAW_DETAILS => array("Transaction is not completed yet.")]
                );
                $trn = $payment->addTransaction(\Magento\Sales\Model\Order\Payment\Transaction::TYPE_CAPTURE,null,true);
                $trn->setIsClosed(0)->save();
                $payment->addTransactionCommentsToOrder(
                    $trn,
                    "Transaction is not completed yet."
                );

                $payment->setAdditionalInformation(
                    [
                        "action" => $this->urlBuilder->getBaseUrl() . "AmanPayment/response",
                    ]
                );

                $payment->setParentTransactionId(null);
                $payment->save();
                $order->save();
            }
        }
    }

    public function getAmanAcceptUrl()
    {
        $storeId = $this->getOrder()->getStoreId();
        $secretKey = $this->amanExpressConfig->getSecretKey($storeId);
        $publicKey = $this->amanExpressConfig->getPublicKey($storeId);
        $acceptCreatePaymentUrl = $this->getAmanAcceptCreatePaymentUrl();
        $merchantRefNum = $this->transID;
        $merchantID = $this->amanExpressConfig->getMerchantID($storeId);
        $currency = $this->amanExpressConfig->getCurrency($storeId);

        $billingAddress = $this->getOrder()->getBillingAddress();
        $billingAddressStreet = $billingAddress->getStreet();

        //customer info
        $customerName = $billingAddress->getFirstname() ." ". $billingAddress->getLastname();
        $customerMobile = $billingAddress->getTelephone();
        $customerEmail = $billingAddress->getEmail();
        $customerAddress = $billingAddressStreet[0]. ", ". $billingAddressStreet[1] .", ". $billingAddress->getRegion();



        //Order info
        $orderId = $this->getOrder()->getId();

        $items = $this->getOrder()->getAllItems();

        $productList = array();
        foreach ($items as $itemId => $item)
        {
            $product['id'] = $item->getId();
            $product['name'] = $item->getName();
            $product['quantity'] = intval($item->getQtyOrdered());
            $product['price'] = number_format((float)$item->getPrice(), 2, '.', '');
            $product['sku'] = $item->getSku();
            $product['currency'] = $currency;
            $orderID = $item->getId();
            $orderName = $item->getName();
            $orderDescription = "The SKU of the product is ". $item->getSku();

            $this->logger->info('item getName ' . json_encode($item->getName()));
            $this->logger->info('item getPrice ' . json_encode(number_format((float)$item->getPrice(), 2, '.', '')));
            $this->logger->info('item getSku ' . json_encode($item->getSku()));
            $productList[] = $product;
        }

        $this->logger->info('getDefaultSuccessPageUrl ' . $this->urlBuilder->getUrl('checkout/onepage/success/'));

        $price = round((float)$this->getOrder()->getGrandTotal(),2);

        //building body
        $merchantName = "Merchant Store Name";
        $reference    = 'MT-'.date('Ymd',time()).'-'.$merchantRefNum;

        if($currency){
            $country = substr($currency,0,2);
        }else{
            $currency = 'EGP';
            $country = "EG";
        }
        $amount = $price;
    
        $product= [
            "name"=> $orderName,
            "description"=> $orderDescription,
        ];

        $returnUrl  = $this->urlBuilder->getBaseUrl() . "amanpayment/response?type=return&orderNo=" . $orderId;
        $callbackUrl  = $this->urlBuilder->getBaseUrl() . "rest/default/V1/payload/payload-api";
        $cancelUrl  = $this->urlBuilder->getBaseUrl() . "amanpayment/response?type=cancel&orderNo=" . $orderId;

        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $userClientIP = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $userClientIP = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            $userClientIP = $_SERVER['REMOTE_ADDR'];
        }

        $expireAt = 30;

        $payment_method = $this->getOrder()->getPayment()->getMethod();

        $payMethod = '';
        if($payment_method == ConfigProvider::Aman_Express_Code || $payment_method == ConfigProvider::Aman_Pkr_Express_Code)
        {
            $payMethod = "ReferenceCode";
            $date = date('Y-m-d');
            $expireAt = date('Y-m-d', strtotime($date. ' + 2 days'));
        } else if($payment_method == "aman_pos")
        {
            $payMethod = "ReferenceCode";
            $date = date('Y-m-d');
            $expireAt = date('Y-m-d', strtotime($date. ' + 2 days'));
        } else if($payment_method == "aman_express")
        {
            $payMethod = "ReferenceCode";
            $date = date('Y-m-d');
            $expireAt = date('Y-m-d', strtotime($date. ' + 2 days'));
        } 
        // else if($payment_method == "aman_shahry")
        // {
        //     $payMethod = "Shahry";
        //     $expireAt = 30;
        // } else if($payment_method == "aman_mobile_wallet")
        // {
        //     $payMethod = "MWALLET";
        //     $expireAt = 30;
        // } else if($payment_method == "aman_valu")
        // {
        //     $payMethod = "VALU";
        //     $expireAt = 30;
        // } 
        else if($payment_method == "aman_card_installment")
        {
            $payMethod = "AmanCard";
            $date = date('Y-m-d');
            $expireAt = date('Y-m-d', strtotime($date. ' + 2 days'));
        } else {
            $payMethod = "";
            $date = date('Y-m-d');
            $expireAt = date('Y-m-d', strtotime($date. ' + 2 days'));
        }

        $body = [
            'merchantName' => $merchantName,
            'reference' => $merchantID, // Merchant ID on Aman System
            'orderReference' => $reference,
            'country' => $country,
            'amount' => number_format((float)$amount, 2, '.', ''),
            'currency' => $currency,
            'customer' => [
                'name' => $customerName,
                'phoneNumber' => $customerMobile,
                'emailAddress' => $customerEmail,
                'address' => $customerAddress,
            ],
            'productList' => $productList,
            'returnUrl' => $returnUrl,
            'callbackUrl'=> $callbackUrl,
            'cancelUrl' => $cancelUrl,
            'expireAt' => $expireAt,
            'paymentMethod' => $payMethod,
            'maxPaymentsCount' => 1,
            'fees' => number_format((float)0, 2, '.', ''),
            'platformType' => "Magento2",
            'platformVersion' => "Version 1.0.0"
        ];
        $this->logger->info('Creating with payment_method ' . json_encode($payment_method));

        $this->logger->info('Creating chargeRequest ' . json_encode($body));

        $payment_create_response = $this->adapterFactory
            ->create($storeId)
            ->amanCreatePayment($body);

        $this->logger->info("Receiving payload = " . json_encode($payment_create_response));

        if (array_key_exists("cashierUrl", json_decode(json_encode($payment_create_response), true)))
        {
            //$payment_status = $payment_create_response["message"];
            $this->logger->info("Payment cashierUrl " . $payment_create_response["cashierUrl"]);
            $payment_data_cashierUrl = $payment_create_response["cashierUrl"];
            return "document.getElementById('loading').remove(); window.location.href = \"" . $payment_data_cashierUrl . "\";" ;
//            if(strtoupper($payment_status) == "SUCCESSFUL")
//            {
//            }
//            else{ //not SUCCESSFUL
//                $this->logger->info("not SUCCESSFUL");
//            }
        }
        else //not message
        {
            $this->logger->info("not message");
        }

        return json_encode($payment_create_response);
    }

    //return
    // 1 -- first time load of the success page
    // 2 -- load success after redirect with normal return from payment
    // 3 -- load success after redirect with cancel return from payment
    // 0 -- otherwise
    public function renderAmanExpress($clearSession)
    {
        $this->logger->info("renderAmanExpress getPaymentMethod = " . $this->getOrder()->getPayment()->getMethod());
        if (($this->getOrder()->getPayment()->getMethod() == ConfigProvider::Aman_Express_Code)
            || ($this->getOrder()->getPayment()->getMethod() == ConfigProvider::Aman_Pkr_Express_Code) || ($this->getOrder()->getPayment()->getMethod() == "aman_pos")
            || ($this->getOrder()->getPayment()->getMethod() == "aman_shahry") || ($this->getOrder()->getPayment()->getMethod() == "aman_mobile_wallet") || ($this->getOrder()->getPayment()->getMethod() == "aman_valu") || ($this->getOrder()->getPayment()->getMethod() == "aman_card_installment") || ($this->getOrder()->getPayment()->getMethod() == "aman_now"))
        {
            $testData = $this->checkoutSession->getTestData();
            if($testData == null)
            {
                $this->logger->info("renderAmanExpress Result = 1");
                return 1;
            }
            else if($testData == "return")
            {
                if($clearSession)
                    $this->checkoutSession->setTestData(null);
                $this->logger->info("renderAmanExpress Result = 2");
                return 2;
            }
            else
            {
                if($clearSession)
                    $this->checkoutSession->setTestData(null);
                //($testData == "cancel")
                $this->logger->info("renderAmanExpress Result = 3");
                return 3;
            }

        }
        return 0;
    }

    public function getAction()
    {
        return $this->getOrder()->getPayment()->getAdditionalInformation('action');
    }

    public function getStoreLanguage()
    {
        $locale = $this->localeResolver->getLocale();

        if ($locale) {

            $langCode = strstr($locale, '_', true);

            $langCode = str_replace("lang","",$langCode);

            $this->logger->info('CurrentStore lang ' . $langCode);

            return $langCode;
        }

        return "en";
    }


    public function getCashierPaymentStatusUrl()
    {
        if($this->getEnvironment() == Environment::ENVIRONMENT_PRODUCTION)
        {
            return $this->amanExpressConfig->getAmanAcceptPaymentStatusUrlProduction();
        }
        else
        {
            return $this->amanExpressConfig->getAmanAcceptPaymentStatusUrlTest();
        }
    }


    public function getAmanAcceptCreatePaymentUrl()
    {
        if($this->getEnvironment() == Environment::ENVIRONMENT_PRODUCTION)
        {
            return $this->amanExpressConfig->getAmanAcceptCreatePaymentUrlProduction();
        }
        else
        {
            return $this->amanExpressConfig->getAmanAcceptCreatePaymentUrlTest();
        }
    }


    public function getAmanExpressTitle()
    {
        $storeId = $this->getOrder()->getStoreId();
        $currency = $this->amanExpressConfig->getCurrency($storeId);
        if(!$currency){
            $currency = 'EGP';
        }
        return __('Please provide the payment of %1 '.$currency.' to process your order', $this->getPrice());
    }

    public function getEnvironment()
    {
        return $this->amanExpressConfig->getEnvironment($this->storeManager->getStore()->getId());
    }

    // /**
    //  * @return \Magento\Sales\Model\Order
    //  */
    public function getOrder()
    {
        if ($this->order == null) {
            $orderId = $this->checkoutSession->getLastOrderId();
            $this->logger->info('Creating Order for orderId '. $orderId);
            $this->order = $this->orderFactory->create()->load($orderId);
        }
        return $this->order;
    }

    public function getPrice()
    {
        return round((float)$this->getOrder()->getGrandTotal(),2);
    }
}
