<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use Mail;
use Illuminate\Support\Facades\Response;
// use Input;
use Auth;
use App\Role;
use App\Price;
use App\Doctor_Agreement;
use App\Licence;
use Log;
use Illuminate\Support\Facades\Input;

class UserController extends Controller
{
	public function __construct()
    {
        $this->middleware('auth');
    }   

    public function add_user(){

        if(ConfigController::check_privilege('ACCESS_ADD_USER'))
        {

            switch (Auth::user()->role_id) {
                case '1':
                    $roles = Role::all();
                    break;
 
                 case '2':
                    $roles = Role::where('id','<>','1')->where('id','<>','2')->get();
                    break;

                default:
                    return view('errors.not_authorized');
                    break;
            }
        }
        else
        {
            return view('errors.not_authorized');
        }

        

    	return view('users.add_user',compact('roles'));
    } 

    public function add_user_db(Request $request){

        if(ConfigController::check_privilege('ACCESS_ADD_USER'))
        {
            $this->validate($request,[
                'email'         => 'required|email|unique:users',
                'name'          => 'required',
                'role'          => 'required',
                'tin_number'    => 'required',
                'pac'           => 'required'
            ]);

            $password = str_random();
            $encrypted_passwd = bcrypt($password);
            
            //user count
            $count_users = count(User::get());

            $licence = ConfigController::check_licence('user');
            if($licence > $count_users)
            {

                User::create([
                    'name'          => $request->name,
                    'email'         => $request->email,
                    'role_id'       => $request->role,
                    'pac'           => $request->pac,
                    'pac_status'    => 'n',
                    'password'      => $encrypted_passwd,
                    'status'        => 'a',
                    'tin_number'    => $request->tin_number,
                    'created_by'    => Auth::user()->id,
                    'reset'         => 'on'
                ]);
            }
            else
            {
                return response()->json(['error' => 'User cannot be added as you have exceeded maximum amount of users as per your licence.']);
            }
             
        }
        else
        {
            return view('errors.not_authorized');  
        }    

           
        //assign data in array
    	$data = array(
    		'name' => $request->name,
			'role' => $request->role,
            'password' => $password,
			'pac' => $request->pac
  		);

        //Send Email
        Mail::send('emails.new_user', array('user'=>$data), function($message)
            {
                $message->to(Input::get('email'), Input::get('name'))->subject('User Credentials');
            });

        //Return with Message JSON
    	return response()->json(['message' => 'User has been added successfully and password has been sent via Email.']);
    }


    public function edit_user_view($id){
        if(ConfigController::check_privilege('ACCESS_EDIT_USER'))
        {


            switch (Auth::user()->role_id) {
                case '1':
                    $roles = Role::all();

                    $users = User::select('id','name','email','role_id','tin_number','pac')
                         ->where('id',$id)
                         ->get();

                        if(count($users)==0){
                            return view('errors.user_not_exist');
                         }
                    break;
 
                 case '2':
                    $roles = Role::where('id','<>','1')->where('id','<>','2')->get();

                    $users = User::select('id','name','email','role_id','tin_number','pac')
                         ->where('id',$id)
                         ->where('role_id','<>','1')
                         ->where('role_id','<>','2')
                         ->get();

                         if(count($users)==0){
                            return view('errors.user_not_exist');
                         }

                    break;

                default:
                    return view('errors.not_authorized');
                    break;
            }

        }
        else
        {
            return view('errors.not_authorized');
        }

        

        return view('users.edit',compact('roles','users'));
    }


    public function edit_user(Request $request){
        $this->validate($request,[
            'email'         => 'required|email',
            'name'          => 'required',
            'tin_number'    => 'required',
            'role'          => 'required',
            'pac'           => 'required'

        ]);

        $user = User::find($request->id);
        $user->email = $request->email;
        $user->name = $request->name;
        $user->tin_number = $request->tin_number;
        $user->role_id = $request->role;
        $user->pac = $request->pac;
        $user->save();

        return response()->json(['message' => 'User updated successfully.']);
    }



    public function delete_user(Request $request){

        $user = User::find($request->id);
        $user->updated_by = Auth::user()->id;
        $user->save();
        $user->delete();

        return response()->json(['success']);
    }



    public function display_users()
    {
        

        if(ConfigController::check_privilege('ACCESS_LIST_USER'))
        {
            $users = User::select('id','name')
                     ->get();

        

            switch (Auth::user()->role_id) {
                case '1'://Admin
                        $data = User::select('id','name','email','created_by','updated_by','role_id','deleted_at')
                                ->withTrashed()
                                ->get();
                    break;

                case '2'://Admin Doctor
                        $data = User::select('id','name','email','created_by','updated_by','role_id','deleted_at')
                                ->where('id','<>','1')
                                ->where('id','<>','2')
                                ->withTrashed()
                                ->get();
                    break;
                
                default:
                        return view('errors.not_authorized');
                    break;
            }
        }
        else
        {
            return view('errors.not_authorized');
        }

        return view('users.list',compact('users','data'));
    }


