<?php
/**
 * @author    Webarian Team
 * @copyright Copyright (c) 2020 Webarian (https://www.webariansoftwares.com/)
 * @package   Webarian_PromoPopup
 */
namespace Webarian\Workshop\Controller\Adminhtml\Workshop;

use Magento\Framework\Controller\ResultFactory;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Registry;
use Webarian\Workshop\Model\WorkshopFactory;

class MassDelete extends \Magento\Backend\App\Action
{
	protected $_coreRegistry;
	protected $query;
	protected $_workshopFactory;
	protected $productRepository;

	public function __construct(
		Context $context,
		Registry $registry,
		WorkshopFactory $workshopFactory,
		\Magento\Catalog\Model\ProductRepository $productRepository
	)
	{
		$this->_coreRegistry = $registry;
		$this->_workshopFactory = $workshopFactory;
		$this->productRepository = $productRepository;
		parent::__construct($context);
	}

	public function execute(){
		// $productId = 224;
		// $product = $this->_objectManager->create('Magento\Catalog\Model\Product');
		// $product->load($productId)->delete();die;
		

		$workshopIds = $this->getRequest()->getParam('workshop_param');
		$workshopObj = $this->_workshopFactory->create();

		$countWorkshopId = 0;

		if(!is_array($workshopIds)) {
			$this->messageManager->addError(__('Please select item(s)'));
		}
		else{
			//$product = $this->_objectManager->create('Magento\Catalog\Model\Product');
			try {
				foreach ($workshopIds as $workshopId) {
					$collection = $workshopObj->load($workshopId);
					$productId = $collection->getData('product_id');
					$collection->delete();

					//$product->load($productId)->delete();
					if ($product = $this->productRepository->getById($productId)){
						$this->productRepository->delete($product);
					}

					$countWorkshopId++;
				}

				$this->messageManager->addSuccess(
					__('A total of %1 record(s) have been deleted.', $countWorkshopId)
				);
				
			} catch (\Magento\Framework\Exception\LocalizedException $e) {
				$this->messageManager->addError($e->getMessage());
			} catch (\Exception $e) {
				$this->_getSession()->addException($e, __('Something went wrong while updating the product(s) status.'));
			}
			$redirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
			return $redirect->setPath('workshop/workshop/index');
		}
	}
}