<?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\Order;

use Magento\Framework\App\Action;
class ReUploadCustomDesign extends Action\Action
{
    const CUSTOM_PREVIEWS = 'custom_previews';
    protected $jsonFactory;
    protected $file;
    protected $advancePreviewFileFactory;
    protected $advancePreviewUploadFactory;
    protected $colPreviewThreeFactory;
    protected $previewOrderItemsFactory;
    protected $resPreviewOrderItemsFactory;
    protected $colPreviewOrderItemsFactory;
    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,
        \Magetop\Advancepreview\Model\PreviewOrderItemsFactory $previewOrderItemsFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewOrderItemsFactory $resPreviewOrderItemsFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewOrderItems\CollectionFactory $colPreviewOrderItemsFactory

    )
    {
        parent::__construct($context);
        $this->jsonFactory = $jsonFactory;
        $this->file = $file;
        $this->advancePreviewFileFactory = $advancePreviewFileFactory;
        $this->advancePreviewUploadFactory = $advancePreviewUploadFactory;
        $this->colPreviewThreeFactory = $colPreviewThreeFactory;
        $this->previewOrderItemsFactory = $previewOrderItemsFactory;
        $this->resPreviewOrderItemsFactory = $resPreviewOrderItemsFactory;
        $this->colPreviewOrderItemsFactory = $colPreviewOrderItemsFactory;
    }
    public function execute()
    {
        // TODO: Implement execute() method.
        $response = [
            'status'=>'error',
            'message'=>'Can not upload your design keke',
            'own_design'=>'',
            'base_file'=>'',
            'preview_filed'=>[],
        ];
        $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;
        $isReupProduct = isset($params['is_reup_product']) ? (int)$params['is_reup_product'] : 0;
        $textureHeight = isset($params['texture_height']) ? (int)$params['texture_height'] : 0;
        $zoom = isset($params['zoom']) ? (int)$params['zoom'] : 0;
        $light = isset($params['light']) ? (int)$params['light'] : 0;
        $texture = isset($params['texture']) ? trim($params['texture']) : '';
        $oldWwnFolder = isset($params['own_folder']) ? trim($params['own_folder']) : '';
        $namePreview = isset($params['name_preview']) ? trim($params['name_preview']) : '';
        $originalFile =  isset($params['original_file']) ? trim($params['original_file']) : '';
        $itemId =  isset($params['item_id']) ? (int)$params['item_id'] : 0;
        $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 == '' || $oldWwnFolder == '') {
            $response['message'] = 'design not found' . ' - '. $texture . ' - ' . $oldWwnFolder. ' - '. $originalFile;
            return $this->jsonFactory->create()->setData($response);
        }
        $ownFolder = $this->cloneDesignFolder($customFolderUpload,$productId,$oldWwnFolder);
        $ouwModelFolder = $customFolderUpload.'/'.$ownFolder;
        if($this->file->isExists($ouwModelFolder)) {
            $options['allow_type'] = ['pdf','ai'];
            $options['file_name'] = $texture;
            $options['is_convert'] = 1;
            $options['is_remove'] = 0;
//            $options['original_file_name'] = $originalFile;
            $uploadResponse = $uploadModel->uploadPdfAiFileAndGetName('custom_preview',$ouwModelFolder,'',$params, $options);
            if($uploadResponse['status'] == 'success') {
                // update status to new
                $previewItem = $this->getPreviewItemByItemId($itemId);
                if($previewItem->getId()) {
                    $dataUpdate = [
                        'status' => 'new',
                        'custom_item_id' => $previewItem->getId(),
                        'updated_at' => date('Y-m-d H:i:s'),
                        'preview_model'=>$ownFolder,
                    ];
                    $updateId = $this->savePreviewOrderItem($dataUpdate);
                }
                $response['status'] = 'success';
                $response['message'] = $uploadResponse;
                $response['own_design'] = $ownFolder;
                $file = $uploadResponse['file_name'];
                $response['base_file'] = $uploadResponse['base_file'];
                if($isReupProduct == 1) {
                    $this->updateCustomerUploadFile($itemId,$response['base_file'],$ownFolder);
                }
                $previewFileds = [
                    'zoom'=>$zoom,
                    'light'=>$light,
                    'model_preview'=>$ownFolder,
                    'name_preview'=>$namePreview,
                    'product_id'=>$productId,
                ];
                $response['preview_filed'] = $previewFileds;
//                $uploadModel->re
                $resignSubFolder = $customFolder.'/'.$ownFolder;
                $response['resize_image'] =  $this->advancePreviewFileFactory->create()->resizeImagePro($file,$resignSubFolder,$textureWidth,$textureHeight,false,false);
            }
            else {
                $response['message'] = $uploadResponse['message'];
            }
        }
        else {
            $response['message'] = 'Default Preview Model Not found';
        }
        if($response['status'] == 'success') {
            $this->messageManager->addSuccessMessage(__('You have re-uploaded design success'));
        }
        else {
            $this->messageManager->addErrorMessage(__('Something wrong when upload design, please check again'));
        }
        return $this->jsonFactory->create()->setData($response);

    }
    protected function updateCustomerUploadFile($itemId, $file,$ownFolder = '') {
        // get data
        $collection = $this->colPreviewOrderItemsFactory->create()
            ->addFieldToSelect(array('custom_item_id'))
            ->addFieldToFilter('item_id',$itemId);
        $id = 0;
        if($collection && $collection->getSize() > 0) {
            $id = $collection->getFirstItem()->getData('custom_item_id');
        }
        if($id > 0) {
            $model = $this->previewOrderItemsFactory->create();
            $dataSave = array(
              'custom_item_id'=>$id,
              'item_id'=>$itemId,
              'custom_design'=>$file,
               'preview_model'=>$ownFolder,

            );
            $model->setData($dataSave);
            try {
                $this->resPreviewOrderItemsFactory->create()->save($model);
                return true;
            }
            catch (\Exception $exception) {

            }
        }
        return  false;
    }
    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.'/'.$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;
    }
    public function getPreviewItemByItemId($itemId = 0) {
        $collection = $this->colPreviewOrderItemsFactory->create()
            ->addFieldToSelect(array('status'))
            ->addFieldToFilter('item_id',$itemId);
        $previewItem = $collection && $collection->getSize() > 0 ? $collection->getFirstItem() : null;
        return $previewItem;

    }

    /**
     * @param array $previewData
     * @return int
     */
    protected function savePreviewOrderItem($previewData = []) {
        $model = $this->previewOrderItemsFactory->create();
        $model->setData($previewData);
        $id = 0;
        try {
            $this->resPreviewOrderItemsFactory->create()->save($model);
            $id =  $model->getId();
        }
        catch (\Exception $exception) {

        }
        return $id;

    }
}
