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

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

class MassDelete extends \Magento\Customer\Controller\AbstractAccount
{
    /**
     * @var PageFactory
     */
    protected $_resultPageFactory;

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

    /**
     * @var Webkul\Agorae\Model\MpfavouritesellerRepository
     */
    protected $_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);
    }

    /**
     * MassDelete
     */
    public function execute()
    {
        $resultRedirect = $this->resultRedirectFactory->create();
        if ($this->getRequest()->isPost()) {
            $sellerIds = $this->getRequest()->getParam('seller_mass_delete');
            $customerId = $this->_customerSession->getCustomer()->getId();
            foreach ($sellerIds as $sellerId) {
                $favouritesCollection = $this->_mpFavouritesellerRepository
                                    ->getSellerCollectionByCustomerId($sellerId, $customerId);
                foreach ($favouritesCollection as $favSeller) {
                    $this->_delSeller($favSeller);
                }
            }
        }
        $this->messageManager->addSuccess(
            __(
                'Successfully favourite Sellers removed'
            )
        );
        return $resultRedirect->setPath('agorae/favouriteseller/index');
    }

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