<?php

namespace Sibs\Sibs\Model\Api;

use Exception;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\App\ResponseInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Sibs\Sibs\Api\SibsLogWebhookInterface;
use Sibs\Sibs\Helper\DataHelper as SibsHelper;
use Sibs\Sibs\Model\SibsConstants;
use Sibs\Sibs\Utils\SibsException;
use Sibs\Sibs\Utils\SibsLog;

/**
 * Class SibsLogWebhook.
 */
class SibsLogWebhook implements SibsLogWebhookInterface
{
    /**
     * @var \Magento\Framework\App\RequestInterface
     */
    protected $request;

    /**
     * @var \Magento\Framework\App\ResponseInterface
     */
    protected $response;

    /**
     * @var \Sibs\Sibs\Helper\DataHelper
     */
    protected $helper;

    /**
     * @var \Magento\Sales\Api\OrderRepositoryInterface
     */
    protected $orderRepository;

    /**
     * CustomerAddress constructor.
     * @param \Magento\Framework\App\RequestInterface $request
     * @param \Magento\Framework\App\ResponseInterface $response
     */
    public function __construct(
        RequestInterface $request,
        ResponseInterface $response,
        SibsHelper $helper,
        OrderRepositoryInterface $orderRepository
    ) {
        $this->request  = $request;
        $this->response = $response;

        $this->helper          = $helper;
        $this->orderRepository = $orderRepository;
    }

    /**
     * @inheritdoc
     */
    public function sibsLog()
    {
        SibsLog::setNameFile(SibsConstants::SIBS_LOG_WEBHOOK);

        try {
            SibsLog::info('SIBSLOGWEBHOOK INIT');
            SibsLog::warn('SIBSLOGWEBHOOK - getContent');

            $httpBody = $this->request->getContent();

            sibsLog::warn($httpBody);
            SibsLog::info('SIBSLOGWEBHOOK END');

            $this->responseSuccess();
        } catch (SibsException $e) {
            $this->responseError(400, $e->getErrorMessage());
        } catch (Exception $e) {
            SibsLog::err($e->getMessage());
            $this->responseError(500, $e->getMessage());
        }
    }

    public function responseSuccess()
    {
        $this->response->getHeaders()
            ->addHeaderLine('Content-Type', 'application/json');

        $this->response->setContent(json_encode([
            'statusCode'     => 200,
            'statusMsg'      => 'Success',
        ]));

        $this->response->send();

        die();
    }

    public function responseError($errorCode, $errorMessage = 'Error')
    {
        $this->response->getHeaders()
            ->addHeaderLine('Content-Type', 'application/json');

        $this->response->setContent(json_encode([
            'statusCode' => $errorCode,
            'statusMsg'  => $errorMessage,
        ]));

        $this->response->send();

        die();
    }
}
