<?php

namespace App\Http\Controllers\Contractor;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

use Carbon\Carbon;
use Validator;
use PDF;

use App\Staff;
use App\Model\StaffDetail;
use App\Model\Form;
use App\Model\Subscriber;
use App\Model\Coverage; 
use App\Model\FormStatus;
use App\Model\WorkOrder;
use App\Model\Docket;
Use App\Model\DealerClaim;
use App\Model\Commission;
use App\Model\Company;

class ContractorController extends Controller
{

	//
	// public function get_guard(){
	// 	if(Auth::guard('contractor')->check())
	// 		{return "contractor";}
	// }

	// public function showFormDLogin(){
	// 	return view('login_cs_co');
	// }

	public function encryptPassword($action, $string) {
		$output = false;
		$encrypt_method = "AES-256-CBC";
		$secret_key = '28472B4B6250655368566D5970337336';
		$secret_iv =  md5(md5($string)); //'This is my secret iv';
		
		// hash
		$key = hash('sha256', $secret_key);
		
		$iv = substr(hash('sha256', $secret_iv), 0, 16);
		if ( $action == 'encrypt' ) {
			$output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
			$output = base64_encode($output);
		} else if( $action == 'decrypt' ) {
			$output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
		}
		return $output;
	}

	// public function requestLogin(Request $request) {
	// 	$this->validate($request, [
	// 		'email' => 'required|email'
	// 		// 'password' => 'required|min:6'
	// 	]);
		
	// 	$user = '';
		
	// 	try {
 //            $message = trans('messages.invalid_login_credentials');
 //            $rememberMe = false;
 //            $user = StaffLaravel::where('email', $request->email)->where('roles_access','Contractor')->first();
	// 		if (!empty($user)) {
	// 			if($this->encryptPassword('encrypt', $request->password) == $user->password){
					
	// 				// Update last_login & last ip
	// 				$user->last_login_at = Carbon::now(new \DateTimeZone('Asia/Kuala_Lumpur'))->toDateTimeString();
	// 				$user->last_login_ip = $request->getClientIp();
	// 				$user->save();

	// 				if($user->roles_access == "Contractor"){
	// 					Auth::guard('contractor')->loginUsingId($user->_id, $rememberMe);
	// 					return redirect('/Contractor');
	// 				}
	// 			}
	// 		}
 //        } catch (\Exception $e) {
 //            Log::error(__CLASS__ . "::" . __METHOD__ . "  " . $e->getMessage() . "on line" . $e->getLine());
 //        }
 //        return redirect('/login/dashboard/admin')->with('error_msg', $message);
	// }

 //    public function logout(){
		
	// 	// Get Current member id
	// 	$id = Auth::guard('contractor')->id();

	// 	if (Auth::guard('contractor')->check()) {
	// 	    $user = StaffLaravel::find($id);
		
	// 		// Update last_login & last ip
	// 		$user->last_login_at = Carbon::now(new \DateTimeZone('Asia/Kuala_Lumpur'))->toDateTimeString();
	// 		$user->last_login_ip = \Request::getClientIp();			
	// 		$user->save();
			
	// 		// Proceed to Log Out
	// 		Auth::guard('contractor')->logout();
	// 		// return redirect('/login/dashboard');

	// 		return redirect('http://cbblaravel.swisslink.com.my/login/dashboard/admin');
	// 	}
 //    }

    /*************************************************************************************   Next Step *************************************************************************************/

    public function viewContractorTeam()
    {
    	$id = Auth::guard('contractor')->id();
		$user = Staff::with('StaffDetail')->find($id);

		$pp = count(WorkOrder::where('status','Pending Non Prelaid')->where('contractor_id',$user->StaffDetail->company_id)->get());
		$sp = count(WorkOrder::where('status','Success Non Prelaid')->where('contractor_id',$user->StaffDetail->company_id)->get());
		$rs = count(WorkOrder::where('status','Reschedule')->where('contractor_id',$user->StaffDetail->company_id)->get());
		$ss = count(WorkOrder::where('status','Suspend')->where('contractor_id',$user->StaffDetail->company_id)->get());
		$cm = count(WorkOrder::where('status','Completed')->where('contractor_id',$user->StaffDetail->company_id)->get());

        return view('contractor.view_team',compact('user','pp','sp','rs','ss','cm','pc','pi'));
    }

