<?php


namespace Magetop\Advancepreview\Controller\Adminhtml\PreviewAdditionalTab;


use Magento\Backend\App\Action;

/**
 * Class UploadMedia
 * @package Magetop\Advancepreview\Controller\Adminhtml\ProductPreview
 */
class DellItem extends \Magetop\Advancepreview\Controller\Adminhtml\PreviewAdditionalTab
{

    protected $previewAdditionalFactory;
    protected $resPreviewAdditionalFactory;
    protected $colPreviewAdditionalFactory;

    public function __construct(
        Action\Context $context,
        \Magento\Framework\Controller\Result\JsonFactory $jsonFactory,
        \Magetop\Advancepreview\Model\PreviewAdditionalFactory $previewAdditionalFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewAdditionalFactory $resPreviewAdditionalFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewAdditional\CollectionFactory $colPreviewAdditionalFactory
    )
    {
        parent::__construct($context, $jsonFactory);
        $this->previewAdditionalFactory = $previewAdditionalFactory;
        $this->resPreviewAdditionalFactory = $resPreviewAdditionalFactory;
        $this->colPreviewAdditionalFactory = $colPreviewAdditionalFactory;

    }

    /**
     * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\Result\Json|\Magento\Framework\Controller\ResultInterface|void
     * @throws \Magento\Framework\Exception\FileSystemException
     */
    function execute()
    {
        $response = [
            'status'=>'error',
            'message'=>__('Something wrong when saving data'),
            'html'=>''
        ];
        $params = $this->getRequest()->getParams();
        $additionId = isset($params['addition_id']) ? (int)$params['addition_id'] : 0;
        $isDell = $this->deleteAdditionalItem($additionId);
        if($isDell) {
            $response['status'] = 'success';
            $response['message'] = __('You have deleted item success');
            $response['html'] = $this->_view->getLayout()->createBlock('Magetop\Advancepreview\Block\Adminhtml\Product\Edit\PreviewAdditionalTab')->setTemplate('Magetop_Advancepreview::product/addition_tab/items.phtml')->toHtml();

        }
        return $this->getAjaxResponse($response);
    }


    protected function deleteAdditionalItem($id) {
        $model = $this->previewAdditionalFactory->create();
        $model->setId($id);
        try {
            $this->resPreviewAdditionalFactory->create()->delete($model);
            return true;
        }
        catch (\Exception $exception) {
        }
        return false;
    }
}
