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

use Magento\Framework\File\Uploader;

class AdvancePreviewUpload
{
    protected $file;
    protected $uploaderFactory;
    public function __construct(
        \Magento\MediaStorage\Model\File\UploaderFactory $uploaderFactory,
        \Magento\Framework\Filesystem\Driver\File $file
    )
    {
        $this->uploaderFactory = $uploaderFactory;
        $this->file = $file;
    }

    public function uploadFileAndGetName($input, $destinationFolder,$subFolder, $data,$option = array())
    {
        try {
            $uploader = $this->uploaderFactory->create(['fileId' => $input]);
            $ext = $uploader->getFileExtension();
            if(isset($option['file_name']) && $option['file_name'] != '')
                $newFileName = $option['file_name'];
            else
                $newFileName = 'image-'.time().'.'.$ext;
            $uploader->setAllowRenameFiles(false);
            $uploader->setFilesDispersion(false);
            $allowTypes = isset($option['allow_type']) ? $option['allow_type'] : array();
            if(count($allowTypes)) {
                $uploader->setAllowedExtensions($allowTypes);
            }
            $result = $uploader->save($destinationFolder,$newFileName);
            //delete old image
            if($result['file'] != '' && isset($data[$input]['value']) && $data[$input]['value'] != '' && $data[$input]['value'] != $result['file'])
            {
                $oldImage = $data[$input]['value'];
                if($subFolder != '')
                    $oldImage = str_replace($subFolder,'',$oldImage);

                if($this->file->isExists($destinationFolder.$oldImage))
                {
                    $this->file->deleteFile($destinationFolder.$oldImage);
                }
            }
            return $result['file'];
        } catch (\Exception $e) {
            if ($e->getCode() != Uploader::TMP_NAME_EMPTY) {
                throw new \Exception($e->getMessage());
            } else {
                $notOldValue = isset($option['not_return']) && $option['not_return'] == 1 ? true : false;
                if (isset($data[$input]['value']) && !$notOldValue) {
                    $fileName = substr($data[$input]['value'],strrpos($data[$input]['value'],'/') + 1);
                    return $fileName;
                }
            }
        }
        return '';
    }
    public function uploadPdfAiFileAndGetName($input, $destinationFolder,$subFolder, $data,$option = array())
    {
        $response = [
            'status'=>'error',
            'message'=>'Can not upload Image',
            'file_name'=>'',
            'base_file'=>'',
        ];
        try {
            $uploader = $this->uploaderFactory->create(['fileId' => $input]);
            $ext = $uploader->getFileExtension();
            if(isset($option['is_convert']) && $option['is_convert'] == 1) {
                $newFileName = 'base-file-'.time().'.'.$ext;
                if(isset($option['original_file_name']) && $option['original_file_name'] != '') {
                    $newFileName = $option['original_file_name'];
                }
            }
            else {
                if(isset($option['file_name']) && $option['file_name'] != '')
                    $newFileName = $option['file_name'];
                else
                    $newFileName = 'image-'.time().'.'.$ext;
            }

            $uploader->setAllowRenameFiles(false);
            $uploader->setFilesDispersion(false);
            $allowTypes = isset($option['allow_type']) ? $option['allow_type'] : array();
            if(count($allowTypes)) {
                $uploader->setAllowedExtensions($allowTypes);
            }
            $result = $uploader->save($destinationFolder,$newFileName);
            //delete old image
            if($result['file'] != '' && isset($data[$input]['value']) && $data[$input]['value'] != '' && $data[$input]['value'] != $result['file'])
            {
                $oldImage = $data[$input]['value'];
                if($subFolder != '')
                    $oldImage = str_replace($subFolder,'',$oldImage);

                if($this->file->isExists($destinationFolder.$oldImage))
                {
                    $this->file->deleteFile($destinationFolder.$oldImage);
                }
            }
            if($result['file'] != '') {
                $response['base_file'] = $result['file'];
                if(isset($option['is_convert']) && $option['is_convert'] == 1) {
                    if(is_file($destinationFolder.$option['file_name'])) {
                        @unlink($destinationFolder.'/'.$option['file_name']);
                    }
                    $convertResponse = $this->convertPdfToImage($destinationFolder,$result['file'] , $option['file_name']);
//                    $response = $convertResponse;
                    if($convertResponse['status'] == 'success') {
                        $response['status'] = 'success';
                        $response['message'] = 'Upload Image and convert success '. $result['file'];
                        $response['file_name'] = $convertResponse['file_name'];

                        if(isset($option['is_remove']) && $option['is_remove'] == 1) {
                            @unlink($destinationFolder.'/'.$result['file']);
                        }
                    }
                }
                else {
                    $response['status'] = 'success';
                    $response['message'] = 'Upload Image success';
                    $response['file_name'] = $result['file'];
                }

            }
//            return $result['file'];
            return $response;
        } catch (\Exception $e) {
            if ($e->getCode() != Uploader::TMP_NAME_EMPTY) {
//                throw new \Exception($e->getMessage());
                $response['message'] = $e->getMessage();
            } else {
                $notOldValue = isset($option['not_return']) && $option['not_return'] == 1 ? true : false;
                if (isset($data[$input]['value']) && !$notOldValue) {
                    $fileName = substr($data[$input]['value'],strrpos($data[$input]['value'],'/') + 1);
                    $response['status'] = 'success';
                    $response['message'] = 'Upload Image success';
                    $response['file_name'] = $fileName;
                }
            }
        }
        return $response;
    }
    protected function convertPdfToImage($destinationFolder, $file, $newFile) {
        $response = [
            'status'=>'error',
            'message'=>'Can not convert File',
            'file_name'=>''
        ];
        try {
            $imagic = new \Imagick();
            $imagic->setResolution(300, 300);
            $imagic->readImage($destinationFolder.'/'.$file.'[0]');
            $imagic->writeImage($destinationFolder.'/'.$newFile);
            $response = [
                'status'=>'success',
                'message'=>'Convert File success',
                'file_name'=>$newFile
            ];
        }
        catch (\Exception $exception) {
            $response['message'] = $exception->getMessage();
        }
        return  $response;
    }
}
