<?php

// BACKEND CONTROLLER WITH MODEL,EVENT-LISTENER

namespace Rvsitebuilder\Wysiwyg\Http\Controllers\Backend;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
//use Rvsitebuilder\Wysiwyg\Events\AfterCommonCreatedEvent;
//use Rvsitebuilder\Wysiwyg\Entities\Common;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\ImageManagerStatic as ImageStatic;
use Lib\Util\RVLog;
use Rvsitebuilder\Wysiwyg\Http\Requests\Deletedocuments;
use Rvsitebuilder\Wysiwyg\Http\Requests\DeletedocumentsRequest;
use Rvsitebuilder\Wysiwyg\Http\Requests\UploadImageCommonRequest;
use Spatie\Image\Image;

class CommonController extends Controller
{
    public function __construct()
    {
        if (false == defined('REAL_PROJECT_PATH')) {
            \define('REAL_PROJECT_PATH', public_path());
        }
        if (false == defined('STORAGE')) {
            \define('STORAGE', 'storage');
        }
        if (false == defined('PROJECT_URL')) {
            \define('PROJECT_URL', url('/'));
        }
        if (false == defined('WEB_THEME_PATH')) {
            \define('WEB_THEME_PATH', public_path('storage'));
        }
    }
    
    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function index(Request $request)
    {
        //buildImagesJson file
        self::_buildImagesJson();
        self::_buildFreeImagesJson();
        self::defacementimage();
        
        if ($request->ajax()) {
            return view('wysiwyg::backend.common.index', compact('commons'))->renderSections()['content'];
        }
        
        return view('wysiwyg::backend.common.index', compact('commons'));
    }
    
    /**
     * Document: Laravel File::
     * https://sonvisal.blogspot.com/2017/03/how-to-use-files-in-laravel.html
     * http://php.net/manual/en/class.splfileinfo.php.
     *
     * @return array[]|bool[]|mixed[]
     */
    public function listdocuments()
    {
        $directory = public_path('storage/documents');
        if (false == is_dir($directory)) {
            File::makeDirectory($directory);
        }
        /*case: directory ไม่ทำ
         $aFolder = File::directories($directory);
         foreach ( $aFolder as $dir) {
         $aFolder = explode('/', $dir);
         $folder = end($aFolder);
         $file = File::allFiles($dir);
         $aFile['dirs'][$folder .'obj'] = $file;
         $aFile['dirs'][$folder] = $file[0]->getFilename();
         }
         */
        
        $obj = [];
        if (true == is_dir($directory)) {
            $aFiles = File::files($directory);
            $aFilesName['files'] = [];
            if (\count($aFiles) > 0) {
                foreach ($aFiles as $k => $file) {
                    $aFilesName['files'][$k] = $file->getFilename();
                    //getFileName
                }
            }
            $obj = json_encode($aFilesName);
        }
        
        $res = [
            'success' => true,
            'documents' => $obj,
        ];
        
        return $res;
    }
    
    public function deletedocuments(DeletedocumentsRequest $request)
    {
        $filename = pathinfo($request->input('fileDeleteName'));
        $directory = public_path('storage/documents');
        $path = $directory.'/'.$filename['basename'];
        //echo $path; exit;
        $isSuccess = false;
        if (File::exists($path)) {
            $isSuccess = File::delete($path);
        }
        
        $res = [
            'success' => $isSuccess,
        ];
        
        return $res;
    }
    
    /**
     * https://laravel.com/docs/5.5/filesystem.
     *
     * @param Request $request
     *
     * @return unknown[]
     */
    public function uploaddocuments(Request $request)
    {
        $upload_success = false;
        $directory = public_path('storage/documents');
        if (false == is_dir($directory)) {
            File::makeDirectory($directory);
        }
        //req object input file
        $aFile = $request->file();
        foreach ($aFile['files'] as $k => $file) {
            //get upload filename
            $fileName = $file->getClientOriginalName();
            //get tmp
            $tmpPath = $file->getPathName();
            //storage/documents
            //$upload_success = Storage::put('documents/' . $fileName, file_get_contents($tmpPath));
            $upload_success = move_uploaded_file($tmpPath, public_path('storage/documents').'/'.$fileName);
        }
        $res = [
            'success' => $upload_success,
        ];
        
        return $res;
    }
    
    public static function _listfiledir($path = '', $ignored = ['wpThumbnails'])
    {
        //iqnore
        //headerbannerorg|headerbanner
        $aFile2 = [];
        //loop dir
        foreach (File::directories($path) as $directory) {
            $aFolder = explode('/', $directory);
            $folder = end($aFolder);
            if (\in_array($folder, $ignored)) { // Ignore thumbs directory
                continue;
            }
            $aFolder = explode('/', $directory);
            $folder = end($aFolder);
            $aFile = File::allFiles($directory);
            foreach ($aFile as $k => $oFile) {
                //echo $oFile->getPath() . '<br>';
                if (preg_match('/wpThumbnails/', $oFile->getPath())) { // Ignore thumbs directory
                    continue;
                }
                $aFile2[$folder][$k] = $oFile->getPathname();
            }
        }
        
        //loop file
        foreach (File::files($path) as $k => $oFile) {
            //echo 'file:: ' . $oFile->getFilename() . '<Br>';
            if (preg_match('/(spacer\.gif|header_banner\.jpg|no\-image\.jpg)$/', $oFile->getFilename())) { // Ignore file
                continue;
            }
            $aFile2[$oFile->getFilename()][$k] = $oFile->getPathname();
        }
        /*
         echo '<br><h2>aFile2</h2><br>';
         print_r($aFile2);
         exit;*/
        return $aFile2;
    }
    
