<?php

namespace App\Http\Controllers\CustomerService;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use LynX39\LaraPdfMerger\Facades\PdfMerger;

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\WorkOrder;
use App\Model\PackageDetail;
use App\Model\Company;
use App\Model\Coverage; 
use App\Model\Product; 
use App\Model\Docket; 

class TeamController extends Controller
{

	function random_code($limit) {
        return substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, $limit);
    }

    function createWorkID($limit){
		$allowedNumbers = range(0, 9);
		shuffle($allowedNumbers);
		$digits = array_rand($allowedNumbers, $limit);
		$number = '';
		
		foreach($digits as $d){
			$number .= $allowedNumbers[$d];
		}
		$unique_id = $number;
		return $unique_id;
	}

	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 viewCustomerTeam()
    {
    	$id = Auth::guard('cs')->id();
		$user = Staff::with('StaffDetail')->find($id);

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

    	return view('customer-service.view_contractor',compact('user','pp','sp','rs','ss','cm'));
    }

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

        $agent = Staff::with('Company','StaffDetail')->where('roles_access','Contractor')->orderBy('created_at', 'desc')->get();
        $curr = Carbon::now()->getTimestamp();
        
        $i = 0;
        $nested_data = array();
        foreach ($agent as $a)
        {
        	$i++;
        	$n1 = '';
        	$reg_time = $a->updated_at;
        	$expiry_date = $reg_time->addDays(3);    
        	$expiry_date = $expiry_date->getTimestamp(); 

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

        	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
        	));
        }
        return \DataTables::of($nested_data)->make(true);
    }

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

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

		$company = Company::where('team','CBB')->get();

    	return view('customer-service.view_contractor_form',compact('user','pp','sp','rs','ss','cm','company'));
    }

    public function requestAddContractor(Request $request){

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

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

    	$encrP = $this->encryptPassword('encrypt', $request->password);
    	$company = Company::where('_id',$request->vendor)->first();

    	$exist = Staff::with('StaffDetail')->where('email',$request->email)->where('roles_access','Contractor')->first();
    	if(empty($exist)){
    		$sl = Staff::create([
	    		'email' => $request->email,
	    		'password' => $encrP,
	    		'roles_access' => 'Contractor',
	    		'company_id' => $request->vendor,
	    		'last_login_at' => '',
	    		'last_login_ip'=> ''
	    	]);

	    	$sdl = new StaffDetail();
	    	$sdl->name = $request->aname;
	    	$sdl->ic = $request->ic;
	    	$sdl->email = $request->email;
	    	$sdl->phone = $request->phone;
	    	$sdl->company_id = $request->vendor;
	    	$sdl->color = $company->color;
	    	$sdl->position = 'Contractor';
	    	$sdl->password = $encrP;
	    	$sdl->user_pic = 'assets/avatar/user.png';

	    	$company->staff()->save($sl);
	    	$company->save();
	    	$sl->staffdetail()->save($sdl);

	    	return redirect()->back()->with('success_msg', '<strong>Success!</strong> add <strong>'.$request->get('aname').'</strong> as new contractor ');

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

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

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

		$company = Company::where('team','CBB')->get();
		$contractor = Staff::with('StaffDetail')->where('_id',$contractor)->first();

    	return view('customer-service.edit_contractor',compact('user','pp','sp','rs','ss','cm','company','contractor'));
    }

    public function requestEditContractor(Request $request){

    	$exist = Staff::with('StaffDetail')->where('_id',$request->contractor_id)->first();
    	$company = Company::where('_id',$request->vendor)->first();

    	if(empty($exist)){
    		return redirect()->back()->withInput()->withErrors('Contractor not found');
    	}else {

    		$exist->email = $request->email;
    		$exist->company_id = $request->vendor;
    		$exist->save();

    		$exist->StaffDetail->name = $request->aname;
	    	$exist->StaffDetail->ic = $request->ic;
	    	$exist->StaffDetail->email = $request->email;
	    	$exist->StaffDetail->phone = $request->phone;
	    	$exist->StaffDetail->company_id = $request->vendor;
	    	$exist->StaffDetail->save();
	    	
	    	$company->staff()->save($exist);
	    	$company->save();

	    	return redirect()->back()->with('success_msg', '<strong>Success!</strong> update <strong>'.$request->get('aname').'</strong> as new contractor ');
    	}
    }

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

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

    	return view('customer-service.view_vendor',compact('user','pp','sp','rs','ss','cm'));
    }

    public function getCustomerVendor() {
    	$i=0;
    	$team = Company::where('team','CBB')->get();
     	$nested_data = array();
    	foreach ($team as $a)
        {
        	$i++; $n1 = '';                        
        	array_push($nested_data, array(
        		'index' => $n1.$i,
        		'name' => $a->name,
        		'address' => $a->address,
        		'city' => $a->city,
        		'state' => $a->state,
        		'postcode' => $a->postcode,
        		'action' => $a->_id
        	));
        }
        return \DataTables::of($nested_data)->make(true);
    }

    function random_color_part() {
    	return str_pad( dechex( mt_rand( 0, 255 ) ), 2, '0', STR_PAD_LEFT);
	}

	function random_color() {
    	return $this->random_color_part() . $this->random_color_part() . $this->random_color_part();
	}

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

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

		$colors = array();
		for($i = 0; $i < 19; $i++){
			$colors[] = '#'.$this->random_color();
		}

    	return view('customer-service.view_vendor_form', compact('user','pp','sp','rs','ss','cm','colors'));
    }

    public function requesAddVendor(Request $request){

    	$sl = Company::create([
    		'name' => $request->cname,
    		"address" => $request->address,
		    "city" => $request->city,
		    "state" => $request->state,
		    "postcode" => $request->postcode,
		    "color" => $request->color,
		    "team" => "CBB",
    	]);

    	return redirect()->back()->with('success_msg', '<strong>Success!</strong> add <strong>'.$request->get('cname').'</strong> as new vendor ');
    }

    public function editVendor($vendor){

    	$id = Auth::guard('cs')->id();
		$user = Staff::with('StaffDetail')->find($id);

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

		$vendor = Company::find($vendor);

		return view('customer-service.edit_vendor', compact('user','pp','sp','rs','ss','cm','vendor'));
    }

    public function requesEditVendor(Request $request){

     	$company = Company::where('_id',$request->company_id)->first();
     	if(!empty($company)){
     		$company->name = $request->cname;
	    	$company->address = $request->address;
			$company->city = $request->city;
			$company->state = $request->state;
			$company->postcode = $request->postcode;
			$company->save();

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

     	}else {
     		return redirect()->back()->with('error_msg', '<strong>Failed!</strong> update <strong>'.$request->get('cname').'</strong> detail. No company exist!');
     	}
    }

    public function requestDeleteVendor(Request $request)
    {
    	$company = Company::where('_id',$request->id)->first();
		
		if(!empty($company)){
			$company->delete();
			return 'true';
		}else {
			return 'false';
		}
    }

    public function requestDeleteContractor(Request $request)
    {
    	$staff = Staff::where('_id',$request->id)->first();
		
		if(!empty($staff)){
			$staff->delete();
			return 'true';
		}else {
			return 'false';
		}
    }

}