    public function viewEditContractorTeam($i_id)
    {
    	$id = Auth::guard('contractor')->id();
		$user = Staff::with('StaffDetail')->find($id);

		$pp = count(WorkOrder::where('status','Pending Non Prelaid')->where('contractor_id',$user->StaffDetail->company_id)->get());
		$sp = count(WorkOrder::where('status','Success Non Prelaid')->where('contractor_id',$user->StaffDetail->company_id)->get());
		$rs = count(WorkOrder::where('status','Reschedule')->where('contractor_id',$user->StaffDetail->company_id)->get());
		$ss = count(WorkOrder::where('status','Suspend')->where('contractor_id',$user->StaffDetail->company_id)->get());
		$cm = count(WorkOrder::where('status','Completed')->where('contractor_id',$user->StaffDetail->company_id)->get());

		$staff = Staff::with('StaffDetail')->where('_id',$i_id)->first();

        return view('contractor.edit_contractor',compact('user','pp','sp','rs','ss','cm','pc','pi','staff'));
    }

    public function getContractorWork()
    {

    	$id = Auth::guard('contractor')->id();
		$user = Staff::with('StaffDetailLaravel')->find($id);
		$curr = Carbon::now()->getTimestamp();

        $work_detail= WorkOrderLaravel::with('FormLaravel')->where('contractor_id',$user->StaffDetailLaravel->company_id)->orderBy('dateTimeStart', 'desc')->get();

		$i = 0;
		$nested_data = array();
		if(!empty($work_detail)){
			foreach ($work_detail as $a)
			{	
				$i++; $y = ''; $n1 = '';

				$reg_time = $a->created_at;
				$expiry_date = $reg_time->addDays(3);    
				$expiry_date = $expiry_date->getTimestamp();  

				if($curr < $expiry_date) {
					$n1 = "New/";
				}

				$formDetail = FormLaravel::with('SubscribersLaravel','PackageDetailLaravel')->first();
				$installer = StaffDetailLaravel::where('_id', $a->installer_id)->where('position','Installer')->first();
				$contractor = CompanyLaravel::where('_id', $a->contractor_id)->first();

				$inst_name = '';
				if(!empty($installer)){
					$inst_name = $installer->name;
				}

				array_push($nested_data, array(
					'index' => $i.$n1,
					'nature_work' => $a->nature_work,
					'wo'=>$a->wo,
					'customer_name' => $formDetail->SubscribersLaravel->name,
					'customer_phone' => $formDetail->SubscribersLaravel->phone1,
					'customer_unit' => $formDetail->SubscribersLaravel->unit_no,
					'customer_building' => $formDetail->SubscribersLaravel->building_name,
					'customer_postcode' => $formDetail->SubscribersLaravel->postcode,
					'customer_city' => $formDetail->SubscribersLaravel->city,
					'contractor_id' => $contractor->name,
					'installer_id' => $inst_name,
					'dateTimeEnd' => $a->dateTimeEnd,
					'status' => $a->status,
					'action' => $a->id,
				));
			}
		}				
		return \DataTables::of($nested_data)->make(true);	
    }