    /**
     * download freeImages.json , parallax.json.
     */
    public static function _buildFreeImagesJson()
    {
        $pathJson = REAL_PROJECT_PATH.\DIRECTORY_SEPARATOR.STORAGE.\DIRECTORY_SEPARATOR.'json';
        RVLog::debug('pathJson: '.$pathJson);
        
        $freepath = $pathJson.'/freeImages.json';
        if (false == File::exists($freepath)) {
            $url = config('rvsitebuildercms.cdn').'/templates/rvs_library/freeImages.json';
            RVLog::debug('url: '.$url);
            $contents = guzzle_get_contents($url);
            file_put_contents($freepath, $contents);
        }
        
        $parallax = $pathJson.'/parallax.json';
        if (false == File::exists($parallax)) {
            $url = config('rvsitebuildercms.cdn').'/templates/rvs_library/parallax.json';
            RVLog::debug('url: '.$url);
            $contents = guzzle_get_contents($url);
            file_put_contents($parallax, $contents);
        }
        
        $freebg = $pathJson.'/freeBackground.json';
        if (false == File::exists($freebg)) {
            $url = config('rvsitebuildercms.cdn').'/templates/rvs_library/freeBackground.json';
            RVLog::debug('url: '.$url);
            $contents = guzzle_get_contents($url);
            file_put_contents($freebg, $contents);
        }
    }
    
    public static function _buildImagesJson()
    {
        RVLog::debug(__FUNCTION__);
        $aData = [];
        $project = REAL_PROJECT_PATH.\DIRECTORY_SEPARATOR.STORAGE;
        $pathJson = REAL_PROJECT_PATH.\DIRECTORY_SEPARATOR.STORAGE.\DIRECTORY_SEPARATOR.'json';
        $urlJson = PROJECT_URL.\DIRECTORY_SEPARATOR.STORAGE.\DIRECTORY_SEPARATOR.'json';
        
        //make json
        if (false == is_dir($pathJson)) {
            File::makeDirectory($pathJson);
        }
        
        $path = REAL_PROJECT_PATH.\DIRECTORY_SEPARATOR.STORAGE.\DIRECTORY_SEPARATOR.'images';
        
        //mkdir images
        if (false == is_dir($path)) {
            File::makeDirectory($path);
        }
        
        if (is_dir($path)) {
            $aFile2 = self::_listfiledir($path);
        } else {
            return false;
        }
        
        $pathMyImagesJson = $pathJson.'/myimages.json';
        $pathStoreImagesJson = $pathJson.'/storeimages.json';
        $pathTagFolderJson = $pathJson.'/tagfolder.json';
        //ถ้ามี json แล้วไม่ต้องทำ
        if (true == is_file($pathMyImagesJson)
            && true == is_file($pathStoreImagesJson)
            && true == is_file($pathTagFolderJson)) {
                //load myimages
                if (preg_match('/var\s*myimages\s*=\s*(\{[\d\D\b\B\w\W]*\});\s*$/ims', file_get_contents($pathMyImagesJson), $match)) {
                    $aData = json_decode($match[1], true);
                }
                
                //load storeimages
                if (preg_match('/var\s*storeimages\s*=\s*(\{[\d\D\b\B\w\W]*\});\s*$/ims', file_get_contents($pathStoreImagesJson), $match)) {
                    $aStore = json_decode($match[1], true);
                }
                
                //load tagfolder (ตอนนี้ fix)
                $aFolderJson = ['All Images', 'Facebook'];
                
                $aResponse = [
                    'success' => true,
                    'msg' => 'Have json file exist.',
                    'json' => ['myimages_url' => $urlJson.'/myimages.json', 'storeimages_url' => $urlJson.'/storeimages.json', 'tagfolder_url' => $urlJson.'/tagfolder.json'], 'myimages' => $aData, 'storeimages' => $aStore, 'tagfolder' => $aFolderJson,
                ];
                /*
                 echo '<pre>have json:';
                 echo 'aData<br>';
                 print_r($aData);
                 echo 'aData<br>';
                 print_r($aStore);
                 echo 'aFolderJson<br>';
                 print_r($aFolderJson);
                 exit;
                 */
                return $aResponse;
            }
            /*
             echo '<pre>no json:';
             echo $path .'<br>';
             print_r($aFile2);
             */
            //exit;
            
            $aData = [];
            $i = '1';
            foreach ($aFile2 as $folde => $aFile) {
                foreach ($aFile as $filePath) {
                    [$width, $height] = getimagesize($filePath);
                    $size = filesize($filePath);
                    $date = filemtime($filePath);
                    $aPath = explode('/', $filePath);
                    $name = end($aPath);
                    if ('spacer.gif' == $name) {
                        //ไม่ต้องแสดง spacer.gif
                        continue;
                    }
                    
                    $nameThumb = 'wpThumbnails/'.$name;
                    $file = str_replace($project.'/', '', $filePath);
                    $imgSaveTarget = str_replace($name, $nameThumb, $filePath);
                    $folderThumb = str_replace($name, 'wpThumbnails', $filePath);
                    
                    if (false == is_dir($folderThumb)) {
                        File::makeDirectory($folderThumb);
                    }
                    //echo $folderThumb. ' +++<br>'; exit;
                    $imgSave = $filePath;
                    $skipmakeThumb = false;
                    if (false == is_file($imgSaveTarget) && ($width > 5000 || $height > 5000)) {
                        $source = WEB_THEME_PATH.'/themes/default/sitebuilderv5/images/noimage.jpg';
                        copy($source, $imgSaveTarget);
                        $skipmakeThumb = true;
                    }
                    
                    //case: รูปไม่ใหญ่มาก และยังไม่มี Thumbnail
                    if (false == $skipmakeThumb && false == is_file($imgSaveTarget)) {
                        //process time out
                        //TODO: makeThumb
                        //$res = RvsLibs_Image2::makeThumb($imgSave, $imgSaveTarget, 120, 0,'gray',100);
                        Image::load($imgSave)
                        ->width(120)
                        ->height(120)
                        ->save($imgSaveTarget);
                    }
                    
                    $aData['img_'.$i] = [
                        'tagFolder' => '', 'tag' => '', 'solution' => $width.'x'.$height, 'size' => $size, 'date' => $date,
                    ];
                    $aStore['img_'.$i] = ['path' => $file, 'name' => $name];
                    
                    ++$i;
                }
            }
            //default
            $aFolderJson = ['All Images', 'Facebook'];
            
            $aData = (empty($aData)) ? '{}' : json_encode($aData);
            $aStore = (false == isset($aStore)) ? '{}' : json_encode($aStore);
            $strFolder = (false == isset($aFolderJson)) ? '{}' : json_encode($aFolderJson);
            
            $strData = 'var myimages = '.$aData.';';
            $strStore = 'var storeimages = '.$aStore.';';
            $strFolder = 'var tagfolder = '.$strFolder.';';
            //echo $strData;
            if (false == is_file($pathMyImagesJson)) {
                file_put_contents($pathMyImagesJson, $strData);
            }
            //echo $strData;exit;
            
            if (false == is_file($pathStoreImagesJson)) {
                file_put_contents($pathStoreImagesJson, $strStore);
            }
            
            if (false == is_file($pathTagFolderJson)) {
                file_put_contents($pathTagFolderJson, $strFolder);
            }
            
            $aResponse = [
                'success' => true,
                'msg' => 'success.',
                'json' => ['myimages_url' => $urlJson.'/myimages.json', 'storeimages_url' => $urlJson.'/storeimages.json', 'tagfolder_url' => $urlJson.'/tagfolder.json'], 'myimages' => $aData, 'storeimages' => $aStore, 'tagfolder' => $aFolderJson,
            ];
            //return $aResponse;
    }
    
