<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Api\BaseController;
use Illuminate\Support\Facades\Auth;

Use App\Model\DealerClaim;
Use App\Model\Docket;
Use App\Model\WorkOrder;
use App\Model\StaffDetail;
use App\Model\Company;
use App\Staff;

use Carbon\Carbon;

class ClaimedController extends BaseController
{
    /*********************************** 
	/*   API to get claimed data
	***********************************/
	public function get_data_claim(){

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

		$dateS = Carbon::createFromFormat('Y-m-d', '2019-01-01');
        $start = $dateS->copy()->startOfDay();
        $dateE = Carbon::createFromFormat('Y-m-d', '2020-12-31');
        $end = $dateE->copy()->endOfDay();

        $result = array();
		$data = DealerClaim::with('Subscriber','Staff')->whereBetween('created_at', array($start, $end))->get();

        if(count($data) > 0) {
			foreach($data as $f) {	

				$name = ''; $contact_no = ''; $building = '';
				$labelD = ''; $service = ''; $rating = ''; 
				$installer_name =''; $contractor_name=''; $submitted_date='';

				if(!empty($f->dealer)){
					$c = Company::find($f->dealer);
					$labelD = $c->name;
				}else{
					$labelD = "";
				}

				if(!empty($f->wo)){
					$wo = WorkOrder::where('wo',$f->wo)->get();
					foreach($wo as $wo) {	
						$installer = StaffDetail::where('_id',$wo->installer_id)->get();
							foreach($installer as $installer) {	
							$installer_name = $installer->name;
							}
						$contractor = Company::where('_id',$wo->contractor_id)->get();
							foreach($contractor as $contractor) {	
							$contractor_name = $contractor->name;
							}
					}
				}

				if(!empty($f->Subscriber)){
					if($f->formT == 'R'){
						$name = $f->Subscriber->name;
						$contact_no = $f->Subscriber->phone1;
						$building = $f->Subscriber->building_name;
					}else if($f->formT == 'B'){
						$name = $f->Subscriber->company_name;
						$contact_no = $f->Subscriber->company_num;
						$building = $f->Subscriber->street;
					}
				
				if(!empty($f->docket)){
					$docket = Docket::where('docket_id',$f->docket)->get();
					foreach($docket as $d) {	
						$service = $d->nature_work;
						$rating = $d->Rating1;
                        $submitted_date = $d->end_job;
					}
				}
						
					array_push($result,array(
						"Dealer Name" => $labelD,
						"Installer Name" => $installer_name,
						"Contractor Name" => $contractor_name,
						"Customer Name"=> $name,
						"Contact Number"=> $contact_no,
						"Completion Date" => $f->activated_dt,
						"Form Type" => $f->formT,
						"Package"=> $f->package,
						"WO No" => $f->wo,
						"DO No" => $f->docket,
						"Service Type" => $service,
						"Building"=> $building,
						"Rating" => $rating,
						"Claim Amount" => $f->total_claim,
                        "Submitted Date" => $submitted_date,
					));	
				}	

			}
		}
		return json_encode($result);
    }
}