    public function filterContractorWork($year, $month, $status)
    {

    	$id = Auth::guard('contractor')->id();
		$user = StaffLaravel::with('StaffDetailLaravel')->find($id);
    	$curr = Carbon::now()->getTimestamp();

		if($year == 'null' && $month == 'null' & $status !='null')
		{
			$nested_data = array();
			$work_detail = WorkOrderLaravel::with('FormLaravel')->where('contractor_id',$user->StaffDetailLaravel->company_id)->orderBy('dateTimeStart', 'desc')->where('status', $status)->get();
			$i = 0;
			$nested_data = array();
			if(!empty($work_detail)){
				foreach ($work_detail as $a)
				{	
					$i++; $y = ''; $n1 = '';

					$reg_time = $a->created_at;
					$expiry_date = $reg_time->addDays(3);    
					$expiry_date = $expiry_date->getTimestamp();  

					if($curr < $expiry_date) {
						$n1 = "New/";
					}

					$formDetail = FormLaravel::with('SubscribersLaravel','PackageDetailLaravel')->first();
					$installer = StaffDetailLaravel::where('_id', $a->installer_id)->where('position','Installer')->first();
					$contractor = CompanyLaravel::where('_id', $a->contractor_id)->first();

					$inst_name = '';
					if(!empty($installer)){
						$inst_name = $installer->name;
					}

					array_push($nested_data, array(
						'index' => $i.$n1,
						'nature_work' => $a->nature_work,
						'wo'=>$a->wo,
						'customer_name' => $formDetail->SubscribersLaravel->name,
						'customer_phone' => $formDetail->SubscribersLaravel->phone1,
						'customer_unit' => $formDetail->SubscribersLaravel->unit_no,
						'customer_building' => $formDetail->SubscribersLaravel->building_name,
						'customer_postcode' => $formDetail->SubscribersLaravel->postcode,
						'customer_city' => $formDetail->SubscribersLaravel->city,
						'contractor_id' => $contractor->name,
						'installer_id' => $inst_name,
						'dateTimeEnd' => $a->dateTimeEnd,
						'status' => $a->status,
						'action' => $a->id,
					));
				}
			}			
		}

		if($year=='null' && $month == 'null' & $status == 'null')
		{
			$nested_data = array();
			$work_detail = WorkOrderLaravel::with('FormLaravel')->where('contractor_id',$user->StaffDetailLaravel->company_id)->orderBy('dateTimeStart', 'desc')->get();
			$i = 0;
			$nested_data = array();
			if(!empty($work_detail)){
				foreach ($work_detail as $a)
				{	
					$i++; $y = ''; $n1 = '';

					$reg_time = $a->created_at;
					$expiry_date = $reg_time->addDays(3);    
					$expiry_date = $expiry_date->getTimestamp();  

					if($curr < $expiry_date) {
						$n1 = "New/";
					}

					$formDetail = FormLaravel::with('SubscribersLaravel','PackageDetailLaravel')->first();
					$installer = StaffDetailLaravel::where('_id', $a->installer_id)->where('position','Installer')->first();
					$contractor = CompanyLaravel::where('_id', $a->contractor_id)->first();

					$inst_name = '';
					if(!empty($installer)){
						$inst_name = $installer->name;
					}

					array_push($nested_data, array(
						'index' => $i.$n1,
						'nature_work' => $a->nature_work,
						'wo'=>$a->wo,
						'customer_name' => $formDetail->SubscribersLaravel->name,
						'customer_phone' => $formDetail->SubscribersLaravel->phone1,
						'customer_unit' => $formDetail->SubscribersLaravel->unit_no,
						'customer_building' => $formDetail->SubscribersLaravel->building_name,
						'customer_postcode' => $formDetail->SubscribersLaravel->postcode,
						'customer_city' => $formDetail->SubscribersLaravel->city,
						'contractor_id' => $contractor->name,
						'installer_id' => $inst_name,
						'dateTimeEnd' => $a->dateTimeEnd,
						'status' => $a->status,
						'action' => $a->id,
					));
				}
			}			
		}

		if($year!='null' && $month!='nulll' && $status !='null')
		{
			$nested_data = array();
			$start_month = $year."-".$month."-01 00:00:00";
			$end_month = $year."-".$month."-32 23:59:59";

			$work_detail = WorkOrderLaravel::with('FormLaravel')->where('contractor_id',$user->StaffDetailLaravel->company_id)->orderBy('dateTimeStart', 'desc')->whereBetween('dateTimeStart', [$start_month, $end_month])->where('status',$status)->get();
			$i = 0;
			$nested_data = array();
			if(!empty($work_detail)){
				foreach ($work_detail as $a)
				{	
					$i++; $y = ''; $n1 = '';

					$reg_time = $a->created_at;
					$expiry_date = $reg_time->addDays(3);    
					$expiry_date = $expiry_date->getTimestamp();  

					if($curr < $expiry_date) {
						$n1 = "New/";
					}

					$formDetail = FormLaravel::with('SubscribersLaravel','PackageDetailLaravel')->first();
					$installer = StaffDetailLaravel::where('_id', $a->installer_id)->where('position','Installer')->first();
					$contractor = CompanyLaravel::where('_id', $a->contractor_id)->first();

					$inst_name = '';
					if(!empty($installer)){
						$inst_name = $installer->name;
					}

					array_push($nested_data, array(
						'index' => $i.$n1,
						'nature_work' => $a->nature_work,
						'wo'=>$a->wo,
						'customer_name' => $formDetail->SubscribersLaravel->name,
						'customer_phone' => $formDetail->SubscribersLaravel->phone1,
						'customer_unit' => $formDetail->SubscribersLaravel->unit_no,
						'customer_building' => $formDetail->SubscribersLaravel->building_name,
						'customer_postcode' => $formDetail->SubscribersLaravel->postcode,
						'customer_city' => $formDetail->SubscribersLaravel->city,
						'contractor_id' => $contractor->name,
						'installer_id' => $inst_name,
						'dateTimeEnd' => $a->dateTimeEnd,
						'status' => $a->status,
						'action' => $a->id,
					));
				}
			}		
		}

		if($year!='null' && $month!='null' && $status =='null')
		{
			$nested_data = array();
			$start_month = $year."-".$month."-01 00:00:00";
			$end_month = $year."-".$month."-32 23:59:59";

			$work_detail = WorkOrderLaravel::with('FormLaravel')->where('contractor_id',$user->StaffDetailLaravel->company_id)->orderBy('dateTimeStart', 'desc')->whereBetween('dateTimeStart', [$start_month, $end_month])->get();
			$i = 0;
			$nested_data = array();
			if(!empty($work_detail)){
				foreach ($work_detail as $a)
				{	
					$i++; $y = ''; $n1 = '';

					$reg_time = $a->created_at;
					$expiry_date = $reg_time->addDays(3);    
					$expiry_date = $expiry_date->getTimestamp();  

					if($curr < $expiry_date) {
						$n1 = "New/";
					}

					$formDetail = FormLaravel::with('SubscribersLaravel','PackageDetailLaravel')->first();
					$installer = StaffDetailLaravel::where('_id', $a->installer_id)->where('position','Installer')->first();
					$contractor = CompanyLaravel::where('_id', $a->contractor_id)->first();

					$inst_name = '';
					if(!empty($installer)){
						$inst_name = $installer->name;
					}

					array_push($nested_data, array(
						'index' => $i.$n1,
						'nature_work' => $a->nature_work,
						'wo'=>$a->wo,
						'customer_name' => $formDetail->SubscribersLaravel->name,
						'customer_phone' => $formDetail->SubscribersLaravel->phone1,
						'customer_unit' => $formDetail->SubscribersLaravel->unit_no,
						'customer_building' => $formDetail->SubscribersLaravel->building_name,
						'customer_postcode' => $formDetail->SubscribersLaravel->postcode,
						'customer_city' => $formDetail->SubscribersLaravel->city,
						'contractor_id' => $contractor->name,
						'installer_id' => $inst_name,
						'dateTimeEnd' => $a->dateTimeEnd,
						'status' => $a->status,
						'action' => $a->id,
					));
				}
			}		
		}

		return \DataTables::of($nested_data)->make(true);		
    }

