<?php
/**
 * Webkul Software.
 *
 * @category   Webkul
 * @package    Webkul_Agorae
 * @author     Webkul Software Private Limited
 * @copyright  Copyright (c) Webkul Software Private Limited (https://webkul.com)
 * @license    https://store.webkul.com/license.html
 */
namespace Webkul\Agorae\Controller\Shopfollower;

use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Webkul\Agorae\Model\MpfavouritesellerRepository;

class Delete extends \Magento\Customer\Controller\AbstractAccount
{
    /**
     * @var PageFactory
     */
    private $resultPageFactory;

    /**
     * @var \Magento\Customer\Model\Session
     */
    protected $_customerSession;

    /**
     * @var Webkul\Agorae\Model\MpfavouritesellerRepository
     */
    private $mpFavouritesellerRepository;

    /**
     * @param Context                         $context
     * @param MpfavouritesellerRepository     $mpFavouritesellerRepository
     * @param \Magento\Customer\Model\Session $customerSession
     * @param PageFactory                     $resultPageFactory
     */
    public function __construct(
        Context $context,
        MpfavouritesellerRepository $mpFavouritesellerRepository,
        \Magento\Customer\Model\Session $customerSession,
        PageFactory $resultPageFactory
    ) {
        $this->mpFavouritesellerRepository = $mpFavouritesellerRepository;
        $this->_customerSession = $customerSession;
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }

    /**
     * Delete class
     */
    public function execute()
    {
        try {
            $resultRedirect = $this->resultRedirectFactory->create();
            $customerId = $this->getRequest()->getParam('id');
            $sellerId = $this->_customerSession
                        ->getCustomer()->getId();
            $followerCollection = $this->mpFavouritesellerRepository
                ->getSellerCollectionByCustomerId($sellerId, $customerId);
            if ($followerCollection->getSize()) {
                foreach ($followerCollection as $follower) {
                    $this->_delFollower($follower);
                    $this->messageManager->addSuccess(
                        __(
                            'Successfully follower removed'
                        )
                    );
                }
            }
        } catch (\Exception $e) {
            $this->messageManager->addError($e->getMessage());
        }
        return $resultRedirect->setPath('agorae/shopfollower/index');
    }

    /**
     * Delete follower
     *
     * @param  object $thisObject
     * @return $this
     */
    private function _delFollower($thisObject)
    {
        $thisObject->delete()->save();
    }
}
