<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Validator;
use Config;

class ImageUploadController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function imageUpload()
    {
        return view('imageUpload');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
	 
	 
	public function fileUploadPost(Request $request)
    {
        // dd($request->all());
        // $input      = array('image' => Input::file('image'));
		$user = auth()->user();
        $role = $user->getRole($user->id);
        $user_id     = $user->id;

        $res    = $user->getResidential($user->id);
        $residential_id = $res->residential_id;
        $company_id     = $res->company_id;
		
		$msg 		= "fail";
        $validator  = Validator::make($request->all(), [
            'file' => 'required|file|mimes:jpg,png,jpeg,gif,svg,pdf,jfif|max:2048',
        ]);        

        if($validator->passes()) {
            $id             = $request['id'];
            $source         = $request['source'];
            $file           = $request->all();
			$file_ext		= $request['file']->getClientOriginalExtension();
			$filename_ori	= $request['file']->getClientOriginalName();
			// $filename 		= $company_id.'_'.date('Ymd_His').'.'.$file_ext;
			$filename 		= md5(uniqid(rand(), true)) . '.' . $file_ext;
            
            // $request['image']->move(public_path('tmp'), $file['image']);
			
			if($id != "" && $id != 0) {
				switch($source) {
					case 'vendor_do': 
						$dest_path = base_path().'/document/'.$company_id.'/do/';
						$path		= '/document/'.$company_id.'/do/'.$filename;
						break;
					
					case 'po'		:
						$dest_path = base_path().'/document/'.$company_id.'/po/';
						$path		= '/document/'.$company_id.'/po/'.$filename;
						break;
				}		
				
			} else {
				$dest_path	= base_path().'/tmp/'.$company_id.'/';
				$path 		= '/tmp/'.$company_id.'/'.$filename;
			}
			
			
			// if($source == "po") { 
				// $filename  = 'po_'.$filename;
			// }
			
			$file['file']  = $filename;
            $request['file']->move($dest_path, $filename);
            
			$fullpath	= base_path().'/tmp/'.$company_id.'/'.$filename;			
			
            $msg 		 = "\n[base_path()] ".base_path();
            $msg 		.= "\n[storage_path()] ".storage_path();
            $msg 		.= "\n[app_path()] ".app_path();
            // $msg 		.= "\n[dest_path] ".dest_path();
			
			// if($source == "po" && $id != "0") {
				// $data_row = [];
				// $data_row['company_id'] = $company_id;
				// $data_row['parent_id']  = 0;
				// $data_row['create_by']  = $user_id;
				// $data_row['create_at']  = date("Y-m-d H:i:s");
				
				// $data_insert[] = $data_row;           
				// DB::table('trade')->where('id', '$id')->update($data_row);
			// }
            
				
			if($source == "vendor_do") {				
				$data_row = array();			
				$data_row['do_file']        = $filename;
				$data_row['update_by']      = $user_id;
				$data_row['update_at']      = date("Y-m-d H:i:s");
				
				$update_result = DB::table(Config::get('constants.tables.do'))->where('id', '=', $id)->update($data_row);
			}
			
			if(File::exists($dest_path)) {
				$status = "success";
				$msg 	.= "\nFile exist! ".$dest_path;
			} else {
				$status = "File not exists! ".$dest_path;
			}
			
            return response()->json(['status'=>$status, 'path'=>$path, 'msg'=>$msg, 'file_ext'=>$file_ext, 'filename'=>$filename_ori]);
        }

        return response()->json(['status'=>$validator->errors()->all(), 'request'=>$request->all()]);
    }
    public function imageUploadPost(Request $request)
    {
        // dd($request->all());
        // $input      = array('image' => Input::file('image'));
		$msg 		= "fail";
        $validator  = Validator::make($request->all(), [
            'image' => 'required|file|mimes:jpg,png,jpeg,gif,svg,jfif|max:2048',
        ]);        

        if($validator->passes()) {
            $id             = $request['id'];
            $source         = $request['source'];
            $file           = $request->all();
			$file_ext		= $request['image']->getClientOriginalExtension();
            $file['image']  = date('Y_m_d_His').'.'.$file_ext;
            // $request['image']->move(public_path('tmp'), $file['image']);
			$dest_path		= base_path().'/tmp/';
            $request['image']->move($dest_path, $file['image']);
            
            $path 		= '/tmp/'.$file['image'];
			$fullpath	= base_path().'/tmp/'.$file['image'];
			
			
            $msg 		 = "\n[base_path()] ".base_path();
            $msg 		.= "\n[storage_path()] ".storage_path();
            $msg 		.= "\n[app_path()] ".app_path();
            // $msg 		.= "\n[dest_path] ".dest_path();
			
			// if($source == "material_item" && $id != "0") {
				// $data_row = [];
				// $data_row['company_id'] = $company_id;
				// $data_row['parent_id']  = 0;
				// $data_row['create_by']  = $user_id;
				// $data_row['create_at']  = date("Y-m-d H:i:s");
				
				// $data_insert[] = $data_row;           
				// DB::table('trade')->where('id', '$id')->update($data_row);
			// }
            
			
			if(File::exists($dest_path)) {
				$status = "success";
				$msg 	.= "\nFile exist! ".$dest_path;
			} else {
				$status = "File not exists! ".$dest_path;
			}
			
            return response()->json(['status'=>$status, 'path'=>$path, 'msg'=>$msg]);
        }

        return response()->json(['status'=>$validator->errors()->all(), 'request'=>$request->all()]);
    }

    public function deleteImage(Request $request)
    {
		$user 		= auth()->user();
        $role		= $user->getRole($user->id);
        $user_id    = $user->id;

        $res    	= $user->getResidential($user->id);
        $residential_id = $res->residential_id;
        $company_id     = $res->company_id;
		
		$id			= $request['id'];
        $source 	= $request['source'];
        $filename 	= $request['filename'];
		$file_path 	= "";
		$dest_path	= "";		
	
		switch($source) {
			case 'material_item'	:
				$file_path 	= public_path($filename);		
				$dest_path	= base_path().$filename;
				break;
			
			case 'vendor_do'	:				
				$dest_path 	= base_path().'/document/'.$company_id.'/do/';
				$file_path	= '/document/'.$company_id.'/do/'.$filename;
				break;
		}
		
		$msg 		= "\n[file_path] ".$dest_path;

        if(File::exists($dest_path)) {
            File::delete($dest_path);
			
            if($source == "material_item") {               
                DB::table('item')->where('id', $id)->update(['img' => '']);
				
            } else if($source == "vendor_do") {
				DB::table('do')->where('id', $id)->update(['img' => '']);
			}
            
        } else {
            return response()->json(['status'=>'Failed to delete image.', 'request'=>$request->all(), 'msg'=>$msg]);
        }

        return response()->json(['status'=>'success', 'request'=>$request->all(), 'path'=>$file_path]);
    }

	public function deleteFile(Request $request)
    {
		$user 		= auth()->user();
        $role		= $user->getRole($user->id);
        $user_id    = $user->id;

        $res    	= $user->getResidential($user->id);
        $residential_id = $res->residential_id;
        $company_id     = $res->company_id;
		
		$id				= $request['id'];
        $source 		= $request['source'];
        $filename 		= $request['filename'];
		$file_path 		= "";
		$dest_path		= "";	
		$delete_status 	= "";
	
		switch($source) {
			case 'material_item'	:
				$file_path 	= public_path($filename);		
				$dest_path	= base_path().$filename;
				break;
			
			case 'vendor_do'	:				
				$dest_path 	= base_path().'/document/'.$company_id.'/do/'.$filename;
				$file_path	= '/document/'.$company_id.'/do/'.$filename;
				break;
		}
		
		$msg 		= "\n[file_path] ".$dest_path;

        if(File::exists($dest_path)) {
            $delete_status = File::delete($dest_path);
			
            if($source == "material_item") {               
                DB::table('item')->where('id', $id)->update(['img' => '']);
				
            } else if($source == "vendor_do") {
				$data_row = array();			
				$data_row['do_file']        = '';
				$data_row['update_by']      = $user_id;
				$data_row['update_at']      = date("Y-m-d H:i:s");
				
				$update_result = DB::table(Config::get('constants.tables.do'))->where('id', '=', $id)->update($data_row);
				// DB::table('do')->where('id', $id)->update(['do_file' => '']);
			}
            
        } else {
            return response()->json(['status'=>'Failed to delete file.', 'request'=>$request->all(), 'msg'=>$msg]);
        }

        return response()->json(['status'=>'success', 'request'=>$request->all(), 'path'=>$file_path, 'delete_status'=>$delete_status, 'dest_path'=>$dest_path]);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
 