    public function filterContractorDocket($year, $month)
    {
        $year = $year;
		$month = $month;
		$nested_data = array();
		$arr = array();
		$i=0;

		if($year=='null' && $month=='null')
		{
			$docket= DocketLaravel::orderBy('created_at', 'desc')->get();

			if(!empty($docket))
			{
				foreach ($docket as $a)
				{				
					$customer = Subscriber::where('_id', $a->customer_id)->first();
					$business = Business::where('_id', $a->customer_id)->first();				

					if(!empty($customer))
					{
						$arr[]=$a;
					}

					if(!empty($business))
					{
						$arr[]=$a;
					}										
				}
			}

			foreach($arr as $b)
			{
				$i++; $n1 = '';

				$tempContractor = CompanyLaravel::where('_id', $b->contractor_id)->first();
				$contractor = $tempContractor->name;

				$tempInstaller = StaffDetailLaravel::where('_id', $b->installer_id)->first();

				$tempCustomer = Subscriber::where('_id', $b->customer_id)->first();
				$tempBusiness = Business::where('_id', $b->customer_id)->first();

				if(!empty($tempCustomer))
				{
					$building = $tempCustomer->building;
				}
				else
				{
					$building = $tempBusiness->company_name;
				}

				if(!empty($tempInstaller))
				{
					array_push($nested_data, array(
						'index' => $n1.$i,
						'docket_id' => $b->docket_id,
						'work_order_id' => $b->work_order_id,
						'nature_work' => $b->nature_work,
						'contractor_id' => $contractor,
						'installer_name' => $tempInstaller->name,
						'customer_id' => $building,
						'installer_id' => $tempInstaller->phone,
						'end_job' => $b->end_job,
						'rating' => $b->Rating1
					));
				}
				else
				{
					array_push($nested_data, array(
						'index' => $n1.$i,
						'docket_id' => $a->docket_id,
						'work_order_id' => $a->work_order_id,
						'nature_work' => $a->nature_work,
						'contractor_id' => $contractor,
						'installer_name' => '',
						'customer_id' => $building,
						'installer_id' => '',
						'end_job' => $a->end_job,
						'rating' => $a->Rating1
					));
				}	
			}
		}

		elseif($year!='' && $month=='null')
		{
			$timestamp = $year."-01-01 00:00:00.000Z";
			$masa = strtotime($timestamp);
			$go = Carbon::createFromTimestamp($masa);
			$go2 = Carbon::createFromTimestamp($masa);
			$end_year = $go2->endOfYear();
			// $time = Carbon::createFromTimeString($timestamp);
			// echo $month;

			$docket = DocketLaravel::whereBetween('created_at', [$go, $end_year])->get();
			if(!empty($docket))
			{
				foreach ($docket as $a)
				{				
					$customer = Subscriber::where('_id', $a->customer_id)->first();
					$business = Business::where('_id', $a->customer_id)->first();				

					if(!empty($customer))
					{
						$arr[]=$a;
					}

					if(!empty($business))
					{
						$arr[]=$a;
					}										
				}
			}

			foreach($arr as $b)
			{
				$i++; $n1 = '';

				$tempContractor = CompanyLaravel::where('_id', $b->contractor_id)->first();
				$contractor = $tempContractor->name;

				$tempInstaller = StaffDetailLaravel::where('_id', $b->installer_id)->first();

				$tempCustomer = Subscriber::where('_id', $b->customer_id)->first();
				$tempBusiness = Business::where('_id', $b->customer_id)->first();

				if(!empty($tempCustomer))
				{
					$building = $tempCustomer->building;
				}
				else
				{
					$building = $tempBusiness->company_name;
				}

				if(!empty($tempInstaller))
				{
					array_push($nested_data, array(
						'index' => $n1.$i,
						'docket_id' => $b->docket_id,
						'work_order_id' => $b->work_order_id,
						'nature_work' => $b->nature_work,
						'contractor_id' => $contractor,
						'installer_name' => $tempInstaller->name,
						'customer_id' => $building,
						'installer_id' => $tempInstaller->phone,
						'end_job' => $b->end_job,
						'rating' => $b->Rating1
					));
				}
				else
				{
					array_push($nested_data, array(
						'index' => $n1.$i,
						'docket_id' => $a->docket_id,
						'work_order_id' => $a->work_order_id,
						'nature_work' => $a->nature_work,
						'contractor_id' => $contractor,
						'installer_name' => '',
						'customer_id' => $building,
						'installer_id' => '',
						'end_job' => $a->end_job,
						'rating' => $a->Rating1
					));
				}	
			}
		}

		elseif($year!='' && $month !='')
		{
			$timestamp = $year."-".$month."-01 00:00:00.000Z";
			$masa = strtotime($timestamp);
			$go = Carbon::createFromTimestamp($masa);
			$go2 = Carbon::createFromTimestamp($masa);
			$end_year = $go2->endOfMonth();
			// $time = Carbon::createFromTimeString($timestamp);

			$docket = DocketLaravel::whereBetween('created_at', [$go, $end_year])->get();
			if(!empty($docket))
			{
				foreach ($docket as $a)
				{				
					$customer = Subscriber::where('_id', $a->customer_id)->first();
					$business = Business::where('_id', $a->customer_id)->first();				

					if(!empty($customer))
					{
						$arr[]=$a;
					}

					if(!empty($business))
					{
						$arr[]=$a;
					}										
				}
			}

			foreach($arr as $b)
			{
				$i++; $n1 = '';

				$tempContractor = CompanyLaravel::where('_id', $b->contractor_id)->first();
				$contractor = $tempContractor->name;

				$tempInstaller = StaffDetailLaravel::where('_id', $b->installer_id)->first();

				$tempCustomer = Subscriber::where('_id', $b->customer_id)->first();
				$tempBusiness = Business::where('_id', $b->customer_id)->first();

				if(!empty($tempCustomer))
				{
					$building = $tempCustomer->building;
				}
				else
				{
					$building = $tempBusiness->company_name;
				}

				if(!empty($tempInstaller))
				{
					array_push($nested_data, array(
						'index' => $n1.$i,
						'docket_id' => $b->docket_id,
						'work_order_id' => $b->work_order_id,
						'nature_work' => $b->nature_work,
						'contractor_id' => $contractor,
						'installer_name' => $tempInstaller->name,
						'customer_id' => $building,
						'installer_id' => $tempInstaller->phone,
						'end_job' => $b->end_job,
						'rating' => $b->Rating1
					));
				}
				// else
				// {
				// 	array_push($nested_data, array(
				// 		'index' => $n1.$i,
				// 		'docket_id' => $a->docket_id,
				// 		'work_order_id' => $a->work_order_id,
				// 		'nature_work' => $a->nature_work,
				// 		'contractor_id' => $contractor,
				// 		'installer_name' => '',
				// 		'customer_id' => $building,
				// 		'installer_id' => '',
				// 		'end_job' => $a->end_job,
				// 		'rating' => $a->Rating1
				// 	));
				// }	
			}
		}

		return \DataTables::of($nested_data)->make(true);
    }