    public function addtagfolder(Request $request)
    {
        $strFolder = null;
        $nTagfolder = $request->input('tagname');
        
        $pathJson = REAL_PROJECT_PATH.\DIRECTORY_SEPARATOR.STORAGE.\DIRECTORY_SEPARATOR.'json';
        $pathTagFolderJson = $pathJson.'/tagfolder.json';
        $tagfolderJson = file_get_contents($pathTagFolderJson);
        
        if (preg_match('/var\s*tagfolder\s*=\s*(\[[\d\D\b\B\w\W]*\]);\s*$/ims', $tagfolderJson, $match)) {
            $aFolder = json_decode($match[1], true);
        }
        
        array_push($aFolder, $nTagfolder);
        
        $strFolder = 'var tagfolder = '.json_encode($aFolder).';';
        if (null != $aFolder) {
            file_put_contents($pathTagFolderJson, $strFolder);
        }
        
        end($aFolder);
        $keyArray = key($aFolder);
        
        $aResponse = [
            'success' => true,
            'msg' => 'Update data success.',
            'key' => $keyArray,
            'tagname' => $nTagfolder,
            'tagfolder' => $aFolder,
        ];
        
        return $aResponse;
    }
    
    public function deletetagfolder(Request $request)
    {
        $tagfolderName = $request->input('tagfolderName');
        $keyTag = $request->input('tagKey');
        
        $pathJson = REAL_PROJECT_PATH.\DIRECTORY_SEPARATOR.STORAGE.\DIRECTORY_SEPARATOR.'json';
        
        $pathTagFolderJson = $pathJson.'/tagfolder.json';
        $tagfolderJson = file_get_contents($pathTagFolderJson);
        $pathIsDefact = $pathJson.'/isdefact.txt';
        
        //load tagfolder
        if (preg_match('/var\s*tagfolder\s*=\s*(\[[\d\D\b\B\w\W]*\]);\s*$/ims', $tagfolderJson, $match)) {
            $aFolder = json_decode($match[1], true);
        }
        
        //delete
        unset($aFolder[$keyTag]);
        
        $aFolderValue = array_values($aFolder);
        $strFolder = 'var tagfolder = '.json_encode(array_values($aFolder)).';';
        
        //write file
        file_put_contents($pathTagFolderJson, $strFolder);
        
        $aResponse = [
            'success' => true,
            'msg' => 'Update data success.',
            'tagName' => $tagfolderName,
            'key' => $keyTag,
            'strFolder' => $strFolder,
            'aFolderValue' => $aFolderValue,
        ];
        
        return $aResponse;
    }
    
    public function addtagImage(Request $request)
    {
        $imageKey = $request->input('imageKey');
        $tag = $request->input('tag');
        $solution = $request->input('solution');
        $size = $request->input('size');
        $date = $request->input('date');
        $tagfolderID = $request->input('tagfolderID');
        $override = $request->input('override');
        
        $pathJson = REAL_PROJECT_PATH.'/'.STORAGE.'/json';
        $pathMyImagesJson = $pathJson.'/myimages.json';
        $pathIsDefact = $pathJson.'/isdefact.txt';
        
        $filePath = ('true' == $override)
        ? REAL_PROJECT_PATH.'/'.STORAGE.'/images/'.$imageKey
        : $this->_chkImageName(REAL_PROJECT_PATH.'/'.STORAGE.'/images/'.$imageKey);
        
        $aMyImageJson = [];
        $aMyImageJson[$imageKey] = [
            'tagFolder' => $tagfolderID,
            'tag' => '',
            'solution' => $solution,
            'size' => $size,
            'date' => $date,
        ];
        
        $rowMyimage = json_encode($aMyImageJson);
        $pat = '/^\{"'.$imageKey.'":/';
        $rowMyimage = preg_replace($pat, '', $rowMyimage);
        $rowMyimage = preg_replace('/\}$/', ';', $rowMyimage);
        $rowMyimage = 'myimages["'.$imageKey.'"]='.$rowMyimage;
        
        //write content to the end of a file.
        File::append($pathMyImagesJson, $rowMyimage);
        
        //open file isdefact.tx
        $IsDefact = '';
        //write file
        file_put_contents($pathIsDefact, $IsDefact);
        
        $aResponse = [
            'success' => true,
            'myimage' => $rowMyimage,
            'imageKey' => $imageKey,
            'tagFolder' => $tagfolderID,
            'solution' => $solution,
            'size' => $size,
            'date' => $date,
        ];
        
        return $aResponse;
    }
    
