<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Staff;
use App\Models\StaffAdmin;
use App\Models\BuilderAdmin;
use App\Models\Builder;
use App\Models\Record;
use App\Models\Location;
use App\Models\PreStartChecklist;
use App\Models\Hazard;
use App\Models\Inspection;
use App\Models\OnSiteStaff;
use App\Models\RecordImage;
use Illuminate\Support\Facades\Validator;
use Carbon\Carbon;
use DB;
use Spatie\ImageOptimizer\OptimizerChainFactory;

class RecordController extends Controller
{
    
    public function store(Request $request)
    {
        $validateUser = Validator::make($request->all(), 
            [
                'staff_id' => 'required|exists:staff,id',
                'builder_id' => 'required|exists:builder_admins,id',
                //'location_id' => 'required|exists:locations,id',
                
                
            ]);
        if($validateUser->fails()){
                return response()->json([
                    'status' => false,
                   
                    'message' => $validateUser->errors()->first()
                ], 401);
            }
        
        
        $staff_id = $request->input('staff_id');
        $builder_id = $request->input('builder_id');
        $location_id = $request->input('location_id');
        $damage = $request->input('damage');
        
        $staff = Staff::where('id',$staff_id)->first();
        $builder = BuilderAdmin::where('id',$builder_id)->first();
        if($location_id)
        {
            $location = Location::where('id',$location_id)->first();
        }
        else
        {
            $location = $request->input('location');
            $dataa = new Location;
            $dataa->name = $location;
            $dataa->loc_lat = "";
            $dataa->loc_long = "";
            $dataa->save();
            $location_id = $dataa->id;
           $location = Location::where('id',$location_id)->first(); 
        }
        $data = new Record;
        $data->staff_name = $staff->name;
        $data->staff_id = $staff_id;
        $data->company = "Allscape";
        $data->builder_name = $builder->name;
        $data->builder_id = $builder_id;
        $data->location = $location->name;
        $data->location_id = $location_id;
        $data->location_lat = $location->loc_lat;
        $data->location_long = $location->loc_long;
        $data->damage = $damage;
        $data->save();
        $record_id = $data->id;
        
        $pre_start = $request->input('pre_start');    
        foreach($pre_start as $pre)
        {
            $savepre = new PreStartChecklist;
            $savepre->record_id = $record_id;
            $savepre->site_signage = $pre['site_signage'];
            $savepre->contact_numbers = $pre['contact_numbers'];
            $savepre->msds_sheets = $pre['msds_sheets'];
            $savepre->fire_extinguisher = $pre['fire_extinguisher'];
            $savepre->washroom_facility = $pre['washroom_facility'];
            $savepre->sub_cont_drient = $pre['sub_cont_drient'];
            $savepre->w_safety = $pre['w_safety'];
            $savepre->ad_supply_eyewash = $pre['ad_supply_eyewash'];
            $savepre->utility_clearence = $pre['utility_clearence'];
            $savepre->public_protection = $pre['public_protection'];
            $savepre->communication_device = $pre['communication_device'];
            $savepre->other = $pre['other'];
            $savepre->save();
        }
        
        $inspection = $request->input('inspection');    
        foreach($inspection as $insp)
        {
            $save_insp = new Inspection;
            $save_insp->record_id = $record_id;
            $save_insp->emergency_response = $insp['i_emergency_response'];
            $save_insp->first_aid_kit = $insp['i_first_aid_kit'];
            $save_insp->ladders_walkway = $insp['i_ladders_walkway'];
            $save_insp->lockout_tagout = $insp['i_lockout_tagout'];
            $save_insp->electrical_panel = $insp['i_electrical_panel'];
            $save_insp->ppe = $insp['i_ppe'];
            $save_insp->fire_extinguisher = $insp['i_fire_extinguisher'];
            $save_insp->signage = $insp['i_signage'];
            $save_insp->msds = $insp['i_msds'];
            $save_insp->access_egress = $insp['i_access_egress'];
            $save_insp->tools = $insp['i_tools'];
            $save_insp->housekeeping = $insp['i_housekeeping'];
            $save_insp->guardrail = $insp['i_guardrail'];
            $save_insp->utilities = $insp['i_utilities'];
            $save_insp->fall_protection = $insp['i_fall_protection'];
            $save_insp->other = $insp['i_other'];
            $save_insp->save();
        }
        
        $hazard = $request->input('hazard');
        foreach($hazard as $h) {
          $hazards = new Hazard;
          $hazards->record_id = $record_id;
          $hazards->rank = $h['severity'];
          $hazards->hazard = $h['hazard_probability'];
          $hazards->detail = $h['hazard_detail'];
          $hazards->save();
        }
        
        $staffOnSite = $request->input('staffonsite');
        foreach($staffOnSite as $s) {
          $hazards = new OnSiteStaff;
          $hazards->record_id = $record_id;
          $hazards->detail = $s['detail'];
          $hazards->save();
        }
        
        $images = $request->input('site_images');
        foreach($images as $image) {
          $hazards = new RecordImage;
          $hazards->record_id = $record_id;
          $hazards->image = $image['image'];
          $hazards->save();
        }
        
        return response()->json([
                'status' => true,
                'message' => 'success',
                'data'=>'',
            ], 200);
            
    }
    