    public function getContractorTeam()
    {
    	$id = Auth::guard('contractor')->id();
		$user = Staff::with('StaffDetail')->find($id);
        $agent = Staff::with('Company','StaffDetail')->where('roles_access','Installer')->orderBy('updated_at','desc')->get();
        
        $i = 0;
        $nested_data = array();
        $curr = Carbon::now()->getTimestamp();
        foreach ($agent as $a)
        {
            $n1 = '';              
            
            $reg_time = $a->updated_at;
            $expiry_date = $reg_time->addDays(3);    
            $expiry_date = $expiry_date->getTimestamp(); 

            if($curr < $expiry_date) {
            	$n1 = "New/";
            } 

            if($a->company_id == $user->StaffDetail->company_id){
            	array_push($nested_data, array(
            		'index' => $n1.$i,
            		'user_pic' => $a->StaffDetail->user_pic,
            		'name' => $a->StaffDetail->name,
            		'ic' => $a->StaffDetail->ic,
            		'email' => $a->StaffDetail->email,
            		'phone' => $a->StaffDetail->phone,
            		'company_id' => $a->Company->name,
            		'position' => $a->StaffDetail->position,
            		'action' => $a->_id
            	));

            }
            $i++; 
        }
        return \DataTables::of($nested_data)->make(true);
    }
    
