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

use Magento\Backend\App\Action;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem;
use Magento\Store\Model\StoreManagerInterface;
use Webarian\Workshop\Model\WorkshopFactory;

class Save extends Action
{
    protected $filesystem;
    protected $storeManager;
    protected $workshopFactory;

    public function __construct(
        Action\Context $context,
        Filesystem $filesystem,
        StoreManagerInterface $storeManager,
        WorkshopFactory $workshopFactory
    ) {
        parent::__construct($context);
        $this->filesystem = $filesystem;
        $this->storeManager = $storeManager;
        $this->workshopFactory = $workshopFactory;
    }

    public function execute()
    {
        $data = $this->getRequest()->getPostValue();
        if (!$data) {
            $this->_redirect('*/*/');
            return;
        }

        $workshopModel = $this->workshopFactory->create();
        $workshopId = isset($data['workshop_id']) ? $data['workshop_id'] : null;

        try {
            // Handle image upload
            $uploader = $this->_objectManager->create(
                \Magento\MediaStorage\Model\File\Uploader::class,
                ['fileId' => 'banner']
            );
            $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
            $uploader->setAllowRenameFiles(true);
            $uploader->setFilesDispersion(true);
            $mediaDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
            $targetPath = $mediaDirectory->getAbsolutePath('webarian/workshop/thumbnails');
            $result = $uploader->save($targetPath);

            if ($result['file']) {
                $data['banner'] = 'webarian/workshop/thumbnails' . $result['file'];
            }

            // Save data to the database
            $workshopModel->setData($data);
            if ($workshopId) {
                $workshopModel->setId($workshopId);
            }
            $workshopModel->save();

            $this->messageManager->addSuccess(__('Workshop saved successfully.'));
        } catch (LocalizedException $e) {
            $this->messageManager->addError($e->getMessage());
        } catch (\Exception $e) {
            $this->messageManager->addException($e, __('Something went wrong while saving the workshop.'));
        }

        $this->_redirect('*/*/');
    }
}