    public function addtagImageMulti(Request $request)
    {
        $imageKey = $request->input('imageKey');
        $tagfolder = $request->input('tagfolder');
        
        $pathJson = REAL_PROJECT_PATH.'/'.STORAGE.'/json';
        $pathMyImagesJson = $pathJson.'/myimages.json';
        $pathTagFolderJson = $pathJson.'/tagfolder.json';
        $tagfolderJson = file_get_contents($pathTagFolderJson);
        $MyImagesJson = file_get_contents($pathMyImagesJson);
        $pathIsDefact = $pathJson.'/isdefact.txt';
        
        if (preg_match('/var\s*myimages\s*=\s*(\{[\d\D\b\B\w\W]*\}\});/ims', $MyImagesJson, $match)) {
            $aData = json_decode($match[1], true);
        }
        
        if (preg_match('/var\s*tagfolder\s*=\s*(\[[\d\D\b\B\w\W]*\]);\s*$/ims', $tagfolderJson, $match)) {
            $aFolder = json_decode($match[1], true);
        }
        
        //$aimgKey = explode(",",$imageKey);
        $aimgKey = $imageKey;
        
        //Update Tagname Myimages
        foreach ($aimgKey as $img_key) {
            foreach ($aData as $key => $x_key) {
                if ($key == $img_key) {
                    $aMyImageJson = [];
                    $aMyImageJson[$key] = [
                        'tagFolder' => $tagfolder,
                        'tag' => '',
                        'solution' => $x_key['solution'],
                        'size' => $x_key['size'],
                        'date' => $x_key['date'],
                    ];
                    
                    $rowMyimage = json_encode($aMyImageJson);
                    $pat = '/^\{"'.$key.'":/';
                    $rowMyimage = preg_replace($pat, '', $rowMyimage);
                    $rowMyimage = preg_replace('/\}$/', ';', $rowMyimage);
                    $rowMyimage = 'myimages["'.$key.'"]='.$rowMyimage;
                    
                    //write content to the end of a file.
                    File::append($pathMyImagesJson, $rowMyimage);
                }
                
                $IsDefact = '';
                //write file
                file_put_contents($pathIsDefact, '');
            }
        }
        
        $aResponse = [
            'success' => true,
        ];
        
        return $aResponse;
    }
    
    public function updatetagfolder(Request $request)
    {
        $pathJson = REAL_PROJECT_PATH.'/'.STORAGE.'/json';
        $pathMyImagesJson = $pathJson.'/myimages.json';
        $pathTagFolderJson = $pathJson.'/tagfolder.json';
        $tagfolderJson = file_get_contents($pathTagFolderJson);
        $MyImagesJson = file_get_contents($pathMyImagesJson);
        $pathIsDefact = $pathJson.'/isdefact.txt';
        
        if (preg_match('/var\s*myimages\s*=\s*(\{[\d\D\b\B\w\W]*\}\});/ims', $MyImagesJson, $match)) {
            $aData = json_decode($match[1], true);
        }
        
        if (preg_match('/var\s*tagfolder\s*=\s*(\[[\d\D\b\B\w\W]*\]);\s*$/ims', $tagfolderJson, $match)) {
            $aFolder = json_decode($match[1], true);
        }
        
        $befor = $request->input('befortag');
        $newTag = $request->input('tagname');
        $keyTag = $request->input('keytag');
        $imgKey = $request->input('imgKey');
        
        //$aimgKey = explode(",",$imgKey);
        $aimgKey = $imgKey;
        $nMyImageJson = [];
        
        if (\count($aimgKey) > 0) {
            //Update Tagname Myimages
            foreach ($aimgKey as $img_key) {
                foreach ($aData as $key => $x_key) {
                    if ($key == $img_key) {
                        $nMyImageJson[$key] = [];
                        $aMyImageJson = [];
                        $aMyImageJson[$key] = [
                            'tagFolder' => $newTag,
                            'tag' => '',
                            'solution' => $x_key['solution'],
                            'size' => $x_key['size'],
                            'date' => $x_key['date'],
                        ];
                        
                        $rowMyimage = json_encode($aMyImageJson);
                        $pat = '/^\{"'.$key.'":/';
                        $rowMyimage = preg_replace($pat, '', $rowMyimage);
                        $rowMyimage = preg_replace('/\}$/', ';', $rowMyimage);
                        $rowMyimage = 'myimages["'.$key.'"]='.$rowMyimage;
                        
                        //write content to the end of a file.
                        File::append($pathMyImagesJson, $rowMyimage);
                    }
                }
            }
        }
        
        //update Tagfolder
        $aFolder[$keyTag] = $newTag;
        $strFolder = 'var tagfolder = '.json_encode($aFolder).';';
        //write file
        file_put_contents($pathTagFolderJson, $strFolder);
        
        $akey = array_keys($nMyImageJson);
        
        $aResponse = [
            'success' => true,
            'key' => $keyTag,
            'ntagfolder' => $newTag,
            'btagfolder' => $befor,
            'tagfolder' => $aFolder,
            'akey' => $akey,
        ];
        
        return $aResponse;
    }
    