    public function addContractorTeam()
    {
    	$id = Auth::guard('contractor')->id();
		$user = Staff::with('StaffDetail')->find($id);

		$pp = count(WorkOrder::where('status','Pending Non Prelaid')->where('contractor_id',$user->StaffDetail->company_id)->get());
		$sp = count(WorkOrder::where('status','Success Non Prelaid')->where('contractor_id',$user->StaffDetail->company_id)->get());
		$rs = count(WorkOrder::where('status','Reschedule')->where('contractor_id',$user->StaffDetail->company_id)->get());
		$ss = count(WorkOrder::where('status','Suspend')->where('contractor_id',$user->StaffDetail->company_id)->get());
		$cm = count(WorkOrder::where('status','Completed')->where('contractor_id',$user->StaffDetail->company_id)->get());

        return view('contractor.add_contractor',compact('user','pp','sp','rs','ss','cm','pc','pi'));
    }

    public function requestAddContractorTeam(Request $request)
    {
        $validator = Validator::make($request->all(), [
			'password' => 'min:8|confirmed',
		]);

		if ($validator->fails()) {
			return redirect()->back()->withInput()->withErrors($validator);
		}

		$staff = Staff::where('email', $request->get('email'))->first();
        if(empty($staff))
        {
        	$id = Auth::guard('contractor')->id();
			$user = Staff::with('StaffDetail')->find($id);

			$pass = $this->encryptPassword('encrypt', $request->get('password'));

			$dealerD = new StaffDetail;		
			$dealerD->name = $request->get('aname');
			$dealerD->ic =  $request->get('ic');
			$dealerD->email = $request->get('email');
			$dealerD->phone = $request->get('phone');
			$dealerD->company_id = $user->StaffDetail->company_id;
			$dealerD->color = '';
			$dealerD->position = 'Installer';
			$dealerD->password = $pass;
			$dealerD->user_pic = 'assets/avatar/user.png';	

			// Save Login Dealer
			$loginD = new Staff;
			$loginD->email = $request->get('email');
			$loginD->password = $pass;
			$loginD->roles_access = 'Installer';
			$loginD->company_id = $user->StaffDetail->company_id;
			$loginD->last_login_at	= '';
			$loginD->last_login_ip	= ''; 

			// $loginData = [
			// 	'email' => $request->get('email'),
			// 	'password' => $pass,
			// 	'roles_access' => 'Sales',
			// 	'last_login_at'	=> '',
			// 	'last_login_ip'	=> '', 
			// ];

            $company = Company::where('_id', $user->StaffDetail->company_id)->first();
			$company->staff()->save($loginD);		
			$loginD->staffdetail()->save($dealerD);

			return redirect()->back()->with('success_msg', '<strong>Success!</strong> register <strong>'.$request->get('email').'</strong>');
		}
		else 
		{
			return redirect()->back()->withInput()->withErrors('Email already exist!');
		}
	}