    public function imageUpload(Request $request)
    {
        if($request->hasFile('image')) {
            
           /* $mediaFiles = $request->image;
                //$path = $mediaFiles->store('public/ADSimages');
               $originName = $request->file('image')->getClientOriginalName();
            $fileName = pathinfo($originName,PATHINFO_FILENAME);
            $extension = $request->file('image')->getClientOriginalExtension();
            $fileName = $fileName.'_'.time().'.'.$extension;
                ///$name = $mediaFiles->getClientOriginalName();
                //$mediaFiles->file('images')->move(public_path().'/ADSimages/', $name);
                $mediaFiles->move(public_path().'/site_images/', $fileName);
                //store image file into directory and db
            $fileurl = url('/site_images/').'/'.$fileName;*/
         
        $image =  $request->image;
 
            // Generate a unique filename for the uploaded image
            $imagename = time().'.'.$image->getClientOriginalExtension();
             
            // Set the path to save the original image
            $imagepath = public_path('/images_dummy/');
             
            // Set the path to save the compressed image
            $pathToOutput = public_path('/site_images/');
 
            // Save the original image
            $image->move($imagepath, $imagename);
 
            // Compress image and save it to optimizedImage path using Spatie's OptimizerChainFactory 
            $optimizerChain = OptimizerChainFactory::create();
            $optimizerChain->optimize($imagepath.$imagename,$pathToOutput.$imagename);
 
            // Delete the original image
            unlink($imagepath.$imagename);
         $fileurl = url('/site_images/').'/'.$imagename;
         
         
         
         
         return response()->json([
                'status' => true,
                'message' => 'success',
                'data'=>$imagename,
                'fileurl'=>$fileurl
            ], 200);
        }
        else
        {
           return response()->json([
                'status' => false,
                'message' => 'error',
                'data'=>'',
            ], 400);
        }
    }
    