    public function _chkImageName($path, $index = '')
    {
        $name = basename($path);
        $name = preg_replace('/rvcopy_(.*)\./ims', '.', $name);
        $name = str_replace('.jpg', 'rvcopy_'.time().'.jpg', $name);
        $path = str_replace(basename($path), $name, $path);
        
        return $path;
    }
    
    public function buildimagesjson(Request $request)
    {
        RVLog::debug(__FUNCTION__);
        //buildImagesJson file
        self::_buildImagesJson();
        self::_buildFreeImagesJson();
    }
    
    public function defacementimage()
    {
        $pathMyImagesJson = public_path('storage/json/myimages.json');
        $pathStoreImagesJson = public_path('storage/json/storeimages.json');
        $pathTagFolderJson = public_path('storage/json/tagfolder.json');
        $pathIsDefact = public_path('storage/json/isdefact.txt');
        
        $myImageJson = file_get_contents($pathMyImagesJson);
        $storeimagesJson = file_get_contents($pathStoreImagesJson);
        $tagfolderJson = file_get_contents($pathTagFolderJson);
        $aMyImageJson = $this->defacementMyImageJSontoArray($myImageJson);
        $aStoreimagesJson = $this->defacementMyImageJSontoArray($storeimagesJson);
        $aTagfolderJson = $this->defacementMyImageJSontoArray($tagfolderJson);
        $aMyImageJson = (empty($aMyImageJson)) ? '{}' : json_encode($aMyImageJson);
        $aStoreimagesJson = (empty($aStoreimagesJson)) ? '{}' : json_encode($aStoreimagesJson);
        $aTagfolderJson = (empty($aTagfolderJson)) ? '{}' : json_encode($aTagfolderJson);
        
        $strData = 'var myimages = '.$aMyImageJson.';';
        $strStore = 'var storeimages = '.$aStoreimagesJson.';';
        $strFolder = 'var tagfolder = '.$aTagfolderJson.';';
        //file_put_contents ( $pathMyImagesJson, $strData );
        //file_put_contents ( $pathStoreImagesJson, $strStore );
        //file_put_contents ( $pathTagFolderJson, $strFolder );
        
        file_put_contents($pathMyImagesJson, $strData);
        file_put_contents($pathStoreImagesJson, $strStore);
        file_put_contents($pathTagFolderJson, $strFolder);
        
        if (File::exists($pathIsDefact)) {
            File::delete($pathIsDefact);
        }
        
        $response = [
            'success' => true,
            'msg' => 'success.',
        ];
        
        return $response;
    }
    
    public function deleteimage(Request $request)
    {
        $response = [
            'status' => 'fail',
            'msg' => '',
            'debug_msg' => '',
        ];
        $isremove = false;
        $imageName = $request->input('imageName');
        $imageKey = $request->input('imageKey');
        $imagePath = $request->input('imagePath');
        
        $pathFreeImagesJson = public_path('storage/json/freeImages.json');
        $pathMyImagesJson = public_path('storage/json/myimages.json');
        $pathStoreImagesJson = public_path('storage/json/storeimages.json');
        $pathTagFolderJson = public_path('storage/json/tagfolder.json');
        $pathIsDefact = public_path('storage/json/isdefact.txt');
        
        $pathImageName = public_path('storage/images/'.$imageName);
        
        $pathImageNameThumb = public_path('storage/images/wpThumbnails/'.$imageName);
        
        $rowDeleteMyimage = 'delete myimages["'.$imageKey.'"];';
        $rowDeleteStoreImage = 'delete storeimages["'.$imageKey.'"];';
        
        if (File::exists($pathImageName)) {
            $isremove = File::delete($pathImageName);
        }
        
        if (File::exists($pathImageNameThumb)) {
            $isremoveThumb = File::delete($pathImageNameThumb);
        }
        
        //file_put_contents FILE_APPEND not work
        //file_put_contents($pathMyImagesJson, $rowDeleteMyimage, FILE_APPEND);
        //file_put_contents($pathStoreImagesJson, $rowDeleteStoreImage, FILE_APPEND);
        file_put_contents($pathStoreImagesJson, $rowDeleteStoreImage, FILE_APPEND);
        file_put_contents($pathMyImagesJson, $rowDeleteMyimage, FILE_APPEND);
        file_put_contents($pathIsDefact, '');
        
        $response = [
            'success' => $isremove,
            'msg' => 'status '.$isremove,
            'imageKey' => $imageKey,
            'imageName' => $imageName,
        ];
        
        return response()->json($response);
    }
    
    public function _getFileName($path, $name)
    {
        $pFilename = $path.$name;
        $a = pathinfo($pFilename);
        $a['basename'] = preg_replace('#\?.*#is', '', $a['basename']);
        $a['extension'] = preg_replace('#\?.*#is', '', $a['extension']);
        $a['filename'] = preg_replace('#\_copy\_.*#is', '', $a['filename']);
        
        $name = $a['filename'].'.'.$a['extension'];
        if (File::exists($pFilename)) {
            RVLog::debug('have'.$pFilename);
            
            $newName = $a['filename'].'_copy_'.time().'_.'.$a['extension'];
            
            return self::_getFileName($path, $newName);
        }
        
        return $name;
    }
    
    public function getUploadMaxSize()
    {
        if (is_numeric($postMaxSize = ini_get('upload_max_filesize'))) {
            return (int) $postMaxSize;
        }
        
        $metric = strtoupper(substr($postMaxSize, -1));
        $postMaxSize = (int) $postMaxSize;
        
        switch ($metric) {
            case 'K':
                return $postMaxSize * 1024;
            case 'M':
                return $postMaxSize * 1048576;
            case 'G':
                return $postMaxSize * 1073741824;
            default:
                return $postMaxSize;
        }
    }
    
