<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Carbon\Carbon;
use Intervention\Image\ImageManagerStatic as Image;

class Upload extends Controller
{
    public function index(){
        return view('index');
      }

      public function uploadFile(Request $request){

        if ($request->input('submit') != null ){

           $file = $request->file('file');

           // File Details
           $filename = $file->getClientOriginalName();
           $extension = $file->getClientOriginalExtension();
           $tempPath = $file->getRealPath();
           $fileSize = $file->getSize();
           $mimeType = $file->getMimeType();

           // Valid File Extensions
           $valid_extension = array("jpg","jpeg","png");

           // 2MB in Bytes
           $maxFileSize = 2097152;

           // Check file extension
           if(in_array(strtolower($extension),$valid_extension)){

             // Check file size
             if($fileSize <= $maxFileSize){

                // File upload location
                $location = config('app.image.dir');
                
                $backupdir = Carbon::now()->format('Y/m/d');
		          $backupdir = sprintf($location.'/backup/%s',$backupdir);
		          $thumbdir = sprintf('%s/%s', config('app.image.thumb_dir'), Carbon::now()->format('Y/m/d'));
                $bckfile = Carbon::now()->format('Hi');
                $bckfile = sprintf('%s.jpg',$bckfile);
                // Upload file
                $file->move($backupdir,$bckfile);
                \File::copy($backupdir."/".$bckfile,$location."/".$filename);
		          $image = Image::make($backupdir."/".$bckfile)->resize(160, 120);
		          \File::makeDirectory($thumbdir, $mode = 0770, true, true);
                $image->save( $thumbdir.'/'.$bckfile);
                echo 'Upload Successful.';
             }else{
                echo 'File too large. File must be less than 2MB.';
             }

           }else{
              echo 'message Invalid File Extension.';
           }

         }

         // Redirect to index
         echo "OK";
      }
}
