<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\User;
use App\Setting;
use App\Dokter;
use App\Worklist;
use App\XFiles;
use Validator;
use Session;

class UserController extends Controller
{
    public function index() {
		$cekkelompok= 	Session('previlage');
		if (Session::get('previlage') == ''){
			return redirect('/login');
		} else {
			if ($cekkelompok == 'supervisor' OR $cekkelompok == 'admin' OR $cekkelompok == 'developer'){
				$users 				= 	User::all();
			} else {
				$users 				= 	User::where('previlage', $cekkelompok)->get();
			}
			$getsetting				= 	Setting::where('id', '1')->first();
			$data 					= 	[];
			$data['users'] 			= 	$users;
			$data['pacsaddr'] 		= 	$getsetting->pacs ?? '';
			$data['zfpaddr'] 		= 	$getsetting->zfp ?? '';
			$data['port'] 			= 	$getsetting->port ?? '';
			$data['portzfp'] 		= 	$getsetting->portzfp ?? '';
			$data['username'] 		= 	$getsetting->username ?? '';
			$data['password'] 		= 	$getsetting->password ?? '';
			return view('admin.user', $data);
		}
    }
	public function exSetting(Request $request) {
    	$validator  =   Validator::make($request->all(), [
            'val01' =>  'required',
            'val02' =>  'required',
            'val03' =>  'required',
			'val04' =>  'required',
			'val05' =>  'required',
			'val06' =>  'required',
        ]);

        if($validator->fails()) {
            return response()->json(['status' => 'error', 'message' => 'Please fill input field or fill with right input']);
        } else {
            $update = Setting::where('id', '1')->update([
            	'pacs'  	=>  $request->input('val01'),
	            'zfp' 		=>  $request->input('val02'),	         
	            'port' 		=> 	$request->input('val03'),
				'portzfp' 	=> 	$request->input('val06'),
				'username' 	=> 	$request->input('val04'),
				'password' 	=> 	$request->input('val05')
            ]);
			if ($update) {
				return response()->json(['icon' => 'success', 'warna' => '#5ba035', 'status' => 'Success', 'message' => 'Setting Saved..!!!']);
				return back();
			}
			else {
				return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Error.!!', 'message' => 'System Down, please try again in a few years....']);
				return back();
			}
        }
    }
	public function exSettingworklist(Request $request) {
		$idne = $request->input('val01');
		if ($idne == 'delete'){
			$delete = Worklist::where('id', $request->input('val02'))->delete();
			if ($delete) {
				return response()->json(['icon' => 'success', 'warna' => '#5ba035', 'status' => 'Success', 'message' => 'Worklist Deleted..!!!']);
				return back();
			}
			else {
				return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Error.!!', 'message' => 'System Down, please try again in a few years....']);
				return back();
			}
		} else {
			$validator  =   Validator::make($request->all(), [
				'val01' =>  'required',
				'val02' =>  'required',
				'val03' =>  'required',
				'val04' =>  'required',
				'val05' =>  'required',
			]);

			if($validator->fails()) {
				return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Error.!!', 'message' => 'Please fill input field or fill with right input']);
			} else {
				
				if ($idne == 'new'){
					$input = Worklist::create([
						'aetitle'		=> $request->input('val05'), 
						'portnumber'	=> $request->input('val04'), 
						'ipaddress'		=> $request->input('val02'), 
						'location'		=> $request->input('val03'),
						'modaliti'		=> $request->input('val06')
					]);
				} else {
					$input = Worklist::where('id', $idne)->update([
						'aetitle'		=> $request->input('val05'), 
						'portnumber'	=> $request->input('val04'), 
						'ipaddress'		=> $request->input('val02'), 
						'location'		=> $request->input('val03'),
						'modaliti'		=> $request->input('val06')
					]);
				}
				if ($input) {
					return response()->json(['icon' => 'success', 'warna' => '#5ba035', 'status' => 'Success', 'message' => 'Worklist Saved..!!!']);
					return back();
				}
				else {
					return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Error.!!', 'message' => 'System Down, please try again in a few years....']);
					return back();
				}
			}
		}
    }
	public function exTtd(Request $request) {
		$iduser 	= Session('id');
    	$marking 	= Session('username').'-Photo-'.$iduser; 
		$update		= XFiles::updateOrCreate(
			[
				'xmarking'	=> $marking,
			],
			[
				'xjenis'	=> 'Tandatangan',
				'xtabel'	=> Session('username'),
				'xfile'		=> $request->input('val01')
			]
		);
		if ($update) {
			User::where('id', $iduser)->update([
				'tandatangan' =>  $marking,
			]);
			return response()->json(['icon' => 'success', 'warna' => '#5ba035', 'status' => 'Success', 'message' => 'Signature Saved..!!!']);
			return back();
		}
		else {
			return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Error.!!', 'message' => 'System Down, please try again in a few years....']);
			return back();
		}
    }
    public function store(Request $request) {
    	$validator  =   Validator::make($request->all(), [
            'nama'          =>  'required',
            'username' 	    =>  'required',
            'password' 	    =>  'required',
            'previlage'     =>  'required',
        ]);

        if($validator->fails()) {
			Session::flash('message', 'Please fill input field or fill with right input'); 
			Session::flash('alert-class', 'alert-danger');
			return back();
        } else {
			$username 	= $request->input('username');
			$previlage 	= $request->input('previlage');
			$nama 		= $request->input('nama');
			$cekuser	= User::where('username', $username)->count();
			if ($cekuser == 0){
				if ($previlage == 'supervisor' OR $previlage == 'developer'){
					$iduser 			= User::insertGetId([
						'nama'      	=>  $request->input('nama'),
						'username' 		=>  $request->input('username'),
						'password' 		=>  bcrypt($request->input('password')),
						'previlage' 	=> 	$request->input('previlage')
					]);
					Dokter::create([
						'id'			=>	$iduser,
						'nama' 			=>  $request->input('nama'),
						'kota' 			=> 	config('global.kota'),
						'alamat' 		=> 	config('global.addressapps')
					]);
				} else {
					$user = User::create([
						'nama'      	=>  $request->input('nama'),
						'username' 		=>  $request->input('username'),
						'password' 		=>  bcrypt($request->input('password')),
						'previlage' 	=> 	$request->input('previlage')
					]);
				}
				Session::flash('message', 'Username for '.$nama.' Saved'); 
				Session::flash('alert-class', 'alert-success');
				return back();
			} else {
				Session::flash('message', 'Username already used, please use another username'); 
				Session::flash('alert-class', 'alert-danger');
				return back();
			}
        }
    }
    public function getUser(Request $request) {
    	$id         =   $request->input('id');
        $result     =   User::where('id', $id)->first();
        echo json_encode($result);
    }
	public function getWorklist() {
    	$arrworklist	= [];
		$getworklist 	= Worklist::orderBy('location', 'ASC')->get();
		foreach ($getworklist as $rowida) {
			$arrworklist[] = array(
				'id' 			=> $rowida->id,
				'aetitle' 		=> $rowida->aetitle,
				'portnumber' 	=> $rowida->portnumber,
				'ipaddress' 	=> $rowida->ipaddress,
				'location' 		=> $rowida->location,
				'modaliti' 		=> $rowida->modaliti,
			);
		}
        echo json_encode($arrworklist);
    }
    public function update(Request $request) {
    	$validator  =   Validator::make($request->all(), [
            'nama'      =>  'required',
            'username' 	=>  'required',
            'previlage' =>  'required'
        ]);

        if($validator->fails()) {
          return response()->json(['status' => 'error', 'message' => 'Please fill input field or fill with right input']);
        } else {
            $id         =   $request->input('id_user');
			$password   =   $request->input('password');
			if ($password == ''){
				$update = User::where('id', $id)->update([
					'nama'      =>  $request->input('nama'),
					'username' 	=>  $request->input('username'),					
					'previlage' =>  $request->input('previlage')
				]);
			} else {
				$update = User::where('id', $id)->update([
					'nama'      =>  $request->input('nama'),
					'username' 	=>  $request->input('username'),
					'password' 	=>  bcrypt($request->input('password')),
					'previlage' =>  $request->input('previlage')
				]);
			}

			if ($update){
				Session::flash('message', 'Updated'); 
				Session::flash('alert-class', 'alert-success');

				return back();
			} else {
				Session::flash('message', 'Update Failed, Please Try Again in a few year'); 
				Session::flash('alert-class', 'alert-success');

				return back();
			}
        }
    }
	public function updateFoto(Request $request) {
		$iduser 	= Session('id');
    	$marking 	= Session('username').'-Photo-'.$iduser; 
    	if($request->hasFile('file')) {
			$ImageExt	= $request->file('file')->getClientOriginalExtension();
			$file_tmp	= $request->file('file');
			$data 		= file_get_contents($file_tmp);
			$photo 		= 'data:image/' . $ImageExt . ';base64,' . base64_encode($data);
			$iduser		= Session('id');
			$update		= XFiles::updateOrCreate(
				[
					'xmarking'	=> $marking,
				],
				[
					'xtabel'	=> Session('username'),
					'xjenis'	=> 'Photo',
					'xfile'		=> $photo
				]
			);
			if ($update) {
				User::where('id', $iduser)->update([
					'photo' =>  $marking,
				]);
				return response()->json(['icon' => 'success', 'warna' => '#5ba035', 'status' => 'Success', 'message' => 'Photo Profile Saved, please relogin to apply the change']);
				return back();
			}
			else {
				return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Error.!!', 'message' => 'System Down, please try again in a few years....']);
				return back();
			}
		} else {
			return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Error.!!', 'message' => 'No File Selected']);
			return back();
		}
    }
    public function delete(Request $request) {
    	$id         =   $request->user_id;
        $user     	=   User::find($id);
		XFiles::where('xtabel', $user->username)->delete();
        $user->delete();
        return back();
    }
}
