<?php
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_MpPayPal
 * @author    Webkul
 * @copyright Copyright (c) Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */

namespace Webkul\MpPayPal\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Webkul\MpPayPal\Model\PayPal\Adapter;
use Magento\Framework\Message\ManagerInterface;

/**
 * Webkul MpPayPal PreDispatchConfigSaveObserver Observer.
 */
class PreDispatchConfigSaveObserver implements ObserverInterface
{
    protected $storeManager;

    public function __construct(
        ScopeConfigInterface $scopeConfig,
        ManagerInterface $messageManager,
        Adapter $adapter,
        \Magento\Framework\App\Config\Storage\WriterInterface $configWriter,
        \Magento\Store\Model\StoreManagerInterface $storeManager
    ) {
        $this->scopeConfig = $scopeConfig;
        $this->_messageManager = $messageManager;
        $this->adapter = $adapter;
        $this->configWriter = $configWriter;
        $this->storeManager = $storeManager;
    }

    /**
     * @param \Magento\Framework\Event\Observer $observer
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        
        try {
            $observerRequestData = $observer['request'];
            
            $params = $observerRequestData->getParams();
            if ($params['section'] == 'payment') {
                $paramsData = $params['groups']['mppaypal']['fields'];
                $newEnvironment = $paramsData['environment']['value'];
                $oldEnvironment = $this->scopeConfig->getValue(
                    'payment/mppaypal/environment',
                    \Magento\Store\Model\ScopeInterface::SCOPE_STORE
                );
                
                if ($newEnvironment != $oldEnvironment) {
                    $path = 'payment/mppaypal/webhook_sandbox_id';
                    $url = Adapter::SANDBOX_URL;
                    if ($oldEnvironment == 'production') {
                        $path = 'payment/mppaypal/webhook_production_id';
                        $url = Adapter::LIVE_URL;
                    }
                    
                    $webhookId = $this->scopeConfig->getValue(
                        $path,
                        \Magento\Store\Model\ScopeInterface::SCOPE_STORE
                    );
                    if ($webhookId) {
                        $finalUrl = $url.Adapter::WEBHOOK_DELETE_URL.'/'.$webhookId;

                        $this->sendHttpRequest($finalUrl);
                        
                        $this->configWriter->save(
                            $path,
                            '',
                            $scope = ScopeConfigInterface::SCOPE_TYPE_DEFAULT,
                            $scopeId = \Magento\Store\Model\ScopeInterface::SCOPE_STORE
                        );
                    }
                }
            }
        } catch (\Exception $e) {
            $this->_messageManager->addError($e->getMessage());
        }
    }

    /**
     * send delete webhook request
     *
     * @param string $finalUrl
     * @return void
     */
    public function sendHttpRequest($finalUrl)
    {
        $token = $this->adapter->getAccessToken();
        $httpHeaders = new \Zend\Http\Headers();
        $httpHeaders->addHeaders([
            'Authorization' => 'Bearer ' . $token,
            'Accept' => 'application/json',
            'Content-Type' => 'application/json'
        ]);
        $request = new \Zend\Http\Request();
        $request->setHeaders($httpHeaders);
        $request->setUri($finalUrl);
        $request->setMethod(\Zend\Http\Request::METHOD_DELETE);

        $client = new \Zend\Http\Client();
        $options = [
            'adapter'   => \Zend\Http\Client\Adapter\Curl::class,
            'curloptions' => [CURLOPT_FOLLOWLOCATION => true],
            'maxredirects' => 0,
            'timeout' => 30
        ];
        $client->setOptions($options);

        $client->send($request);
    }
}