    public function formatBytes($bytes, $precision = 2)
    {
        $unit = ['B', 'KB', 'MB', 'GB'];
        $exp = floor(log($bytes, 1024)) | 0;
        
        return round($bytes / (pow(1024, $exp)), $precision).$unit[$exp];
    }
    
    public function uploadimage(UploadImageCommonRequest $request)
    {
        $aFile = $request->file('files');
        $id = $request->input('id');
        $realFilename = $request->input('filename');
        
        $filename = $id.'.'.$aFile[0]->getClientOriginalExtension();
        $filename = $aFile[0]->getClientOriginalName();
        // echo $filename;
        
        if (!$aFile[0]->getPathname()) {
            $serverFileMax = $this->getUploadMaxSize();
            $str = 'Uploaded file size is '.$this->formatBytes($serverFileMax).' larger than maximum allow size ';
            $response = [
                'status' => 'error',
                'message' => $str,
                'debug_msg' => '',
                'id' => $id,
            ];
            
            return response()->json($response);
        }
        
        $filename = $realFilename
        ? $this->_getFileName(public_path('storage/images/'), $realFilename)
        : $filename = $this->_getFileName(public_path('storage/images/'), $filename);
        
        //echo $filename;exit;
        
        //save orginal image but not width more than 2500px
        if (![$width,$high] = @getimagesize($aFile[0])) {
            return response()->json(['status' => 'error', 'message' => 'Image too large.', 'id' => $id]);
        }
        
        $img = ImageStatic::make($aFile[0]->getRealPath());
        if ($width > 2500) {
            $img->resize(2500, null, function ($constraint) { $constraint->aspectRatio(); });
        }
        //echo $img;
        
        $img->save(config('filesystems.disks.wys_upload_img_original.root').'/'.$filename, 100);
        //print_r($img->dirname.'/'.$img->basename);
        
        //save thumb image
        $img = ImageStatic::make($aFile[0]->getRealPath());
        $img->resize(120, null, function ($constraint) { $constraint->aspectRatio(); });
        $img->save(config('filesystems.disks.wys_upload_img_thumb.root').'/'.$filename, 100);
        //print_r($img->dirname.'/'.$img->basename);
        $pathImage = public_path('storage/images/'.$filename);
        
        $image_url = url('/storage/images/'.$filename);
        $image_thumbnail_url = url('storage/images/wpThumbnails/'.$filename);
        $id = $request->input('id');
        
        $aImageJSON = $this->updateImageJSON($pathImage, $id);
        
        $response = [
            'status' => 'success',
            'message' => '',
            'debug_msg' => '',
            'url' => $image_url,
            'thumb' => $image_thumbnail_url,
            'id' => $id,
            'name' => basename($pathImage),
        ];
        if (!empty($aImageJSON)) {
            $response = array_merge($response, $aImageJSON);
        }
        
        return response()->json($response);
    }
    
    public function updateImageJSON($pathImage, $id)
    {
        $pathFreeImagesJson = public_path('storage/json/freeImages.json');
        $pathMyImagesJson = public_path('storage/json/myimages.json');
        $pathStoreImagesJson = public_path('storage/json/storeimages.json');
        $pathTagFolderJson = public_path('storage/json/tagfolder.json');
        $pathIsDefact = public_path('storage/json/isdefact.txt');
        
        $pathImg = public_path('storage/images');
        $aMyImageJson = [];
        $aStoreimagesJson = [];
        $aTagfolderJson = [];
        $size = filesize($pathImage);
        $date = filemtime($pathImage);
        $aName = explode('/', $pathImage);
        $name = $aName[\count($aName) - 1];
        $imageName = $id;
        // echo $imageName;exit;
        $tagFolder = ''; // uploads
        
        [$width, $height] = getimagesize($pathImage);
        
        $aMyImageJson[$imageName] = [
            'tagFolder' => $tagFolder,
            'tag' => '',
            'solution' => $width.'x'.$height,
            'size' => $size,
            'date' => $date,
        ];
        
        $aStoreimagesJson[$imageName] = [
            'path' => 'images/'.$name,
            'name' => $name,
        ];
        $rowMyimage = json_encode($aMyImageJson, true);
        // echo $rowMyimage;exit;
        $pat = '/^\{"'.$imageName.'":/';
        $rowMyimage = preg_replace($pat, '', $rowMyimage);
        $rowMyimage = preg_replace('/\}$/', ';', $rowMyimage);
        $rowMyimage = 'myimages["'.$imageName.'"]='.$rowMyimage;
        // echo 'asdf';exit;
        $rowStore = json_encode($aStoreimagesJson);
        $rowStore = preg_replace($pat, '', $rowStore);
        $rowStore = preg_replace('/\}$/', ';', $rowStore);
        $rowStore = 'storeimages["'.$imageName.'"]='.$rowStore;
        
        $handle = fopen($pathMyImagesJson, 'a+');
        fwrite($handle, $rowMyimage);
        fclose($handle);
        
        $handle = fopen($pathStoreImagesJson, 'a+');
        fwrite($handle, $rowStore);
        fclose($handle);
        
        $handle = fopen($pathIsDefact, 'a+');
        fwrite($handle, '');
        fclose($handle);
        
        $response = [
            'myimages' => $aMyImageJson,
            'storeimages' => $aStoreimagesJson,
        ];
        
        return $response;
    }
    
