<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Intervention\Image\ImageManagerStatic as Image;
use App\Models\GrantProject;
use File;

class PhotoController extends Controller
{
    public $allowedMimeType = array('image/png', 'image/jpeg', 'image/jpg', 'image/gif');

    public function upload(Request $request)
    {
        $subdomain = explode('.', $request->server('HTTP_HOST'));
        $result = "";         // response photo path
        // dd($request->input('upload'));
        if ($request->hasFile('upload')) {
            if ($request->file('upload')->isValid()) {

                $file = $request->file('upload');
                if (in_array($file->getMimeType(), $this->allowedMimeType)) {
                    
                    if( $request->has("old_img") && File::exsit()) File::delete($request->input("old_img"));
                    
                    $storeFileName = date("Ymdhis").str_random(4);
                    $storePath = 'media/photos/'.$subdomain[0] .'/'. date('Ym');
                    $path = public_path() . '/' . $storePath.'/'.$storeFileName;

                    if (!file_exists(public_path() . '/' .$storePath)) {
                        mkdir(public_path().'/'.$storePath, 0777, true);
                        chmod(public_path().'/'.$storePath, 0777);
                    }   
                    try {
                        if ($request->has('ratio')) {
                            $raito = explode("x", $request->input('ratio'));
                            $upload = Image::make($file);
                            $upload->fit($raito[0], $raito[1]);
                            $upload->orientate();
                            $upload->encode('jpg', 75);
                        } else {
                            $upload = $image->make($file);
                            $upload->orientate();
                            $upload->encode('jpg', 75);
                        }

                        $upload_success = $upload->save($path.'.jpg');
                        if( $upload_success ) {
                            $result = ['error'=>0, 'result'=>$storePath.'/'.$storeFileName.'.jpg'];
                        } else {
                            $result = ['error'=>1, 'result'=>$upload_success];
                        }
                    } catch(Exception $e) {
                        // DEBUG
                        // die($e->getMessage());
                    }
                }
            } else {
                $result = ['error'=>1, 'result'=>'error file not valid'];
            }

        } else {
            $result = array('error'=>1, 'result'=>'no pic');
        }

        return response()->json($result); 
    }

    public function ckeditor_photo(Request $request){
        $subdomain = explode('.', $request->server('HTTP_HOST'));
        if(isset($_FILES['upload'])){
            $filen = $_FILES['upload']['tmp_name']; 
            $storeFileName = date("Ymdhis").str_random(4);
            $storePath = 'media/photos/'.$subdomain[0] .'/'. date('Ym');
            if (!file_exists(public_path() . '/' .$storePath)) {
                mkdir(public_path().'/'.$storePath, 0777, true);
                chmod(public_path().'/'.$storePath, 0777);
            }   
            $con_images = $storePath.'/'.$storeFileName;
            move_uploaded_file($filen, $con_images );
            $url = "/".$con_images;
            $funcNum = $_GET['CKEditorFuncNum'] ;
            // Optional: instance name (might be used to load a specific configuration file or anything else).
            $CKEditor = $_GET['CKEditor'] ;
            // Optional: might be used to provide localized messages.
            $langCode = $_GET['langCode'] ;

            // Usually you will only assign something here if the file could not be uploaded.
            $message = '';
            echo "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction($funcNum, '$url', '$message');</script>";
        }
    }

    public function admin_ckeditor_photo(Request $request){
        $subdomain = explode('.', $request->server('HTTP_HOST'));
        if(isset($_FILES['upload'])){
            $filen = $_FILES['upload']['tmp_name']; 
            $storeFileName = date("Ymdhis").str_random(4);
            $storePath = 'media/photos/admin/'. date('Ym');
            $con_images = $storePath.'/'.$storeFileName;
            if (!file_exists(public_path() . '/' .$storePath)) {
                mkdir(public_path().'/'.$storePath, 0777, true);
                chmod(public_path().'/'.$storePath, 0777);
            }   
            move_uploaded_file($filen, $con_images );
            $url = "/".$con_images;
            $funcNum = $_GET['CKEditorFuncNum'] ;
            // Optional: instance name (might be used to load a specific configuration file or anything else).
            $CKEditor = $_GET['CKEditor'] ;
            // Optional: might be used to provide localized messages.
            $langCode = $_GET['langCode'] ;

            // Usually you will only assign something here if the file could not be uploaded.
            $message = '';
            echo "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction($funcNum, '$url', '$message');</script>";
        }
    }