    public function reportList(Request $request)
    {
        $validateUser = Validator::make($request->all(), 
            [
                'builder_id' => 'required|exists:builders,id',
            ]);
        if($validateUser->fails()){
                return response()->json([
                    'status' => false,
                    
                    'message' => $validateUser->errors()->first()
                ], 401);
            }
        $builder = Builder::where('id',$request->builder_id)->first();
        $builderAdmin = $builder->admin_id;
        $data = Record::select('records.*','builder_admins.id as builder_id','builder_admins.name as builder_name','staff.id as staff_id','staff.name as staff_name')->join('builder_admins','builder_admins.id','=','records.builder_id')->join('staff','staff.id','=','records.staff_id')->where('records.status',1)->where('records.builder_id',$builderAdmin)->get();
        $dame = array();
        foreach($data as $d)
        {
            $k['id'] = $d->id;
            $k['staff_id'] = $d->staff_id;
            $k['builder_id'] = $d->builder_id;
            $k['location_id'] = $d->location_id;
            $k['staff_name'] = $d->staff_name;
            $k['builder_name'] = $d->builder_name;
            $k['company'] = $d->company;
            $k['location'] = $d->location;
            $k['location_lat'] = $d->location_lat;
            $k['location_long'] = $d->location_long;
            $k['date'] = Carbon::parse($d->created_at)->format('d-m-Y');
            $k['time'] = Carbon::parse($d->created_at)->format('h:i A');
            $dame[] = $k;
        }
        
        return response()->json([
                'status' => true,
                'message' => 'success',
                'data'=>$dame,
            ], 200);
    }
    
    
    public function reportListByBuilderAdmin(Request $request)
    {
        $validateUser = Validator::make($request->all(), 
            [
                'builder_id' => 'required|exists:staff,id',
            ]);
        if($validateUser->fails()){
                return response()->json([
                    'status' => false,
                    
                    'message' => $validateUser->errors()->first()
                ], 401);
            }
        //$builder = Builder::where('id',$request->builder_id)->first();
        $builderAdmin = $request->builder_id;
        $data = Record::select('records.*','builder_admins.id as builder_id','builder_admins.name as builder_name','staff.id as staff_id','staff.name as staff_name')->join('builder_admins','builder_admins.id','=','records.builder_id')->join('staff','staff.id','=','records.staff_id')->where('records.status',1)->where('records.staff_id',$builderAdmin)->get();
        $dame = array();
        foreach($data as $d)
        {
            $k['id'] = $d->id;
            $k['staff_id'] = $d->staff_id;
            $k['builder_id'] = $d->builder_id;
            $k['location_id'] = $d->location_id;
            $k['staff_name'] = $d->staff_name;
            $k['builder_name'] = $d->builder_name;
            $k['company'] = $d->company;
            $k['location'] = $d->location;
            $k['location_lat'] = $d->location_lat;
            $k['location_long'] = $d->location_long;
            $k['date'] = Carbon::parse($d->created_at)->format('d-m-Y');
            $k['time'] = Carbon::parse($d->created_at)->format('h:i A');
            $dame[] = $k;
        }
        
        return response()->json([
                'status' => true,
                'message' => 'success',
                'data'=>$dame,
            ], 200);
    }
    
    public function imageDelete(Request $request)
    {
        unlink("site_images/".$request->image);
        return response()->json([
                'status' => true,
                'message' => 'success',
                'data'=>"",
            ], 200);
    }
    