    public function saveimage(Request $request)
    {
        $response = [
            'status' => 'fail',
            'msg' => '',
            'debug_msg' => '',
        ];
        $imgdata = $request->input('data');
        $imgthumnaildata = $request->input('thumnail');
        $imageURL = $request->input('imageURL');
        $override = $request->input('override');
        $imageName = $request->input('imageName');
        $imageType = $request->input('imageType');
        $tagFolder = $request->input('tagFolder');
        // echo $imageName;
        $imageName = preg_replace('#\?.*#is', '', $imageName);
        
        //use base_path.'public_html'
        
        $pathFreeImagesJson = public_path('storage/json/freeImages.json');
        $pathMyImagesJson = public_path('storage/json/myimages.json');
        $pathStoreImagesJson = public_path('storage/json/storeimages.json');
        $pathTagFolderJson = public_path('storage/json/tagfolder.json');
        $pathIsDefact = public_path('storage/json/isdefact.txt');
        
        $pathImg = public_path('storage/images');
        
        $aMyImageJson = [];
        $aStoreimagesJson = [];
        $aTagfolderJson = [];
        
        //make image folder
        if (false == is_dir($pathImg)) {
            File::makeDirectory($pathImg);
        }
        
        if ('true' == $override) {
            $pathImage = public_path('storage/images/'.$imageName);
        } else {
            $imageName = $this->_getFileName(public_path('storage/images/'), $imageName);
            $pathImage = public_path('storage/images/'.$imageName);
        }
        
        RVLog::debug(__FUNCTION__.':'.$pathImage);
        
        $img = explode(',', $imgdata);
        $fileData = base64_decode($img[1]);
        
        file_put_contents($pathImage, $fileData);
        
        $folderThumb = public_path('storage/images/wpThumbnails');
        if (false == is_dir($folderThumb)) {
            //mkDir(array('-p', $folderThumb));
            File::makeDirectory($folderThumb);
        }
        $thumnailPath = $folderThumb.'/'.$imageName;
        
        $thumnail = explode(',', $imgthumnaildata);
        $thumnailData = base64_decode($thumnail[1]);
        //echo $thumnailData;exit;
        file_put_contents($thumnailPath, $thumnailData);
        
        if ($tagFolder) {
            if (!\in_array($tagFolder, $aTagfolderJson)) {
                // $aTagfolderJson[count($tagfolderJson)] = $input->tagFolder;
                array_push($aTagfolderJson, $tagFolder);
            }
        } else {
            $tagFolder = '';
        }
        
        // echo $override;exit;
        if ('false' == $override) {
            $i = time();
            $imageName = 'img_'.$i;
            $storeImageJson = file_get_contents($pathStoreImagesJson);
            
            $storeImageJson = $this->defacementMyImageJSontoArray($storeImageJson);
            //	print_r($aStoreimagesJson);
        } else {
            $storeImageJson = file_get_contents($pathStoreImagesJson);
            //echo $input->imageName
            $imageNameDef = str_replace('.', "\.", $imageName);
            
            //ใส่ ?: ไม่ต้อง return ค่า
            //match หา key img
            // input storeimages["img_1537945441"]={"path":"images\/1537945439891.png","name":"1537945439891.png"};
            
            $pat = '/"img_([0-9]+?)"(?:.{0,1})(?:=|:)\{"(?:path|name)":"[a-z0-9_\/\\\-]+?'.$imageNameDef.'"/im';
            //echo $storeImageJson;
            preg_match($pat, $storeImageJson, $matches);
            $i = (isset($matches[1])) ? $matches[1] : time();
            if (isset($matches[1])) {
                $i = $matches[1];
            } else {
                $i = time();
                $override = false;
            }
            $imageName = 'img_'.$i;
        }
        [$width, $height] = getimagesize($pathImage);
        
        $size = filesize($pathImage);
        $date = filemtime($pathImage);
        $aName = explode('/', $pathImage);
        $name = $aName[\count($aName) - 1];
        
        // $file = str_replace ( $input->project_id . '/', '', $filePath );
        // $pathToStore = $file;
        $aMyImageJson[$imageName] = [
            'tagFolder' => $tagFolder,
            'tag' => '',
            'solution' => $width.'x'.$height,
            'size' => $size,
            'date' => $date,
        ];
        
        $aStoreimagesJson[$imageName] = [
            // 'path' => $pathImage,
            'path' => 'images/'.$name,
            'name' => $name,
        ];
        
        // $strData = "var myimages = " . SGL_AjaxProvider::jsonEncode($aMyImageJson) . ";";
        // $strStore = "var storeimages = " . SGL_AjaxProvider::jsonEncode($aStoreimagesJson) . ";";
        // file_put_contents($pathMyImagesJson, $strData);
        // file_put_contents($pathStoreImagesJson, $strStore);
        
        // echo json_encode($aMyImageJson);exit;
        
        $rowMyimage = json_encode($aMyImageJson, true);
        // echo $rowMyimage;exit;
        $pat = '/^\{"'.$imageName.'":/';
        $rowMyimage = preg_replace($pat, '', $rowMyimage);
        $rowMyimage = preg_replace('/\}$/', ';', $rowMyimage);
        $rowMyimage = 'myimages["'.$imageName.'"]='.$rowMyimage;
        // echo 'asdf';exit;
        $rowStore = json_encode($aStoreimagesJson);
        $rowStore = preg_replace($pat, '', $rowStore);
        $rowStore = preg_replace('/\}$/', ';', $rowStore);
        $rowStore = 'storeimages["'.$imageName.'"]='.$rowStore;
        
        if ('true' == $override) {
            // $rowDeleteMyimage = 'delete myimages["'.$imageName.'"];';
            // $rowDeleteStoreImage = 'delete storeimages["'.$imageName.'"];';
            // file_put_contents ( $pathMyImagesJson, $rowDeleteMyimage, FILE_APPEND );
            // file_put_contents ( $pathStoreImagesJson, $rowDeleteStoreImage, FILE_APPEND );
        }
        
        $handle = fopen($pathMyImagesJson, 'a+');
        fwrite($handle, $rowMyimage);
        fclose($handle);
        
        $handle = fopen($pathStoreImagesJson, 'a+');
        fwrite($handle, $rowStore);
        fclose($handle);
        
        $handle = fopen($pathIsDefact, 'a+');
        fwrite($handle, '');
        fclose($handle);
        
        $image_url = url('/storage/images/'.basename($pathImage));
        $image_thumbnail_url = url('storage/images/wpThumbnails/'.basename($pathImage));
        
        //RVLog::debug(__FUNCTION__ . ':' . $image_url);
        //RVLog::debug(__FUNCTION__ . ':' . $image_thumbnail_url);
        $version = '?v='.md5_file($thumnailPath);
        RVLog::debug(__FUNCTION__.'thumnailPath:'.$image_thumbnail_url.$version);
        $id = str_replace('img_', '', $imageName);
        // echo $image_url;exit;
        $response = [
            'success' => true,
            'msg' => 'success.',
            'override' => $override,
            //'src' => $pathImage,
            'src' => $image_url,
            'thumnail' => $thumnailPath,
            'thumnail_url' => $image_thumbnail_url.$version,
            'name' => basename($pathImage),
            'myimages' => $aMyImageJson,
            'storeimages' => $aStoreimagesJson,
            'tagfolder' => $aTagfolderJson,
            'imagekey' => $imageName,
            'id' => $id,
        ];
        
        return response()->json($response);
    }
    