    public function reset_password(Request $request){
        if(ConfigController::check_privilege('ACCESS_USER_RESET_PASSWORD'))
        {
            $this->validate($request,[
                'password' => 'required|min:6'
            ]);


            $user = User::find($request->id);
            $user->password = bcrypt($request->password);
            $user->updated_by = Auth::user()->id;
            $user->reset = 'on';
            $user->save();


            $data = array(
                'name' => $request->name,
                'password' => $request->password,
            );

            //Send Email
            Mail::send('emails.user_password', array('user'=>$data), function($message)
                {
                    $message->to(Input::get('email'), Input::get('name'))->subject('User Password Reset');
                });

            return response()->json(['message' => 'Password has been changed successfully and email has been sent to the user.']);
        }
        else
        {
            return view('errors.not_authorized');
        }
    }


    public function restore_user(Request $request){
        if(ConfigController::check_privilege('ACCESS_RESTORE_USER'))
        {
            $count_users = count(User::get());

            $licence = ConfigController::check_licence('user');
            if($licence > $count_users)
            {

                User::withTrashed()
                    ->where('id',$request->id)
                    ->restore();
            }
            else
            {
                return response()->json(['error' => 'User cannot be restored as you have exceeded maximum amount of users as per your licence.']);
            }
            return response()->json(['success']);
        }
        else
        {
            return view('errors.not_authorized');   
        }
    }

    public function search_user(Request $request){
        if(ConfigController::check_privilege('ACCESS_SEARCH_USER'))
        {
            $users = User::select('id','name')
                     ->get();

        

            switch (Auth::user()->role_id) 
            {
                case '1'://Admin
                        switch ($request->search_type) 
                        {
                            case 'name':
                                    $data = User::select('id','name','email','last_login','ip','created_by','updated_by','role_id','deleted_at')
                                                ->withTrashed()
                                                ->where('name','like','%'.$request->search_term.'%')
                                                ->get();
                                break;

                            case 'id':
                                    $data = User::select('id','name','email','last_login','ip','created_by','updated_by','role_id','deleted_at')
                                                ->withTrashed()
                                                ->where('id',$request->search_term)
                                                ->get();
                                break; 

                            case 'email':
                                    $data = User::select('id','name','email','last_login','ip','created_by','updated_by','role_id','deleted_at')                                 
                                                ->withTrashed()
                                                ->where('email',$request->search_term)
                                                ->get();
                                break; 
                        }
                        
                    break;

                case '2'://Admin Doctor

                        switch ($request->search_type) 
                        {
                            case 'name':
                                    $data = User::select('id','name','email','last_login','ip','created_by','updated_by','role_id','deleted_at')
                                                ->where('id','<>','1')
                                                ->where('id','<>','2')
                                                ->withTrashed()
                                                ->where('name','like','%'.$request->search_term.'%')
                                                ->get();
                                break;

                            case 'id':
                                    $data = User::select('id','name','email','last_login','ip','created_by','updated_by','role_id','deleted_at')
                                                ->where('id','<>','1')
                                                ->where('id','<>','2')                                    
                                                ->withTrashed()
                                                ->where('id',$request->search_term)
                                                ->get();
                                break; 

                            case 'email':
                                    $data = User::select('id','name','email','last_login','ip','created_by','updated_by','role_id','deleted_at')
                                                ->where('id','<>','1')
                                                ->where('id','<>','2')                                    
                                                ->withTrashed()
                                                ->where('email',$request->search_term)
                                                ->get();
                                break; 
                        }
                    break;
                
                default:
                        return view('errors.not_authorized');
                    break;
            }
        }
        else
        {
        return view('errors.not_authorized');
        }

        return view('users.list',compact('users','data'));
    }

    public function change_password(Request $request){
        $this->validate($request,[
            'new_password' => 'required|min:6',
            'confirm_new_password' => 'required|same:new_password'
        ]);

        $encrypted_password = bcrypt($request->new_password);

        $user = User::find(Auth::user()->id);
        $user->password = $encrypted_password;
        $user->password_changed_at = date("Y-m-d");
        $user->reset = 'off';
        $user->save();

        return response()->json(['success' => 'Password changed successfully. Please wait for 4 seconds.']);

    }


    public function change_pac_status(Request $request)
    {
        $this->validate($request,[
            'pac_code' => 'required'
        ]);

        if(Auth::user()->pac == $request->pac_code)
        {
            $user = User::find(Auth::user()->id);
            $user->pac_status = 'y';
            $user->save();

            return response()->json(['success' => 'Correct PAC Code. Please wait for few minutes...']);
        }
        else
        {
            return response()->json(['error' => 'Error, Incorrect PAC Code']);
        }
    }


