<?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 CustomerController extends Controller
{

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

    function createWorkID($limit){
		$number = WorkOrder::select('id','wo')->orderBy('created_at','DESC')->first();
		$numberOnly = str_replace('WO-','',$number->wo);
		$numberOnly++;
		return $numberOnly;

		$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 viewCustomer()
    {
    	$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());

		$coverage = Coverage::all();
		$company = Company::where('team','Dealer')->get();

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

    public function getAllNewCustomer($type,$building,$dealer){

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

		$i = 0; $n1 = ''; $street = ''; $labelD = '';
		$curr = Carbon::now()->getTimestamp();
		$nested_data = array();

		if($type == 'null' && $building == 'null' && $dealer == 'null'){

		$form = Form::with('Subscriber','PackageDetail','WorkOrder')->orderBy('created_at', 'desc')->take(2000)->get();

		}else if($type != 'null' && $building == 'null' && $dealer == 'null'){
			$form = Form::with('Subscriber','PackageDetail','WorkOrder')->where('type_service',$type)->orderBy('created_at', 'desc')->get();
		}else if($type != 'null' && $building != 'null' && $dealer == 'null'){
			$form = Form::with(['Subscriber' => function($q) use ($building)
				{
					$q->where('building_name', $building)->get();
				}],'PackageDetail','WorkOrder')->where('type_service',$type)->orderBy('created_at', 'desc')->get();
		}
		else if($type == 'null' && $building != 'null' && $dealer == 'null'){
			$form = Form::with(['Subscriber' => function($q) use ($building)
				{
					$q->where('building_name', $building)->get();
				}],'PackageDetail','WorkOrder')->orderBy('created_at', 'desc')->get();
		}
		else if($type == 'null' && $building == 'null' && $dealer != 'null'){
			$form = Form::with('Subscriber','PackageDetail','WorkOrder')->where('company_id',$dealer)->orderBy('created_at', 'desc')->get();
		}
		else if($type == 'null' && $building != 'null' && $dealer != 'null'){
			$form = Form::with(['Subscriber' => function($q) use ($building)
				{
					$q->where('building_name', $building)->get();
				}],'PackageDetail','WorkOrder')->where('company_id',$dealer)->orderBy('created_at', 'desc')->get();
		}
		else if($type != 'null' && $building == 'null' && $dealer != 'null'){
			$form = Form::with('Subscriber','PackageDetail','WorkOrder')->where('type_service',$type)->where('company_id',$dealer)->orderBy('created_at', 'desc')->get();
		}
		else if($type != 'null' && $building != 'null' && $dealer != 'null'){
			$form = Form::with(['Subscriber' => function($q) use ($building)
				{
					$q->where('building_name', $building)->get();
				}],'PackageDetail','WorkOrder')->where('type_service',$type)->where('company_id',$dealer)->orderBy('created_at', 'desc')->get();
		}
		if(!empty($form)){
			foreach ($form as $key => $f) {
				if(empty($f->WorkOrder)){
					$i++;

					$n1 = '';
					$reg_time = $f->created_at;
					$expiry_date = $reg_time->addDays(3);    
					$expiry_date = $expiry_date->getTimestamp(); 

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


					if(!empty($f->dealer_id)){
						$labelD = "D/";
					}else{
						$labelD = "";
					}
					if(!empty($f->Subscriber)){
						if($f->Subscriber->street != ''){
							$street = $f->Subscriber->street;
						}

						$wo = '';
						if($f->status_email == 'verified'){
							$work_order = '';
							if($f->type_application == 'R'){
								do {
									$work_order = 'WO-'.$this->createWorkID(4);
								} while (WorkOrder::where("wo", "=", $work_order)->first() instanceof WorkOrder);

								$wo = $work_order.'/'.$f->Subscriber->subscriber_id;
								$cov = Coverage::where('building_name',$f->Subscriber->building_name)->where('Type','R')->first();
								if(!empty($cov)){
									if($cov->status_building == 'non prelaid'){
										$wo = 'Non/'.$work_order.'/'.$f->Subscriber->subscriber_id;
									}
								}

							}else if($f->type_application == 'B'){
								do {
									$work_order = 'WO-'.$this->createWorkID(4);
								} while (WorkOrder::where("wo", "=", $work_order)->first() instanceof WorkOrder);
								$wo = $work_order.'/'.$f->Subscriber->subscriber_id;
								$cov = Coverage::where('building_name',$f->Subscriber->building_name)->where('Type','B')->first();
								if(!empty($cov)){
									if($cov->status_building == 'non prelaid'){
										$wo = 'Non/'.$work_order.'/'.$f->Subscriber->subscriber_id;
									}
								}
							
							}

						}else if($f->status_email == 'unverified'){
							$wo = '';
						}

						$building = ''; $unit = '-'; $address = ''; $name = '';
						if($f->type_application == 'R'){
							$name = $f->Subscriber->name;
							$building = $f->Subscriber->building_name;
							$unit = $f->Subscriber->unit_no;

							if($f->Subscriber->street != ''){
								$address = $f->Subscriber->street. ' , '.$f->Subscriber->postcode. ' , '.$f->Subscriber->city. ' , '.$f->Subscriber->state;
							}else {
								$address = $f->Subscriber->postcode. ' , '.$f->Subscriber->city. ' , '.$f->Subscriber->state;
							}

						}else if($f->type_application == 'B'){

							$name = $f->Subscriber->company_name;
							if($f->Subscriber->unit_no == ''){
								$unit = '-';
							}else {
								$unit = $f->Subscriber->unit_no;
							}

							$building = $f->Subscriber->street;

							$address = $f->Subscriber->postcode. ' , '.$f->Subscriber->city. ' , '.$f->Subscriber->state;
						}

						$nP = '';
						
						array_push($nested_data, array(
							'formT' => $n1.$i.$f->type_application,
							'type' => $f->type_service,
							'name' => $labelD.$name,
							'phone' => $f->Subscriber->phone1,
							'unit' => $unit,
							'building' => $building,
							'street' => $address,
							// 'postcode' => $f->Subscriber->postcode,
							// 'city' => $f->Subscriber->city,
							'need_phone' => $nP,
							'email' => $f->status_email,
							'action1' => $wo,
							'action2' => $f->_id
						));
					}
				}
			}
		}

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

    public function getAllNewCustomerss($type,$building,$dealer){

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

		$i = 0; $n1 = ''; $street = ''; $labelD = '';
		$curr = Carbon::now()->getTimestamp();
		$nested_data = array();

		$customer = Subscriber::where('_id','5cb5444ecfe8c571a302d054')->first();
		$package = PackageDetail::where('_id','5cb5444ecfe8c571a302d054')->first();
		$wo = WorkOrder::where('_id','5cb5444ecfe8c571a302d054')->first();

		$f = Form::where('test','ayaya')->first();
		dd($f);

		$form = Form::with('PackageDetail','WorkOrder','Subscriber')->orderBy('created_at', 'desc')->where('_id','5cb5444ecfe8c571a302d054')->first();
		

		if($type == 'null' && $building == 'null' && $dealer == 'null'){
			$form = Form::with('Subscriber','PackageDetail','WorkOrder')->orderBy('created_at', 'desc')->get();
		}else if($type != 'null' && $building == 'null' && $dealer == 'null'){
			$form = Form::with('Subscriber','PackageDetail','WorkOrder')->where('type_service',$type)->orderBy('created_at', 'desc')->get();
		}else if($type != 'null' && $building != 'null' && $dealer == 'null'){
			$form = Form::with(['Subscriber' => function($q) use ($building)
				{
					$q->where('building_name', $building)->get();
				}],'PackageDetail','WorkOrder')->where('type_service',$type)->orderBy('created_at', 'desc')->get();
		}
		else if($type == 'null' && $building != 'null' && $dealer == 'null'){
			$form = Form::with(['Subscriber' => function($q) use ($building)
				{
					$q->where('building_name', $building)->get();
				}],'PackageDetail','WorkOrder')->orderBy('created_at', 'desc')->get();
		}
		else if($type == 'null' && $building == 'null' && $dealer != 'null'){
			$form = Form::with('Subscriber','PackageDetail','WorkOrder')->where('company_id',$dealer)->orderBy('created_at', 'desc')->get();
		}
		else if($type == 'null' && $building != 'null' && $dealer != 'null'){
			$form = Form::with(['Subscriber' => function($q) use ($building)
				{
					$q->where('building_name', $building)->get();
				}],'PackageDetail','WorkOrder')->where('company_id',$dealer)->orderBy('created_at', 'desc')->get();
		}
		else if($type != 'null' && $building == 'null' && $dealer != 'null'){
			$form = Form::with('Subscriber','PackageDetail','WorkOrder')->where('type_service',$type)->where('company_id',$dealer)->orderBy('created_at', 'desc')->get();
		}
		else if($type != 'null' && $building != 'null' && $dealer != 'null'){
			$form = Form::with(['Subscriber' => function($q) use ($building)
				{
					$q->where('building_name', $building)->get();
				}],'PackageDetail','WorkOrder')->where('type_service',$type)->where('company_id',$dealer)->orderBy('created_at', 'desc')->get();
		}

		if(!empty($form)){
			foreach ($form as $key => $f) {
				// if(empty($f->WorkOrder)){
					$i++;

					$n1 = '';
					$reg_time = $f->created_at;
					$expiry_date = $reg_time->addDays(3);    
					$expiry_date = $expiry_date->getTimestamp(); 

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


					if(!empty($f->dealer_id)){
						$labelD = "D/";
					}else{
						$labelD = "";
					}

					if(!empty($f->Subscriber)){
						if($f->Subscriber->street != ''){
							$street = $f->Subscriber->street;
						}

						$wo = '';
						if($f->status_email == 'verified'){

							$work_order = '';
							if($f->type_application == 'R'){

								do {
									$work_order = 'WO-'.$this->createWorkID(4);
								} while (WorkOrder::where("wo", "=", $work_order)->first() instanceof WorkOrder);

								$wo = $work_order.'/'.$f->Subscriber->subscriber_id;
								$cov = Coverage::where('building_name',$f->Subscriber->building_name)->where('Type','R')->first();
								if(!empty($cov)){
									if($cov->status_building == 'non prelaid'){
										$wo = 'Non/'.$work_order.'/'.$f->Subscriber->subscriber_id;
									}
								}

							}else if($f->type_application == 'B'){

								do {
									$work_order = 'WO-'.$this->createWorkID(4);
								} while (WorkOrder::where("wo", "=", $work_order)->first() instanceof WorkOrder);

								$wo = $work_order.'/'.$f->Subscriber->subscriber_id;
								$cov = Coverage::where('building_name',$f->Subscriber->building_name)->where('Type','B')->first();
								if(!empty($cov)){
									if($cov->status_building == 'non prelaid'){
										$wo = 'Non/'.$work_order.'/'.$f->Subscriber->subscriber_id;
									}
								}
							
							}

						}else if($f->status_email == 'unverified'){
							$wo = '';
						}

						array_push($nested_data, array(
							$f->_id,
							// 'formT' => $n1.$i.$f->type_application,
							// 'type' => $f->type_service,
							// 'name' => $labelD.$f->Subscriber->name,
							// 'phone' => $f->Subscriber->phone1,
							// 'unit' => $f->Subscriber->unit_no,
							// 'building' => $f->Subscriber->building_name,
							// 'street' => $street,
							// 'postcode' => $f->Subscriber->postcode,
							// 'city' => $f->Subscriber->city,
							// 'email' => $f->status_email,
							// 'action1' => $wo,
							// 'action2' => $f->_id
						));
					}
				// }
			}
		}
		dd($nested_data);
    	return \DataTables::of($nested_data)->make(true);
    }

    public function deleteFormCustomer(Request $request){

    	$form = Form::where('_id',$request->id)->first();
		
		if(!empty($form)){
			$form->delete();
			return 'true';
		}else {
			return 'false';
		}
    }

    public function editSubscriber($subscriber_id){

    	$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());

		$coverage = Coverage::all();
    	$form = Subscriber::with('Form')->where('_id',$subscriber_id)->first();
    	return view('customer-service.edit_subscriber',compact('user','pp','sp','rs','ss','cm','form','coverage'));
    }

    public function updateCustomerDetail(Request $request){
    	$form = Subscriber::with('Form')->where('subscriber_id',$request->subscriber_id)->first();

    	$phone = ''; $street = ''; $fax = '';
    	if($request->phone2 != null){
    		$phone = $request->phone2;
    	}

    	if($form->Form->type_application == 'R'){

    		if($request->street != null){
	    		$street = $request->street;
	    	}

			$cov = Coverage::where('building_name',$request->building)->first();
			
			if(!empty($cov)){
				$building = $cov->building_name;
				$postcode = $cov->postcode;
				$city = $cov->city;
				$state = $cov->state;
			}else {
				$building = $request->building;
				$postcode = '-'; 
				$city = '-'; 
				$state = '-';
			}

	    	$form->name = $request->name;
	    	$form->ic = $request->ic;
	    	$form->email = $request->email;
	    	$form->phone1 = $request->phone1;
	    	$form->phone2 = $phone;
	    	$form->unit_no = $request->unit_no;
	    	$form->building_name = $building;
	    	$form->street = $street;
	    	$form->city = $city;
	    	$form->postcode = $postcode;
	    	$form->state = $state;
	    	$form->save();

	    	return redirect()->back()->with('success_msg', 'Success! Update customer '.$request->get('name'));

	    }else if($form->Form->type_application == 'B'){

	    	if($request->company_fax != null){
	    		$fax = $request->company_fax;
	    	}

	    	$form->company_reg = $request->company_reg;
	    	$form->company_num = $request->company_num;
	    	$form->company_fax = $fax;
	    	$form->company_name = $request->company_name;
	    	$form->unit_no = $request->unit_no;
	    	$form->street = $request->address;
	    	$form->city = $request->city;
	    	$form->postcode = $request->postcode;
	    	$form->state = $request->state;

	    	$form->name = $request->name;
	    	$form->ic = $request->ic;
	    	$form->designation = $request->designation;
	    	$form->email = $request->email;
	    	$form->phone1 = $request->phone1;
	    	$form->phone2 = $phone;
	    	$form->save();

	    	return redirect()->back()->with('success_msg', 'Success! Update customer '.$request->get('name'));
	    }
	     
    }

    public function generateRPDF($subscriber_id) {

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

		$product = Product::where('formT','R')->orderBy('created_at','asc')->get();
		$form = Subscriber::with('Form')->where('subscriber_id',$subscriber_id)->first();
		
		$package = PackageDetail::where('_id',$form->_id)->first();
		$created_at = Carbon::parse($form->created_at)->toDateTimeString();

		$ext1 = pathinfo(public_path().$form->front_ic, PATHINFO_EXTENSION);
		$ext2 = pathinfo(public_path().$form->back_ic, PATHINFO_EXTENSION);

		$ext3 = pathinfo(public_path().$form->visaF, PATHINFO_EXTENSION);
		$ext4 = pathinfo(public_path().$form->visaB, PATHINFO_EXTENSION);

		$ext5 = pathinfo(public_path().$form->paymentReceipt, PATHINFO_EXTENSION);
		$ext6 = pathinfo(public_path().$form->soForm, PATHINFO_EXTENSION);

		$documentPath = 'document/'.$subscriber_id;

		$created = $form->Form->created_at->toDateString();
		// dd($created . $created_at);
	
		$total = floatval($package->montly_fee) + floatval($package->deposit) + floatval($package->voice_fee) + floatval($package->upfront_payment);
		// dd($total);
		$pdf = PDF::loadView('pdf.residential-pdf', compact('form','package','product','ext1','ext2','ext3','ext4','ext5','ext6','created_at','created'));
		$pdf->setPaper('A4', 'potrait');

		if($ext1 == "pdf" || $ext2 == "pdf" || $ext3 == "pdf" || $ext4 == "pdf" || $ext5 == "pdf" || $ext6 == "pdf" ){
			$pdf->save(public_path().'/'.$documentPath.'/application.pdf');
			$merges = PDFMerger::init();
			$merges->addPDF(public_path().'/'.$documentPath.'/application.pdf', 'all');
			if($ext1 == "pdf"){
			$merges->addPDF(public_path().$form->front_ic,'all');
			}
			if($ext2 == "pdf"){
			$merges->addPDF(public_path().$form->back_ic,'all');
			}
			if($ext3 == "pdf"){
			$merges->addPDF(public_path().$form->visaF,'all');
			}
			if($ext4 == "pdf"){
			$merges->addPDF(public_path().$form->visaB,'all');
			}
			if($ext5 == "pdf"){
				$merges->addPDF(public_path().$form->paymentReceipt,'all');
			}
			if($ext6 == "pdf"){
				$merges->addPDF(public_path().$form->soForm,'all');
			}
			$merges->merge();
			$merges->save(public_path().'/'.$documentPath.'/'.$subscriber_id.'.pdf',"browser");

		}else if(($ext1 == "jpeg" || $ext1 == "jpg" || $ext1 == "png" ) || ($ext2 == "jpeg" || $ext2 == "jpg" || $ext2 == "png" ) || 
		($ext3 == "jpeg" || $ext3 == "jpg" || $ext3 == "png" ) ||($ext4 == "jpeg" || $ext4 == "jpg" || $ext4 == "png" ) ||
		($ext5 == "jpeg" || $ext5 == "jpg" || $ext5 == "png" ) ||($ext6 == "jpeg" || $ext6 == "jpg" || $ext6 == "png" )){
			return $pdf->stream();
		}else{
			return $pdf->stream();
		}
		
    }

    public function redirectPDF($sid){
    	$form = Subscriber::with('Form')->where('_id',$sid)->first();
    	if($form->Form->type_application == 'R'){
    		return redirect('/customer-service/residential/generate-pdf/'.$form->subscriber_id);
    	}else if($form->Form->type_application == 'B'){
    		return redirect('/customer-service/business/generate-pdf/'.$form->subscriber_id);
    	}
    }

    public function generateBPDF($subscriber_id) {

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

		$product = Product::where('formT','B')->get();
		$form = Subscriber::with('Form')->where('subscriber_id',$subscriber_id)->first();
		$package = PackageDetail::where('_id',$form->_id)->first();
		$dateSubmittion = date('d/m/Y', strtotime($form->created_at));

		$ext1 = pathinfo(public_path().$form->front_ic, PATHINFO_EXTENSION);
		$ext2 = pathinfo(public_path().$form->back_ic, PATHINFO_EXTENSION);

		$ext3 = pathinfo(public_path().$form->form9_44, PATHINFO_EXTENSION);

		$ext4 = pathinfo(public_path().$form->paymentReceipt, PATHINFO_EXTENSION);
		$ext5 = pathinfo(public_path().$form->soForm, PATHINFO_EXTENSION);

		$documentPath = 'document/'.$subscriber_id;

		// $pdf = PDF::loadView('pdf.business-pdf', compact('form','package','product','ext1','ext2','ext3','ext4','ext5','ext6','dateSubmittion'));
		if(strtotime($form->created_at) >= 1580774399){
			$pdf = PDF::loadView('pdf.newBusiness-pdf', compact('form','package','product','ext1','ext2','ext3','ext4','ext5','dateSubmittion'));
		}else {
			$pdf = PDF::loadView('pdf.oldBusiness-pdf', compact('form','package','product','ext1','ext2','ext3','ext4','ext5','ext6','dateSubmittion'));
		}
		
		$pdf->setPaper('A4', 'potrait');

		
		if($ext1 == "pdf" || $ext2 == "pdf" || $ext3 == "pdf" || $ext4 == "pdf" || $ext5 == "pdf" ){
			$pdf->save(public_path().'/'.$documentPath.'/application.pdf');
			$merges = PDFMerger::init();
			$merges->addPDF(public_path().'/'.$documentPath.'/application.pdf', 'all');
			if($ext1 == "pdf"){
			$merges->addPDF(public_path().$form->front_ic,'all');
			}
			if($ext2 == "pdf"){
			$merges->addPDF(public_path().$form->back_ic,'all');
			}
			if($ext3 == "pdf"){
			$merges->addPDF(public_path().$form->form9_44,'all');
			}
			if($ext4 == "pdf"){
				$merges->addPDF(public_path().$form->paymentReceipt,'all');
			}
			if($ext5 == "pdf"){
				$merges->addPDF(public_path().$form->soForm,'all');
			}
			$merges->merge();
			$merges->save(public_path().'/'.$documentPath.'/'.$subscriber_id.'.pdf',"browser");

		}else if(($ext1 == "jpeg" || $ext1 == "jpg" || $ext1 == "png" ) || ($ext2 == "jpeg" || $ext2 == "jpg" || $ext2 == "png" ) || 
		($ext3 == "jpeg" || $ext3 == "jpg" || $ext3 == "png" ) ||($ext4 == "jpeg" || $ext4 == "jpg" || $ext4 == "png" ) ||
		($ext5 == "jpeg" || $ext5 == "jpg" || $ext5 == "png" )){
			return $pdf->stream();
		}else {
			return $pdf->stream();
		}
}

    public function viewSubscriber()
    {
    	$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());

		$rec = count(WorkOrder::where('nature_work','Rectification')->get());
		$re = count(Form::where('type_application','R')->get());
		$bu = count(Form::where('type_application','B')->get());

		$coverage = Coverage::all();
		$company = Company::where('team','Dealer')->get();

    	return view('customer-service.view_subscriber', compact('user','pp','sp','rs','ss','cm','rec','re','bu','coverage','company'));
    }

    public function getAllRectification($type,$building,$dealer){

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

		$i = 0; $n1 = ''; $street = ''; $labelD = ''; $wo = '';
		$curr = Carbon::now()->getTimestamp();
		$nested_data = array();

		if($type == 'null' && $building == 'null' && $dealer == 'null'){
			$form = Form::with('Subscriber','PackageDetail','WorkOrder')->orderBy('created_at', 'desc')->get();
		}else if($type != 'null' && $building == 'null' && $dealer == 'null'){
			$form = Form::with('Subscriber','PackageDetail','WorkOrder')->where('type_service',$type)->orderBy('created_at', 'desc')->get();
		}else if($type != 'null' && $building != 'null' && $dealer == 'null'){
			$form = Form::with(['Subscriber' => function($q) use ($building)
				{
					$q->where('building_name', $building)->get();
				}],'PackageDetail','WorkOrder')->where('type_service',$type)->orderBy('created_at', 'desc')->get();
		}
		else if($type == 'null' && $building != 'null' && $dealer == 'null'){
			$form = Form::with(['Subscriber' => function($q) use ($building)
				{
					$q->where('building_name', $building)->get();
				}],'PackageDetail','WorkOrder')->orderBy('created_at', 'desc')->get();
		}
		else if($type == 'null' && $building == 'null' && $dealer != 'null'){
			$form = Form::with('Subscriber','PackageDetail','WorkOrder')->where('company_id',$dealer)->orderBy('created_at', 'desc')->get();
		}
		else if($type == 'null' && $building != 'null' && $dealer != 'null'){
			$form = Form::with(['Subscriber' => function($q) use ($building)
				{
					$q->where('building_name', $building)->get();
				}],'PackageDetail','WorkOrder')->where('company_id',$dealer)->orderBy('created_at', 'desc')->get();
		}
		else if($type != 'null' && $building == 'null' && $dealer != 'null'){
			$form = Form::with('Subscriber','PackageDetail','WorkOrder')->where('type_service',$type)->where('company_id',$dealer)->orderBy('created_at', 'desc')->get();
		}
		else if($type != 'null' && $building != 'null' && $dealer != 'null'){
			$form = Form::with(['Subscriber' => function($q) use ($building)
				{
					$q->where('building_name', $building)->get();
				}],'PackageDetail','WorkOrder')->where('type_service',$type)->where('company_id',$dealer)->orderBy('created_at', 'desc')->get();
		}

		$wo = 'null'; $do = 'null';
		if(!empty($form)){
			foreach ($form as $key => $f) {
				
				if(!empty($f->WorkOrder)){

					if($f->WorkOrder->nature_work == "Rectification" || $f->type_service == "Rectification") {
						$wo = $f->WorkOrder->wo; 

						if($f->WorkOrder->status == "Completed"){
							$doc = Docket::where('work_order_id',$f->WorkOrder->wo)->first();
							if(!empty($doc)){
								$do = $doc->docket_id;
							}	
						}else{
							$wo  = $f->WorkOrder->wo; 
							$do = "null";
						}

						$i++;

						$n1 = '';
						$reg_time = $f->created_at;
						$expiry_date = $reg_time->addDays(3);    
						$expiry_date = $expiry_date->getTimestamp(); 

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


						if(!empty($f->dealer_id)){
							$labelD = "D/";
						}

						if(!empty($f->Subscriber)){
							if($f->Subscriber->street != ''){
								$street = $f->Subscriber->street;
							}

							$name = '';
							if($f->type_application == 'R'){
								$name = $f->Subscriber->name;
							}else if($f->type_application == 'B'){
								$name = $f->Subscriber->building_name;
							}

							array_push($nested_data, array(
								'formT' => $n1.$i.$f->type_application,
								'submittion' => Carbon::parse($f->created_at)->toDateString(),
								'type' => $f->type_service,
								'name' => $labelD.$name,
								'phone' => $f->Subscriber->phone1,
								'unit' => $f->Subscriber->unit_no,
								'building' => $f->Subscriber->building_name,
								'street' => $street,
								'postcode' => $f->Subscriber->postcode,
								'city' => $f->Subscriber->city,
								'action1' => $f->type_application.'/'.$f->Subscriber->subscriber_id,
								'action2' => $wo,
								'action3' => $do
							));
						}
					}
				}
			}
		}

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

    public function getAllResidential($type,$building,$dealer){

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

		$i = 0; $n1 = ''; $street = ''; $labelD = ''; $wo = '';
		$curr = Carbon::now()->getTimestamp();
		$nested_data = array();

		if($type == 'null' && $building == 'null' && $dealer == 'null'){
			$form = Form::with('Subscriber','PackageDetail','WorkOrder')->orderBy('created_at', 'desc')->take(2000)->get();
		}else if($type != 'null' && $building == 'null' && $dealer == 'null'){
			$form = Form::with('Subscriber','PackageDetail','WorkOrder')->where('type_service',$type)->orderBy('created_at', 'desc')->get();
		}else if($type != 'null' && $building != 'null' && $dealer == 'null'){
			$form = Form::with(['Subscriber' => function($q) use ($building)
				{
					$q->where('building_name', $building)->get();
				}],'PackageDetail','WorkOrder')->where('type_service',$type)->orderBy('created_at', 'desc')->get();
		}
		else if($type == 'null' && $building != 'null' && $dealer == 'null'){
			$form = Form::with(['Subscriber' => function($q) use ($building)
				{
					$q->where('building_name', $building)->get();
				}],'PackageDetail','WorkOrder')->orderBy('created_at', 'desc')->get();
		}
		else if($type == 'null' && $building == 'null' && $dealer != 'null'){
			$form = Form::with('Subscriber','PackageDetail','WorkOrder')->where('company_id',$dealer)->orderBy('created_at', 'desc')->get();
		}
		else if($type == 'null' && $building != 'null' && $dealer != 'null'){
			$form = Form::with(['Subscriber' => function($q) use ($building)
				{
					$q->where('building_name', $building)->get();
				}],'PackageDetail','WorkOrder')->where('company_id',$dealer)->orderBy('created_at', 'desc')->get();
		}
		else if($type != 'null' && $building == 'null' && $dealer != 'null'){
			$form = Form::with('Subscriber','PackageDetail','WorkOrder')->where('type_service',$type)->where('company_id',$dealer)->orderBy('created_at', 'desc')->get();
		}
		else if($type != 'null' && $building != 'null' && $dealer != 'null'){
			$form = Form::with(['Subscriber' => function($q) use ($building)
				{
					$q->where('building_name', $building)->get();
				}],'PackageDetail','WorkOrder')->where('type_service',$type)->where('company_id',$dealer)->orderBy('created_at', 'desc')->get();
		}

		$wo = 'null'; $do = 'null';
		if(!empty($form)){
			foreach ($form as $key => $f) {

				
				
				if(!empty($f->WorkOrder)){
					$wo = $f->WorkOrder->wo; 

					if($f->WorkOrder->status == "Completed"){
						$doc = Docket::where('work_order_id',$f->WorkOrder->wo)->first();
						if(!empty($doc)){
							$do = $doc->docket_id;
						}	
					}else{
						$wo  = $f->WorkOrder->wo; 
						$do = "null";
					}
				}else {
					$wo  = "null";
					$do = "null";
				}


				if($f->type_application == 'R' && $f->type_service != "Rectification"){
					$i++;

					$n1 = '';
					$reg_time = $f->created_at;
					$expiry_date = $reg_time->addDays(3);    
					$expiry_date = $expiry_date->getTimestamp(); 

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


					if(!empty($f->dealer_id)){
						$labelD = "D/";
					}else {
						$labelD = "";
					}

					if(!empty($f->Subscriber)){
						if($f->Subscriber->street != ''){
							$street = $f->Subscriber->street;
						}

						array_push($nested_data, array(
							'formT' => $n1.$i.$f->type_application,
							'submittion' => Carbon::parse($f->created_at)->toDateString(),
							'type' => $f->type_service,
							'name' => $labelD.$f->Subscriber->name,
							'phone' => $f->Subscriber->phone1,
							'unit' => $f->Subscriber->unit_no,
							'building' => $f->Subscriber->building_name,
							'street' => $street,
							'postcode' => $f->Subscriber->postcode,
							'city' => $f->Subscriber->city,
							'action1' => $f->type_application.'/'.$f->Subscriber->subscriber_id,
							'action2' => $wo,
							'action3' => $do
						));
					}
				}
			}
		}

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

    public function getAllBusiness($type,$building,$dealer){

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

		$i = 0; $n1 = ''; $street = ''; $labelD = ''; $wo = '';
		$curr = Carbon::now()->getTimestamp();
		$nested_data = array();

		if($type == 'null' && $building == 'null' && $dealer == 'null'){
			$form = Form::with('Subscriber','PackageDetail','WorkOrder')->orderBy('created_at', 'desc')->take(2000)->get();
		}else if($type != 'null' && $building == 'null' && $dealer == 'null'){
			$form = Form::with('Subscriber','PackageDetail','WorkOrder')->where('type_service',$type)->orderBy('created_at', 'desc')->get();
		}else if($type != 'null' && $building != 'null' && $dealer == 'null'){
			$form = Form::with(['Subscriber' => function($q) use ($building)
				{
					$q->where('building_name', $building)->get();
				}],'PackageDetail','WorkOrder')->where('type_service',$type)->orderBy('created_at', 'desc')->get();
		}
		else if($type == 'null' && $building != 'null' && $dealer == 'null'){
			$form = Form::with(['Subscriber' => function($q) use ($building)
				{
					$q->where('building_name', $building)->get();
				}],'PackageDetail','WorkOrder')->orderBy('created_at', 'desc')->get();
		}
		else if($type == 'null' && $building == 'null' && $dealer != 'null'){
			$form = Form::with('Subscriber','PackageDetail','WorkOrder')->where('company_id',$dealer)->orderBy('created_at', 'desc')->get();
		}
		else if($type == 'null' && $building != 'null' && $dealer != 'null'){
			$form = Form::with(['Subscriber' => function($q) use ($building)
				{
					$q->where('building_name', $building)->get();
				}],'PackageDetail','WorkOrder')->where('company_id',$dealer)->orderBy('created_at', 'desc')->get();
		}
		else if($type != 'null' && $building == 'null' && $dealer != 'null'){
			$form = Form::with('Subscriber','PackageDetail','WorkOrder')->where('type_service',$type)->where('company_id',$dealer)->orderBy('created_at', 'desc')->get();
		}
		else if($type != 'null' && $building != 'null' && $dealer != 'null'){
			$form = Form::with(['Subscriber' => function($q) use ($building)
				{
					$q->where('building_name', $building)->get();
				}],'PackageDetail','WorkOrder')->where('type_service',$type)->where('company_id',$dealer)->orderBy('created_at', 'desc')->get();
		}

		$wo = 'null'; $do = 'null';
		if(!empty($form)){
			foreach ($form as $key => $f) {
				if(!empty($f->WorkOrder)){
					$wo = $f->WorkOrder->wo; 

					if($f->WorkOrder->status == "Completed"){
						$doc = Docket::where('work_order_id',$f->WorkOrder->wo)->first();
						if(!empty($doc)){
							$do = $doc->docket_id;
						}	
					}else{
						$wo  = $f->WorkOrder->wo; 
						$do = "null";
					}
				}else {
					$wo  = "null";
					$do = "null";
				}


				if($f->type_application == 'B' && $f->type_service != "Rectification"){
					$i++;

					$n1 = '';
					$reg_time = $f->created_at;
					$expiry_date = $reg_time->addDays(3);    
					$expiry_date = $expiry_date->getTimestamp(); 

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


					if(!empty($f->dealer_id)){
						$labelD = "D/";
					}else {
						$labelD = "";
					}

					if(!empty($f->Subscriber)){
						if($f->Subscriber->street != ''){
							$street = $f->Subscriber->street;
						}

						array_push($nested_data, array(
							'formT' => $n1.$i.$f->type_application,
							'submittion' => Carbon::parse($f->created_at)->toDateString(),
							'type' => $f->type_service,
							'name' => $labelD.$f->Subscriber->company_name,
							'phone' => $f->Subscriber->phone1,
							'unit' => $f->Subscriber->unit_no,
							'building' => $f->Subscriber->building_name,
							'street' => $street,
							'postcode' => $f->Subscriber->postcode,
							'city' => $f->Subscriber->city,
							'action1' => $f->type_application.'/'.$f->Subscriber->subscriber_id,
							'action2' => $wo,
							'action3' => $do
						));
					}
				}
			}
		}

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


    public function getCustomerWo()
    {
    	$curr = Carbon::now()->getTimestamp();
    	$work_detail= WorkOrderLaravel::with('FormLaravel')->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 filterCustomerWo($year, $month, $status)
    {
    	$curr = Carbon::now()->getTimestamp();

    	if($year == 'null' && $month == 'null' & $status !='null')
		{
			$nested_data = array();
			$work_detail = WorkOrderLaravel::with('FormLaravel')->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/";
					}else {
						$n1 = "";
					}

					$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')->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/";
					}else {
						$n1 = "";
					}

					$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')->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/";
					}else {
						$n1 = "";
					}

					$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')->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/";
					}else {
						$n1 = "";
					}

					$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 deleteCustomerWo(Request $request)
    {
    	$wo = WorkOrderLaravel::where('_id',$request->id)->first();
		
		if(!empty($wo)){
			$wo->delete();
			return 'true';
		}else {
			return 'false';
		}
    }

    public function getCountry()
    {
    	$jsonString = file_get_contents(base_path('resources/views/customer-service/country.json'));
 		$data = json_decode($jsonString, true);

 		return $jsonString;
    }

    public function getBuilding()
    {
    	$wK = Coverage::all();

    	$data = array(); 
		foreach ($wK as $key=>$w) {
			array_push($data, array(
				'name' => $w->address,
			));
		}

		// Read and parse our events JSON file into an array of event data arrays.
		$json = json_encode($data);
			
		// Send JSON to the client.
		echo $json;
    }
}