    public function defacementMyImageJSontoArray($data)
    {
        // case remove file myimage
        
        $pat = '/delete[^;](?:(?:myimages)|(?:storeimages))\[\"([^;]*)\"\];/is';
        $data = preg_replace_callback($pat, function ($match) {
            $GLOBALS['deleteJSonMyImage'][$match[1]] = true;
            
            return '';
        }, $data);
            
            $pat = '/null/is';
            $data = preg_replace($pat, '{}', $data);
            // case add image file
            $pat = '/\}\}\;/is';
            $data = preg_replace($pat, '},', $data);
            //echo $data;
            $pat = '/\}\;/is';
            $data = preg_replace($pat, '},', $data);
            
            $pat = '/(?:(?:myimages)|(?:storeimages)|(?:tagfolder))\[(.*?)\]/is';
            $data = preg_replace($pat, '$1:', $data);
            //echo $data;
            $pat = '/\,$/is';
            $data = preg_replace($pat, '};', $data);
            //echo $data;exit;
            $pat = '/(?:var ((?:myimages)|(?:storeimages)|(?:tagfolder)) =)|(?:\;)|[\=]/is';
            $data = preg_replace($pat, '', $data);
            //echo $data;
            // 		$pat = '/\;$/';
            // 		if (!preg_match ( $pat, $data)) {
            // 		//$data .= ';';
            
            // 		}
            
            $pat = '/\"\{\}\"/is';
            $data = preg_replace($pat, '{', $data);
            
            $data = json_decode($data);
            
            if (empty($data)) {
                return [];
            }
            
            if (isset($GLOBALS['deleteJSonMyImage'])) {
                foreach ($GLOBALS['deleteJSonMyImage'] as $key => $val) {
                    unset($data->{$key});
                }
            }
            
            unset($GLOBALS['deleteJSonMyImage']);
            
            return $data;
    }
    
    /**
     * Update the specified resource in storage.
     *
     * @param Request $request
     * @param mixed   $itemid
     *
     * @return Response
     */
    public function update(Request $request, $itemid)
    {
        $response = [
            'status' => 'fail',
            'msg' => '',
            'debug_msg' => '',
        ];
        
        $common = Common::find($itemid);
        
        if ($common) {
            $common->save();
        }
        
        $response = [
            'status' => 'success',
            'msg' => 'The item has update.',
            //'debug_msg' => $debug_msg
        ];
        
        return response()->json($response);
    }
    
    /**
     * Remove the specified resource from storage.
     *
     * @param mixed $itemid
     *
     * @return Response
     */
    public function destroy($itemid)
    {
        $response = [
            'status' => 'fail',
            'msg' => '',
            'debug_msg' => '',
        ];
        
        $common = Common::find($itemid);
        
        if ($common) {
            $common->delete();
        }
        
        $response = [
            'status' => 'success',
            'msg' => 'The item has delete.'.$itemid,
            //'debug_msg' => $debug_msg
        ];
        
        return response()->json($response);
    }
    
    /**
     * gen thumbnail cdn จะเปิดใช้กรณีมีการเพิ่มรูปเข้ามาใหม่และต้องการ gen thumnail //P'Tum Apiruk.
     */
    public static function _genThumbnail()
    {
        $url = config('rvsitebuildercms.cdn').'/templates/rvs_library/freeBackground.json';
        
        $cdn_json = guzzle_get_contents($url);
        $var = 'aFreeBackground';
        
        if (preg_match('/\s*var\s*'.$var.'\s*=\s*(\{[\d\D\b\B\w\W]*\});\s*$/ims', $cdn_json, $match)) {
            $cdn_json = json_decode($match[1], true);
        }
        
        $path = public_path('cdn').'/templates/rvs_library/freebackground/';
        foreach ($cdn_json['bggroup'] as $key => $value) {
            echo $key;
            foreach ($value as $k => $v) {
                $path_img = $path.$key.'/'.$k;
                $type_img = $v['type'];
                $folderThumb = $path_img.'/wpThumbnails';
                echo $k.'<hr />';
                if (false == is_dir($folderThumb)) {
                    //mkDir(array('-p', $folderThumb));
                    File::makeDirectory($folderThumb);
                }
                
                foreach ($v['image'] as $v_img) {
                    $img_file = $path_img.'/'.$v_img.'.'.$type_img;
                    $thumb_file = $folderThumb.'/'.$v_img.'.'.$type_img;
                    echo  $img_file.': success <br >';
                    
                    //TODO: makeThumb
                    
                    Image::load($img_file)
                    ->width(120)
                    ->height(120)
                    ->save($thumb_file);
                }
            }
        }
    }
}
