<?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 DocketController 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 viewDocket()
    {
    	$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_docket',compact('user','pp','sp','rs','ss','cm'));
    }

    public function getCustomerDocket($year,$month,$day)
    {
    	if($year == 'null' && $month == 'null' && $day == 'null'){
    		$docket= Docket::with('WorkOrder')->orderBy('created_at', 'desc')->get();
    	}else if($year != 'null' && $month == 'null' && $day == 'null'){

    		$timestamp = $year."-01-01 00:00:00.000Z";
			$masa = strtotime($timestamp);
			$go = Carbon::createFromTimestamp($masa);
			$go2 = Carbon::createFromTimestamp($masa);
			$end_year = $go2->endOfYear();

			$docket = Docket::with('WorkOrder')->orderBy('created_at', 'desc')->whereBetween('created_at', [$go, $end_year])->get();

    	}else if($year != 'null' && $month != 'null' && $day == 'null'){

    		$timestamp = $year."-".$month."-01 00:00:00.000Z";
			$masa = strtotime($timestamp);
			$go = Carbon::createFromTimestamp($masa);
			$go2 = Carbon::createFromTimestamp($masa);
			$end_year = $go2->endOfMonth();

			$docket = Docket::with('WorkOrder')->orderBy('created_at', 'desc')->whereBetween('created_at', [$go, $end_year])->get();
    	}

    	$i = 0; $n1 = ''; $building = '';
    	$curr = Carbon::now()->getTimestamp();
    	$tempD = array();
		$nested_data = array();
    	if(!empty($docket)){
    		foreach($docket as $d){

    			$i++; 
                if(!empty($d->WorkOrder->_id)){
        			$form = Form::with('Subscriber','PackageDetail')->where('_id',$d->WorkOrder->_id)->first();
        			$company = Company::where('_id', $d->WorkOrder->contractor_id)->first();
        			$installer = Staff::with('StaffDetail')->withTrashed()->where('_id', $d->installer_id)->first();

        			if($form->type_application == 'R'){
        				$building = $form->Subscriber->building_name;
        			}else if($form->type_application == 'B'){
        				$building = $form->Subscriber->company_name;
        			}

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

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

    				array_push($tempD, array(
    	    			'index' => $n1.$i,
    	    			'docket_id' => $d->docket_id,
    	    			'work_order_id' => $d->work_order_id,
    	    			'nature_work' => $d->nature_work,
    	    			'contractor_id' => $company->name,
    	    			'installer_name' => $installer->StaffDetail->name,
    	    			'customer_id' => $building,
    	    			'installer_id' => $installer->StaffDetail->phone,
    	    			'end_job' => date('d/m/Y H:i', strtotime($d->end_job)),
    	    			'rating' => round((($d->Rating1 + $d->Rating2 + $d->Rating3)/15) * 100)."%",
                        'action' => $d->docket_id.'/'.$d->work_order_id
    	    		));
                }
    		}
    	}

    	foreach($tempD as $t){
    		array_push($nested_data, array(
    			'index' => $t['index'],
    			'docket_id' => $t['docket_id'],
    			'work_order_id' => $t['work_order_id'],
    			'nature_work' => $t['nature_work'],
    			'contractor_id' => $t['contractor_id'],
    			'installer_name' => $t['installer_name'],
    			'customer_id' => $t['customer_id'],
    			'installer_id' => $t['installer_id'],
    			'end_job' => $t['end_job'],
    			'rating' =>$t['rating'],
                'action' =>$t['action'],
    		));
    	}

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

    public function generateDocketPDF($do)
    {
    	$id = Auth::guard('cs')->id();
		$user = Staff::with('StaffDetail')->find($id);
        $docket = Docket::with('WorkOrder')->where('docket_id',$do)->first();
        if(!empty($docket)){
            $form = Form::with('Subscriber','PackageDetail')->where('_id',$docket->WorkOrder->_id)->first();

            $address = '';
            if($form->type_application == 'R'){
                if($form->Subscriber->street != ''){
                    $address = $form->Subscriber->unit_no. ' , '.$form->Subscriber->building_name. ' , '.$form->Subscriber->street. ' , '.$form->Subscriber->postcode. ' , '.$form->Subscriber->city. ' , '.$form->Subscriber->state;
                }else {
                    $address = $form->Subscriber->unit_no. ' , '.$form->Subscriber->building_name. ' , '.$form->Subscriber->postcode. ' , '.$form->Subscriber->city. ' , '.$form->Subscriber->state;
                }

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

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

            }

            $product = Product::where('formT',$form->type_application)->where('speed',$form->PackageDetail->name)->first();
            $installer = Staff::with('StaffDetail')->where('_id',$docket->installer_id)->withTrashed()->first();

            if(empty($product)){
                $product = 'RMbps';
            }else {
                $product = $product->package_name;
            }

            $dateTime =  Carbon::parse($docket->WorkOrder->dateTimeStart)->toDateTimeString();
            $edateTime =  Carbon::parse($docket->end_job)->toDateTimeString();

            $pdf = PDF::loadView('pdf.docket-pdf',compact('docket','form','address','product','installer','dateTime','edateTime'));
            $pdf->setPaper('A4', 'potrait');
            return $pdf->stream();
        }
    }
}