    public function change_branch(Request $request)
    {
        if(Auth::user()->role_id == '4')
        {
            $id = Auth::user()->id;

            $status = false;

            $this->validate($request,[
                'branch_id' => 'required'
            ]);

            try
            {
                $user = User::find($id);
                $user->branch_id = $request->branch_id;
                $user->save();

                $branch_name = ConfigController::get_branch($request->branch_id);
            }
            catch(\Exception $e)
            {
                $status = true;
                Log::debug('User '.$id.' branch_id not updated due to below error');
                Log::debug('======================================================');
                Log::debug($e);
                Log::debug('======================================================');
            }

            if($status == true)
            {
                return response()->json(['error' => 'Oops, Something went wrong. Please try again later.']);
            }
            else
            {
                return response()->json(['success' => 'Thank you. Your user has been updated.','branch_name' => $branch_name]);
            }

        }
        else
        {
            return response()->json(['error' => 'Sorry, you do not have access to this service.']);
        }
    }



    public function add_payroll($id,Request $request)
    {
        if(ConfigController::check_privilege('ACCESS_PAYROLL'))
        {
           $products = Price::select('id','name','amount')
                              ->get();

            $user_id = $id;

            if($request->ajax()) 
            {
                $view = view('users.agreements_data',compact('products','user_id'))->render();

                return response()->json(['html'=>$view]);
            }

            return view('users.agreements',compact('products','user_id'));
        }
        else
        {
            return view('errors.not_authorized');
        }
    }


    public function save_payroll(Request $request)
    {
        if(ConfigController::check_privilege('ACCESS_PAYROLL'))
        {
            $status = false;

            $products = Price::select('id')
                               ->get();

                foreach ($products as $product) {
                    //check if the checkbox has been checked
                    if(Input::get('productCheckbox'.$product->id) == 'yes')
                    {
                        //check if the record exist in the DB
                        if(ConfigController::confirm_agreement_change($request->user_id,$product->id,Input::get('percentage'.$product->id),'check') == 'insert')
                        {
                            //insert data in the DB 
                            try
                            {
                                $agreement = new Doctor_Agreement;
                                $agreement->user_id = $request->user_id;
                                $agreement->created_by = Auth::user()->id;
                                $agreement->updated_by = Auth::user()->id;
                                $agreement->product_id = $product->id;
                                $agreement->percentage = Input::get('percentage'.$product->id);
                                $agreement->save();

                            }
                            catch(\Exception $e)
                            {
                                Log::debug('======================================================');
                                Log::debug('------- Insert agreement Failed --------');
                                Log::debug($e);
                                Log::debug('======================================================');   
                                $status = true;                         
                            }
                        }

                        //Update current rule
                        if(ConfigController::confirm_agreement_change($request->user_id,$product->id,Input::get('percentage'.$product->id),'check') == 'update')
                        {
                            $agreement_id = ConfigController::confirm_agreement_change($request->user_id,$product->id,Input::get('percentage'.$product->id),'id');
                            

                            //Delete data DB
                            try
                            {
                                $agreement = Doctor_Agreement::find($agreement_id);
                                $agreement->updated_by = Auth::user()->id;
                                $agreement->save();
                                $agreement->delete();
                            }
                            catch(\Exception $e)
                            {
                                Log::debug('======================================================');
                                Log::debug('------- Delete agreement Failed --------');
                                Log::debug($e);
                                Log::debug('======================================================');
                                $status = true;
                            }


                            //Insert
                            try
                            {   

                                $agreement = new Doctor_Agreement;
                                $agreement->user_id = $request->user_id;
                                $agreement->created_by = Auth::user()->id;
                                $agreement->updated_by = Auth::user()->id;
                                $agreement->product_id = $product->id;
                                $agreement->percentage = Input::get('percentage'.$product->id);
                                $agreement->save();
                            }
                            catch(\Exception $e)
                            {
                                Log::debug('======================================================');
                                Log::debug('------- Update agreement Failed --------');
                                Log::debug($e);
                                Log::debug('======================================================');
                                $status = true;
                            }
                        }


                } 
                
                if(Input::get('productCheckbox'.$product->id) == 'no')
                {
                        if(ConfigController::confirm_agreement_change($request->user_id,$product->id,Input::get('percentage'.$product->id),'check') == 'no_change')
                        {
                            $agreement_id = ConfigController::confirm_agreement_change($request->user_id,$product->id,Input::get('percentage'.$product->id),'id');

                            //Update the DB
                            try
                            {
                                $agreement = Doctor_Agreement::find($agreement_id);
                                $agreement->updated_by = Auth::user()->id;
                                $agreement->save();
                                $agreement->delete();
                            }
                            catch(\Exception $e)
                            {
                                Log::debug('======================================================');
                                Log::debug('------- Delete agreement Failed --------');
                                Log::debug($e);
                                Log::debug('======================================================');
                                $status = true;
                            }

                        }
                }
            }

            //if have error then submit error parameter else succcess
            if($status)
            {
                return response()->json(['error' => 'An Internal error has occured. Please try again.']);
            }
            else
            {
                return response()->json(['success' => 'Data updated successfully.']);
            } 
        
        }
        else
        {
            return view('errors.not_authorized');
        }
    }


}