<?php
namespace Magetop\Advancepreview\Controller\Adminhtml\Order;

use Magento\Backend\App\Action;
class UploadProof extends Action
{
    const CUSTOM_PREVIEWS = 'custom_previews';
    protected $jsonFactory;
    /**
     * @var \Magetop\Advancepreview\Model\PreviewOrderItemsFactory
     */
    protected $previewOrderItemsFactory;
    /**
     * @var \Magetop\Advancepreview\Model\ResourceModel\PreviewOrderItemsFactory
     */
    protected $resPreviewOrderItemsFactory;
    protected $colPreviewOrderItemsFactory;
    protected $emailHelper;
    protected $file;
    protected $advancePreviewFileFactory;
    protected $advancePreviewUploadFactory;
    protected $colPreviewThreeFactory;
    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\PreviewOrderItemsFactory $previewOrderItemsFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewOrderItemsFactory $resPreviewOrderItemsFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewOrderItems\CollectionFactory $colPreviewOrderItemsFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewThree\CollectionFactory $colPreviewThreeFactory,
        \Magetop\Advancepreview\Helper\Email $emailHelper
    )
    {
        parent::__construct($context);
        $this->jsonFactory = $jsonFactory;
        $this->file = $file;
        $this->advancePreviewFileFactory = $advancePreviewFileFactory;
        $this->advancePreviewUploadFactory = $advancePreviewUploadFactory;
        $this->previewOrderItemsFactory = $previewOrderItemsFactory;
        $this->resPreviewOrderItemsFactory = $resPreviewOrderItemsFactory;
        $this->colPreviewOrderItemsFactory = $colPreviewOrderItemsFactory;
        $this->colPreviewThreeFactory = $colPreviewThreeFactory;
        $this->emailHelper = $emailHelper;
    }
    public function execute()
    {
        $response = [
            'status'=>'error',
            'message'=>'Can not upload your design',
            '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;
        $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']) : '';
        $oldOwnFolder = 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;
        $isAdminCreateDesign =  isset($params['is_create_design']) ? (int)$params['is_create_design'] : 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 == '' || $oldOwnFolder == '') {
            $response['message'] = 'design not found';
            return $this->jsonFactory->create()->setData($response);
        }
        $ownFolder = $this->cloneDesignFolder($customFolderUpload,$productId,$oldOwnFolder);
        $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()) {
                    if($isAdminCreateDesign == 1) {
                        $dataUpdate = [
//                            'status' => 'design_approved',
                            'custom_item_id' => $previewItem->getId(),
                            'admin_upload_design' => $uploadResponse['base_file'],
                            'admin_upload_status' => 2,
                            'preview_model'=>$ownFolder,
                        ];
                    }
                    else {
                        $dataUpdate = [
//                            'status' => 'design_approved',
                            'custom_item_id' => $previewItem->getId(),
                            'is_new_proof' => 1,
                            'custom_design' => $uploadResponse['base_file'],
                            'preview_model'=>$ownFolder,
                            'updated_at' => date('Y-m-d H:i:s')
                        ];
                    }

                    $updateId = $this->savePreviewOrderItem($dataUpdate);
                }
                $response['status'] = 'success';
                $response['message'] = $uploadResponse;
                $response['own_design'] = $ownFolder;
                $file = $uploadResponse['file_name'];
                $response['base_file'] = $uploadResponse['base_file'];
                $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'] = 'Default Preview Model Not found';
        }
        if($response['status'] == 'success') {
            $this->messageManager->addSuccessMessage(__('You have successfully uploaded the design'));
        }
        else {
            $this->messageManager->addErrorMessage(__('Something wrong when upload design, please check again'));
        }
        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.'/'.$folderPreview,$customFolderUpload,$ownFolder, $ignoreFile);
        return $ownFolder;
    }
    private function copyPreviewModel(
        $sourceDirectory,
        $destinationDirectory,
        $childFolder = '',
        $ignoreFile = ''
    ) {
        $directory = opendir($sourceDirectory);
        /** @var \Magento\Framework\Filesystem $fileSystem*/
        $fileSystem = $this->_objectManager->get('Magento\Framework\Filesystem');
        $mediaDirectory = $fileSystem->getDirectoryWrite('media');

        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;

    }

}
