<?php
/******************************************************************************
 *   ______                                                                   *
 *  /       \                                                                 *
 * /$$$$$$  | ________  __    __   ______    ______                           *
 * $$ |__$$ |/        |/  |  /  | /      \  /      \                          *
 * $$    $$ |$$$$$$$$/ $$ |  $$ |/$$$$$$  |/$$$$$$  |                         *
 * $$$$$$$$ |  /  $$/  $$ |  $$ |$$ |  $$/ $$    $$ |                         *
 * $$ |  $$ | /$$$$/__ $$ \__$$ |$$ |      $$$$$$$$/                          *
 * $$ |  $$ |/$$      |$$    $$/ $$ |      $$       |                         *
 * $$/   $$/ $$$$$$$$/  $$$$$$/  $$/        $$$$$$$/                          *
 *                                                                            *
 * @PROJECT    : 3D Preview Extension [Magetop.com]                           *
 * @AUTHOR     : Azure - Developer                                            *
 * @COPYRIGHT  : © 2019  Magetop.com                                          *
 * @LINK       : https://Magetop.com                                          *
 * @CREATED    :  10/01/2022                                                  *
 ******************************************************************************/

namespace Magetop\Advancepreview\Controller\Product;

use Magento\Framework\App\Action;


class UploadCustomDesign extends Action\Action
{
    const CUSTOM_PREVIEWS = 'custom_previews';
    protected $jsonFactory;
    protected $file;
    protected $advancePreviewFileFactory;
    protected $advancePreviewUploadFactory;
    protected $colPreviewThreeFactory;
    public function __construct(
        Action\Context $context,
        \Magento\Framework\Controller\Result\JsonFactory $jsonFactory,
        \Magento\Framework\Filesystem\Driver\File $file,
        \Magetop\Advancepreview\Model\AdvancePreviewFileFactory $advancePreviewFileFactory,
        \Magetop\Advancepreview\Model\AdvancePreviewUploadFactory $advancePreviewUploadFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewThree\CollectionFactory $colPreviewThreeFactory

    )
    {
        parent::__construct($context);
        $this->jsonFactory = $jsonFactory;
        $this->file = $file;
        $this->advancePreviewFileFactory = $advancePreviewFileFactory;
        $this->advancePreviewUploadFactory = $advancePreviewUploadFactory;
        $this->colPreviewThreeFactory = $colPreviewThreeFactory;
    }
    public function execute()
    {
        // TODO: Implement execute() method.
        $response = [
           'status'=>'error',
            'message'=>'Can not upload your design',
            'own_design'=>'',
            'base_file'=>''
        ];
        $params = $this->getRequest()->getParams();
        $productId = isset($params['product_id']) ? (int)$params['product_id'] : 0;
        $previewItem  = $this->getPreviewListByProductId($productId);
        $folderPreview = '';
        if($previewItem != null && $previewItem->getData('folder_preview') != '') {
            $folderPreview = $previewItem->getData('folder_preview');
        }
        else {
            $response['message'] = __('Preview Data not found, Please contact to admin');
            return  $this->jsonFactory->create()->setData($response);
        }
        $textureWidth = isset($params['texture_width']) ? (int)$params['texture_width'] : 0;
        $textureHeight = isset($params['texture_height']) ? (int)$params['texture_height'] : 0;
        $texture = isset($params['texture']) ? trim($params['texture']) : '';
        $customFolder = self::CUSTOM_PREVIEWS.'/product_id_'.$productId;
        $advancePreviewFile = $this->advancePreviewFileFactory->create();
        $customFolderUpload = $advancePreviewFile->getBaseDir($customFolder);
        $uploadModel = $this->advancePreviewUploadFactory->create();
        $media = $advancePreviewFile->getAdvanceMediaFolder();
        /*if($this->file->isExists($customFolderUpload)) {
            $this->file->createDirectory($customFolderUpload,0775);
        }
        $options['file_name'] = 'Barra_baseColor.png';
        $customPreview = $uploadModel->uploadFileAndGetName('custom_preview',$customFolderUpload,$media.$customFolder,$params, $options);*/
        if($texture == '') {
            $response['message'] = 'Default Wrapper design not found';
            return $this->jsonFactory->create()->setData($response);
        }
        $ownFolder = $this->cloneDesignFolder($customFolderUpload,$productId,$folderPreview);
//        $ownFolder = $this->getRequest()->getParam('custom_folder','');
        $ouwModelFolder = $customFolderUpload.'/'.$ownFolder;
//        $response['folder_custom'] = $ouwModelFolder;
        if($this->file->isExists($ouwModelFolder)) {
            $options['allow_type'] = ['pdf','ai'];
            $options['file_name'] = $texture;
            $options['is_convert'] = 1;
            $options['is_remove'] = 0;
            $uploadResponse = $uploadModel->uploadPdfAiFileAndGetName('custom_preview',$ouwModelFolder,'',$params, $options);
            if($uploadResponse['status'] == 'success') {
                $response['status'] = 'success';
                $response['message'] = $uploadResponse;
                $response['own_design'] = $ownFolder;
                $file = $uploadResponse['file_name'];
                $response['base_file'] = $uploadResponse['base_file'];
//                $uploadModel->re
                $resignSubFolder = $customFolder.'/'.$ownFolder;
                $response['resize_image'] =  $this->advancePreviewFileFactory->create()->resizeImagePro($file,$resignSubFolder,$textureWidth,$textureHeight,false,false);
            }
        }
        else {
            $response['message'] = 'Default Preview Model Not found';
        }
        return $this->jsonFactory->create()->setData($response);

    }
    protected function cloneDesignFolder($customFolderUpload, $productId, $folderPreview, $ignoreFile = '') {
        /** @var \Magento\Catalog\Model\Session $catalogSession */
      /*  $catalogSession = $this->_objectManager->get('Magento\Catalog\Model\Session');
        if($catalogSession->getOwnDesignFolder() && $catalogSession->getOwnDesignFolder() != '' && strrpos($productId,$catalogSession->getOwnDesignFolder()) !== false) {
            $ownFolder = $catalogSession->getOwnDesignFolder();
        }
        else {
            $ownFolder = $productId.'_'.time();
            $catalogSession->setOwnDesignFolder($ownFolder);
        }*/
        $ownFolder = $productId.'_'.time();
        $this->copyPreviewModel($customFolderUpload.'/model-'.$folderPreview,$customFolderUpload,$ownFolder, $ignoreFile);
        return $ownFolder;
    }
    private function copyPreviewModel(
         $sourceDirectory,
         $destinationDirectory,
         $childFolder = '',
        $ignoreFile = ''
    ) {
		 /** @var \Magento\Framework\Filesystem $fileSystem*/
        $fileSystem = $this->_objectManager->get('Magento\Framework\Filesystem');
        $mediaDirectory = $fileSystem->getDirectoryWrite('media');
        $directory = opendir($sourceDirectory);

        if (is_dir($destinationDirectory) === false) {
            mkdir($destinationDirectory);
        }

        if ($childFolder !== '') {
            if (is_dir("$destinationDirectory/$childFolder") === false) {
                mkdir("$destinationDirectory/$childFolder");
            }

            while (($file = readdir($directory)) !== false) {
                if ($file === '.' || $file === '..' || $file == $ignoreFile) {
                    continue;
                }

                if (is_dir("$sourceDirectory/$file") === true) {
                    // recurseCopy("$sourceDirectory/$file", "$destinationDirectory/$childFolder/$file");
					$mediaDirectory->copyFile("$sourceDirectory/$file", "$destinationDirectory/$childFolder/$file");
                } else {
                    copy("$sourceDirectory/$file", "$destinationDirectory/$childFolder/$file");
                }
            }

            closedir($directory);

            return;
        }

        while (($file = readdir($directory)) !== false) {
            if ($file === '.' || $file === '..') {
                continue;
            }

            if (is_dir("$sourceDirectory/$file") === true) {
                recurseCopy("$sourceDirectory/$file", "$destinationDirectory/$file");
            }
            else {
                copy("$sourceDirectory/$file", "$destinationDirectory/$file");
            }
        }

        closedir($directory);
    }

    /**
     * @param int $productId
     * @return \Magento\Framework\DataObject|mixed|null
     */
    protected function getPreviewListByProductId($productId = 0) {
        $collection = $this->colPreviewThreeFactory->create()
            ->addFieldToSelect(array('folder_preview'))
            ->addFieldToFilter('product_id',$productId)
            ->setOrder('is_default','ASC')
            ->setOrder('position','ASC');
//        echo (string)$collection->getSelect();
        $itemPreview = null;
        if($collection && $collection->getSize() > 0) {
            $itemPreview = $collection->getFirstItem();
            foreach ($collection as $item) {
                if($item->getData('is_default') == 1) {
                    $itemPreview = $item;
                    break;
                }
            }
        }
        return $itemPreview;
    }

}