    public function reportDetail(Request $request)
    {
        $imagepat = url('/site_images');
        $validateUser = Validator::make($request->all(), 
            [
                'record_id' => 'required|exists:records,id',
            ]);
        if($validateUser->fails()){
                return response()->json([
                    'status' => false,
                    
                    'message' => $validateUser->errors()->first()
                ], 401);
            }
        $id = $request->record_id;
        $builder = BuilderAdmin::where('status',1)->get();
        $staff = Staff::where('status',1)->get();
        $recorddata = Record::where('id',$id)->first();
        $precheckList = PreStartChecklist::where('record_id',$id)->first();
        //prechecklist
        $prechecklistArray = array();
        if($precheckList->site_signage==1)
        {
            $prechecklistArray[] = "construction Site Signage";
        }
        if($precheckList->contact_numbers==1)
        {
            $prechecklistArray[] = "Contact Numbers";
        }
        if($precheckList->msds_sheets==1)
        {
            $prechecklistArray[] = "MSDS Sheets";
        }
        if($precheckList->fire_extinguisher==1)
        {
            $prechecklistArray[] = "Fire Extinguisher";
        }
        if($precheckList->washroom_facility==1)
        {
            $prechecklistArray[] = "Washroom Facility";
        }
        if($precheckList->sub_cont_drient==1)
        {
            $prechecklistArray[] = "Sub-Cont Drient";
        }
        if($precheckList->w_safety==1)
        {
            $prechecklistArray[] = "Workplace Safety Act+reg";
        }
        if($precheckList->ad_supply_eyewash==1)
        {
            $prechecklistArray[] = "Cirst AD Supply Eyewash";
        }
        if($precheckList->utility_clearence==1)
        {
            $prechecklistArray[] = "Exe.permit/ Utility Clearence";
        }
        if($precheckList->public_protection==1)
        {
            $prechecklistArray[] = "Public Protection";
        }
        if($precheckList->communication_device==1)
        {
            $prechecklistArray[] = "Communication Device";
        }
        if($precheckList->other==1)
        {
            $prechecklistArray[] = "Other";
        }
        //prechecklist
        
        $inspectionList = Inspection::where('record_id',$id)->first();
        //inspection List
        $inspectionArray = array();
        
        if($inspectionList->emergency_response)
        {
            $inspectionArray[] ="Emergency Response";
        }
        if($inspectionList->first_aid_kit)
        {
            $inspectionArray[] ="First Aid Kit";
        }
        if($inspectionList->ladders_walkway)
        {
            $inspectionArray[] ="Ladders Walkways";
        }
        if($inspectionList->lockout_tagout)
        {
            $inspectionArray[] ="Lockout Tagolt";
        }
        if($inspectionList->electrical_panel)
        {
            $inspectionArray[] ="Electrical Parel";
        }
        if($inspectionList->ppe)
        {
            $inspectionArray[] ="PPE";
        }
        if($inspectionList->fire_extinguisher)
        {
            $inspectionArray[] ="Fire Extinguisher";
        }
        if($inspectionList->signage)
        {
            $inspectionArray[] ="Signage";
        }
        if($inspectionList->msds)
        {
            $inspectionArray[] ="MSDS Sheets";
        }
        if($inspectionList->access_egress)
        {
            $inspectionArray[] ="Access/Egress";
        }
        if($inspectionList->tools)
        {
            $inspectionArray[] ="Tools+Equipment";
        }
        if($inspectionList->housekeeping)
        {
            $inspectionArray[] ="Housekeeping";
        }
        if($inspectionList->guardrail)
        {
            $inspectionArray[] ="Guardrail";
        }
        if($inspectionList->utilities)
        {
            $inspectionArray[] ="Utilities";
        }
        if($inspectionList->fall_protection)
        {
            $inspectionArray[] ="Heights/Fall Protection";
        }
        if($inspectionList->other)
        {
            $inspectionArray[] ="Other";
        }
        //inspection List
        $images = RecordImage::select('id','record_id',DB::raw("(CASE WHEN image!='' THEN concat('$imagepat','/',image) ELSE '' END) as image"))->where('record_id',$id)->get();
        $hazard = Hazard::where('record_id',$id)->get();
        $hazardArray = array();
        if($hazard != [])
        {
            foreach($hazard as $haz)
            {
                if($haz->hazard=='A')
                {
                    $g['hazard'] = $haz->hazard.' - Probable, (immediately or soon)';
                }
                if($haz->hazard=='B')
                {
                    $g['hazard'] = $haz->hazard.' - Reasonably Probable, (eventually)';
                }
                if($haz->hazard=='C')
                {
                    $g['hazard'] = $haz->hazard.' - Remote, (could at same point)';
                }
                if($haz->hazard=='D')
                {
                    $g['hazard'] = $haz->hazard.' - Extremely Remote, (not likely)';
                }
                if($haz->rank=='1')
                {
                    $g['rank'] = $haz->rank.' - Immediate Danger,(death disaster)';
                }
                if($haz->rank=='2')
                {
                    $g['rank'] = $haz->rank.' - Serious Injury,(major injury, damage)';
                }
                if($haz->rank=='3')
                {
                    $g['rank'] = $haz->rank.' - Minor,(non serious injury, damage)';
                }
                if($haz->rank=='4')
                {
                    $g['rank'] = $haz->rank.' - Negligible,(first aid or less)';
                }
                if($haz->rank=='5')
                {
                    $g['rank'] = $haz->rank.' - Not Applicable';
                }
                
                $g['detail'] = $haz->detail;
                $hazardArray[] = $g;
            }
        }
        $onSiteStaff = OnSiteStaff::select('detail')->where('record_id',$id)->get();
        $data = array('recorddata'=>$recorddata,'precheckList'=>$prechecklistArray,'inspectionList'=>$inspectionArray,'images'=>$images,'hazard'=>$hazardArray,'builder'=>$builder,'staff'=>$staff,'onSiteStaff'=>$onSiteStaff);
        return response()->json([
                'status' => true,
                'message' => 'success',
                'data'=>$data,
            ], 200);
            
    }
    
}
