<?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\Model;

use Webkul\MpPayPal\Api\WebhookInterface;

class Webhook implements WebhookInterface
{
    /**
     * webhook events array
     */
    protected $_webhookEvent = [];

    public function __construct(
        \Magento\Framework\Filesystem\Driver\File $driver,
        \Webkul\MpPayPal\Helper\Data $helper,
        \Magento\Framework\Json\Helper\Data $jsonHelper,
        \Magento\Framework\Controller\Result\JsonFactory $jsonResultFactory,
        $webhookEvent = []
    ) {
        $this->driver = $driver;
        $this->helper = $helper;
        $this->jsonHelper = $jsonHelper;
        $this->jsonResultFactory = $jsonResultFactory;
        $this->_webhookEvent = $webhookEvent;
    }

    /**
     * handle payment success
     *
     * @api
     * @return \Magento\Framework\Controller\Result\JsonFactory
     */

    public function executeWebhook()
    {
        $data = $this->driver->fileGetContents('php://input');
        $this->helper->logDataInLogger('data '.$data);
        $paypalResponse = $this->jsonHelper->jsonDecode($data);
        $eventType = $paypalResponse['event_type'];
        $this->helper->logDataInLogger('eventType '.$eventType);
        
        if ($eventType && isset($this->_webhookEvent[$eventType])) {
            $this->_webhookEvent[$eventType]->process($paypalResponse['resource']);
        }
        $result = $this->jsonResultFactory->create();
        
        $result->setHttpResponseCode(200);
        return $result;
    }
}