	public function requestEditInstaller(Request $request)
    {

		$staff = Staff::with('StaffDetail')->where('_id', $request->get('_id'))->first();

        if(!empty($staff))
        {
        	$id = Auth::guard('contractor')->id();
			$user = Staff::with('StaffDetail')->find($id);

			if($request->get('password') != ''){

				$validator = Validator::make($request->all(), [
		    		'password' => 'min:8',
		    	]);

		    	if ($validator->fails()) {
		    		return redirect()->back()->withInput()->withErrors($validator);
		    	}
    	
				$pass = $this->encryptPassword('encrypt', $request->get('password'));
				$staff->email = $request->get('email');
				$staff->password = $pass;
				$staff->save();

				$staff->StaffDetail->name = $request->get('aname');
				$staff->StaffDetail->ic = $request->get('ic');
				$staff->StaffDetail->email = $request->get('email');
				$staff->StaffDetail->phone = $request->get('phone');
				$staff->StaffDetail->save();

				return redirect()->back()->with('success_msg', '<strong>Success!</strong> register <strong>'.$request->get('email').'</strong>');

			}else {

				$staff->email = $request->get('email');
				$staff->save();

				$staff->StaffDetail->name = $request->get('aname');
				$staff->StaffDetail->ic = $request->get('ic');
				$staff->StaffDetail->email = $request->get('email');
				$staff->StaffDetail->phone = $request->get('phone');
				$staff->StaffDetail->save();

				return redirect()->back()->with('success_msg', '<strong>Success!</strong> register <strong>'.$request->get('email').'</strong>');
			}

			
		}
		else 
		{
			return redirect()->back()->withInput()->withErrors('Email already exist!');
		}
	}

	public function deleteInstaller(Request $request){

    	$staff = Staff::where('_id',$request->id)->first();
		
		if(!empty($staff)){
			$st = StaffDetail::where('email',$staff->email)->first();
			if(!empty($st)){
				$st->delete();
				$staff->delete();
				return 'true';
			}
		
		}else {
			return 'false';
		}
    }
}