<?php
/**
 * @author Aitoc Team
 * @copyright Copyright (c) 2020 Aitoc (https://www.aitoc.com)
 * @package Aitoc_PreOrders
 */

/**
 * Copyright © 2018 Aitoc. All rights reserved.
 * Developed by Alex Yakimovich
 */
namespace Aitoc\PreOrders\Controller\Notification;

use Aitoc\PreOrders\Api\Data\PreOrderSubscribersInterfaceFactory;
use Aitoc\PreOrders\Model\PreOrderSubscribers;
use Aitoc\PreOrders\Model\PreOrderSubscribersRepository;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Framework\Exception\LocalizedException;

class Subscribe extends Action
{
    /**
     * @var PreOrderSubscribersInterfaceFactory
     */
    private $preOrderSubscribersModel;

    /**
     * @var PreOrderSubscribersRepository
     */
    private $preOrderSubscribersRepository;

    /**
     * @param PreOrderSubscribersRepository $preOrderSubscribersRepository
     * @param PreOrderSubscribersInterfaceFactory $preOrderSubscribers
     * @param Context $context
     */
    public function __construct(
        PreOrderSubscribersRepository $preOrderSubscribersRepository,
        PreOrderSubscribersInterfaceFactory $preOrderSubscribers,
        Context $context
    ) {
        $this->preOrderSubscribersRepository = $preOrderSubscribersRepository;
        $this->preOrderSubscribersModel = $preOrderSubscribers;
        parent::__construct($context);
    }

    /**
     * Subscribe action
     *
     * @return ResponseInterface|Redirect|ResultInterface
     */
    public function execute()
    {
        /** @var HttpRequest $request */
        $request = $this->getRequest();
        if ($request->isPost()) {
            try {
                $requestData = (array)$request->getPost();
                /** @var PreOrderSubscribers $subscriberModel */
                $subscriberModel = $this->preOrderSubscribersModel->create();
                $subscriberModel
                    ->setProductId($requestData['product_id'])
                    ->setProductId($requestData['product_id'])
                    ->setCustomerEmail($requestData['email'])
                    ->setCustomerName($requestData['customer_name']);
                $this->preOrderSubscribersRepository->save($subscriberModel);
            } catch (LocalizedException $e) {
                $this->messageManager->addErrorMessage($e->getMessage());
            }
        } else {
            $this->messageManager->addErrorMessage(__("Invalid post data."));
        }
        $this->messageManager->addSuccessMessage('You has been subscribed successfully');
        $resultRedirect = $this->resultRedirectFactory->create();
        $resultRedirect->setUrl($this->_redirect->getRefererUrl());
        return $resultRedirect;
    }
}