    public function uploadMultiple(Request $request) 
    {
        $result = "";
        $error = false;
        $returnPath = array();
        
        // dd($request->all());
        
        if ($request->hasFile('upload')) {

            foreach ( $request->file('upload') as $file) {
                // dd($file->toJson())
                $mime = $file->getMimeType();
                
                if (in_array($mime, $this->allowedMimeType)) {

                    $storeFileName = date("Ymdhis").str_random(4);
                    $storePath = 'media/photos/' . date('Ym');
                    $path = public_path() . '/' . $storePath.'/'.$storeFileName;

                    if (!file_exists(public_path() . '/' .$storePath)) {
                        mkdir(public_path().'/'.$storePath, 0777, true);
                        chmod(public_path().'/'.$storePath, 0777);
                    }
                    
                    try {
                        if ($request->has('ratio')) {
                            $raito = explode("x", $request->input('ratio'));
                            $upload = Image::make($file);
                            $upload->fit($raito[0], $raito[1]);
                            $upload->orientate();
                            $upload->encode('jpg', 75);
                        } else {
                            $upload = $image->make($file);
                            $upload->orientate();
                            $upload->encode('jpg', 75);
                        }

                        $upload_success = $upload->save($path.'.jpg');
                        
                        if($upload_success ) {
                            $returnPath[] = $storePath.'/'.$storeFileName.'.jpg';
                        } else {
                            $error = true;
                            $result = array('error'=>1, 'result'=>$upload_success);
                        }
                    } catch (Exception $e) {
                        // DEBUG
                        // die($e->getMessage());
                    }
                }
            }
        } else {
            $result = array('error'=>1, 'result'=>'no pic');
        }

        // dd($returnPath);
        if( !$error) return response()->json(array('error'=>0, 'result'=>$returnPath));
        else return response()->json($result);
    }
    public function delete(Request $request) 
    {
        File::delete($request->input("path"));
    }


    public function upload_logo(Request $request)
    {
        $subdomain = explode('.', $request->server('HTTP_HOST'));
        $result = "";         // response photo path
        // dd($request->input('upload'));
        if ($request->hasFile('upload')) {
            if ($request->file('upload')->isValid()) {

                $file = $request->file('upload');
                if (in_array($file->getMimeType(), $this->allowedMimeType)) {
                    
                    if( $request->has("old_img") && File::exsit()) File::delete($request->input("old_img"));
                    
                    $storeFileName = date("Ymdhis").str_random(4);
                    $storePath = 'media/photos/'.$subdomain[0] .'/logo';
                    $path = public_path() . '/' . $storePath.'/'.$storeFileName;

                    if (!file_exists(public_path() . '/' .$storePath)) {
                        mkdir(public_path().'/'.$storePath, 0777, true);
                        chmod(public_path().'/'.$storePath, 0777);
                    }   
                    try {
                        if ($request->has('ratio')) {
                            $raito = explode("x", $request->input('ratio'));
                            $upload = Image::make($file);
                            $upload->fit($raito[0], $raito[1]);
                            $upload->orientate();
                            $upload->encode('jpg', 75);
                        } else {
                            $upload = $image->make($file);
                            $upload->orientate();
                            $upload->encode('jpg', 75);
                        }

                        $upload_success = $upload->save($path.'.jpg');
                        if( $upload_success ) {
                            $result = ['error'=>0, 'result'=>$storePath.'/'.$storeFileName.'.jpg'];
                        } else {
                            $result = ['error'=>1, 'result'=>$upload_success];
                        }
                    } catch(Exception $e) {
                        // DEBUG
                        // die($e->getMessage());
                    }
                }
            } else {
                $result = ['error'=>1, 'result'=>'error file not valid'];
            }

        } else {
            $result = array('error'=>1, 'result'=>'no pic');
        }

        return response()->json($result); 
    }
}
