File "Helper.php"

Full path: /home/qooetu/costes.qooetu.com/app/Helpers/Helper.php
File size: 57.11 B (57.11 KB bytes)
MIME-type: text/x-php
Charset: utf-8

Download   Open   Edit   Advanced Editor &nnbsp; Back

<?php // Code within app\Helpers\Helper.php

namespace App\Helpers;
use Illuminate\Support\Facades\Input;
use Modules\Backend\Entities\Upload;
use Auth;
use Response;
use App\User;
use Session;
use Validator;
use Redirect;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
use Modules\UserManagement\Entities\Role;
use Modules\Reseller\Entities\Reseller;
use Modules\Authority\Entities\ContentSetting;
use Modules\UserManagement\Entities\CSetting;
use Modules\Authority\Entities\AuthorityHaulage;
use Modules\UserManagement\Entities\Haulage;
use Modules\Authority\Entities\UnitRate;
use Modules\Authority\Entities\NewEstimatePbcwork;
use Modules\Authority\Entities\EstimateSelfInspection;
use Modules\Authority\Entities\EstimationHaulage;
use Modules\Authority\Entities\Estimate;
use App\AuthoritySetting;
use Mail;
use Entrust;
use Modules\Authority\Entities\AppSetting;
use App\RoleUser as UserRole;
class Helper
{



  public static function getHaulageSummary($estimation)
  {
    $sum=round($estimation->haulage->sum('total_cost'))*$estimation->total_period;
       return $sum;
  }

  public static function getRoleUsers($name){
  $role=Role::where('name',$name)->first();
  $models=UserRole::where(['role_id'=>$role->id])->get();
   $users=array();
    foreach($models as $user){
    $users[]=$user->user_id;
    }
    return $users;
}


  public static function getDirectCost($estimation)
  {
     
    $total_pbcworks=floor(self::getPBCTotal($estimation));
      
    
    $haulage=self::getHaulageSummary($estimation);
      
    $direct_cost=$total_pbcworks+$haulage;
     return floor($direct_cost);
  }

  public static function getOverheadCost($estimation)
  {

    $direct_cost=Self::getDirectCost($estimation);
    $indirect_cost=Self::getInDirectCost($estimation);
    $sum=$direct_cost+$indirect_cost;
    $overhead_percentage=$estimation->overhead_and_profit;
     if($overhead_percentage>0)
     {
      $overhead_percentage=$overhead_percentage/100;
     }else{
      $overhead_percentage=0;
     }
    
    $overheadcost=$overhead_percentage*$sum;
     return floor($overheadcost);

  }

  public static function getProjectCostWithoutOverhead($estimation)
  {
    $direct_cost=Self::getDirectCost($estimation);
    $indirect_cost=Self::getInDirectCost($estimation);
    $sum=$direct_cost+$indirect_cost;
    return floor($sum);

  }

   public static function getProject($estimation)
  {
    $direct_cost=Self::getDirectCost($estimation);
    $indirect_cost=Self::getInDirectCost($estimation);
    $overhead=Self::getOverheadCost($estimation);
    $sum=$direct_cost+$indirect_cost+$overhead;
    return floor( $sum);

  }


  public static function getVAT($estimation)
  {
     if($estimation->vat>0)
     {
      $vat_percent=$estimation->vat/100;
    }else{
      $vat_percent=$estimation->vat/100;
    }
     
     $project_cost=Self::getProject($estimation);
    $sum=$vat_percent*$project_cost;
    return floor($sum);

  }


  public static function TotalProjectCost($estimation)
  {
     $vat=self::getVAT($estimation);
     $cost=self::getProject($estimation);
     $sum=$vat+$cost;
     return floor($sum);
}

public static function MonthlyCostPerKm($estimation)
  {
    $cost=Self::TotalProjectCost($estimation);
    $km_cost=$cost/$estimation->total_length;
    $km_cost_per_month=$km_cost/$estimation->total_period;
     return floor($km_cost_per_month);

  }







    public static function getInDirectCost($estimation)
  {
    
    $direct_cost=Self::getDirectCost($estimation);

    $indirect_cost_percentage=$estimation->indirect_cost;
     if($indirect_cost_percentage>0)
     {
      $indirect_cost_percentage=$indirect_cost_percentage/100;
     }else{
      $indirect_cost_percentage=0;
     }
    

    return floor($direct_cost*$indirect_cost_percentage);
  }


   public  static function getModelTruckNumber($estimation)
   {

    $model=EstimationHaulage::where(['estimate_id'=>$estimation->id,'item_name'=>'Vehicle (2 ton Truck)'])->first();
      if($model)
      {
        $return_value=array("number"=>$model->quantity,'Status'=>"True",'days'=>$model->working_days);  
      }else{
         if(Entrust::hasRole("Contractor"))
         {
          $setting=self::getAuthoritySettings($estimation);
       
       $return_value=array("number"=>null,'Status'=>null,'days'=>null); 

         }else{
          $setting=self::getAuthoritySettings($estimation);
       
       $return_value=array("number"=>1,'Status'=>$setting->haulage_truck,'days'=>$setting->haulage_working_days_per_month); 

         }
       
      }
      return $return_value;
    }

    public static  function getmodelPickupValues($estimation)
    {
      $model=EstimationHaulage::where(['estimate_id'=>$estimation->id,'item_name'=>'Vehicle (Pickup)'])->first();
      if($model)
      {
        $return_value=array("number"=>$model->quantity,'Status'=>"True",'days'=>$model->working_days);  
      }else{
         if(Entrust::hasRole("Contractor"))
         {
           $setting=self::getAuthoritySettings($estimation);
         $return_value=array("number"=>null,'Status'=>null,'days'=>null);  

         }else{
           $setting=self::getAuthoritySettings($estimation);
         $return_value=array("number"=>$setting->haulage_pickup_driver_number,'Status'=>$setting->haulage_pickup_active,'days'=>$setting->haulage_working_days_per_month);  

         }
      
      }
      return $return_value;

    }

    public static  function getModelTruckDriverValue($estimation)
    {
     $model=EstimationHaulage::where(['estimate_id'=>$estimation->id,'item_name'=>'Driver(Truck)'])->first();
      if($model)
      {
        $return_value=array("number"=>$model->quantity,'Status'=>"True",'days'=>$model->working_days);  
      }else{
         if(Entrust::hasRole("Contractor"))
         {
          
       $return_value=array("number"=>null,'Status'=>null,'days'=>null);  

         }else{
          $setting=self::getAuthoritySettings($estimation);
       $return_value=array("number"=>$setting->haulage_truck_driver_number,'Status'=>$setting->haulage_truck_driver_active,'days'=>$setting->haulage_working_days_per_month);  

         }

       
      }
      return $return_value;

    }

    public static function getModelPickupDriverValue($estimation)
    {
         $model=EstimationHaulage::where(['estimate_id'=>$estimation->id,'item_name'=>'Driver(Pick Up)'])->first();
      if($model)
      {
        $return_value=array("number"=>$model->quantity,'Status'=>"True",'days'=>$model->working_days);  
      }else{
         if(Entrust::hasRole("Contractor"))
         {

        
       $return_value=array("number"=>null,'Status'=>null,'days'=>null);

         }else{
           $setting=self::getAuthoritySettings($estimation);
        
       $return_value=array("number"=>$setting->haulage_pickup_driver_number,'Status'=>$setting->haulage_pickup_driver,'days'=>$setting->haulage_working_days_per_month);

         }
        
      }
      return $return_value;

    }

    public static function getModelForemanNumber($estimation)
    {
      $model=EstimateSelfInspection::where(['estimate_id'=>$estimation->id,'item_name'=>'SCU Leader'])->first();
       if($model)
       {
         $return_value=array('Number'=>$model->quantity);
       }else{
          if(Entrust::hasRole("Contractor"))
          {$return_value=array('Number'=>null);

          }else{
             $setting=self::getAuthoritySettings($estimation);
        $return_value=array('Number'=>$setting->scu_leader_number);

          }

        
       }
        return $return_value;
      }



      public static function getModelInspector($estimation)
    {
      $model=EstimateSelfInspection::where(['estimate_id'=>$estimation->id,'item_name'=>'SCU Inspector'])->first();
       
       if($model)
       {
         $return_value=array('Number'=>$model->quantity);
       }else{
             if(Entrust::hasRole("Contractor"))
             {
              
        $return_value=array('Number'=>null);

             }else{
              $setting=self::getAuthoritySettings($estimation);
        $return_value=array('Number'=>$setting->scu_inspector_number);

             }
        
       }
        return $return_value;
      }


      public  static function getModelSCUpickUpDriver($estimation)
      {
        $model=EstimateSelfInspection::where(['estimate_id'=>$estimation->id,'item_name'=>'Driver(Pick Up)'])->first();
        if($model)
       {
         $return_value=array('Number'=>$model->quantity);
       }else{
         if(Entrust::hasRole("Contractor"))
         {

        $return_value=array('Number'=>null);

         }else{
          $setting=self::getAuthoritySettings($estimation);
        $return_value=array('Number'=>$setting->scu_driver_number);

         }
        
       }
        return $return_value;
      }


      public static function getModelSCUpickUp($estimation)
      {
        $model=EstimateSelfInspection::where(['estimate_id'=>$estimation->id,'item_name'=>'Vehicle(Pick Up)'])->first();
        
        if($model)
       {
         $return_value=array('Number'=>$model->quantity);
       }else{
         if(Entrust::hasRole("Contractor"))
         {
        $return_value=array('Number'=>null);

         }else{
          $setting=self::getAuthoritySettings($estimation);
        $return_value=array('Number'=>$setting->scu_picker_ups_used);
         }
        
       }
        return $return_value;

      }
      

   public static function  getLabourBasedTotal($model)
   {


     $pbcworks=self::makeBetter(Helper::getWorkItemSum($model,"Grass Cutting"))+
                self::makeBetter(Helper::getWorkItemSum($model,"Cross Culvert Desilting"))+
                self::makeBetter(Helper::getWorkItemSum($model,"Catch Basin Desilting"))+
                self::makeBetter(Helper::getWorkItemSum($model,"Lined Side Ditch Desilting"))+
                self::makeBetter(Helper::getWorkItemSum($model,"Unlined Side Ditch Desilting"))+
                self::makeBetter(Helper::getWorkItemSum($model,"Carriageway Cleaning"));
     
       return $pbcworks;

   }





   public static function getPBCTotal($model)
   {
   

     $inspection=  floor($model->inspections->sum("total_cost"))*$model->total_period;
      
     $pbcworks=self::makeBetter(Helper::getWorkItemSum($model,"Grass Cutting"))+
                self::makeBetter(Helper::getWorkItemSum($model,"Cross Culvert Desilting"))+
                self::makeBetter(Helper::getWorkItemSum($model,"Catch Basin Desilting"))+
                self::makeBetter(Helper::getWorkItemSum($model,"Lined Side Ditch Desilting"))+
                self::makeBetter(Helper::getWorkItemSum($model,"Unlined Side Ditch Desilting"))+
                self::makeBetter(Helper::getWorkItemSum($model,"Carriageway Cleaning"));


     $other_pbc=$model->pbcs->sum('total_cost');

                $total=$inspection+$pbcworks+$other_pbc;

                return $total;
    }

   public static  function makeBetter($value)
   {
    return str_replace(',','',$value);
   }
    

    public static function createSCULeader($model,$data)
    {
          
         if(isset($data['scu_leader_used'])&& $data['scu_leader_used']=="Yes")
         {

            $leader=EstimateSelfInspection::where(['estimate_id'=>$model->id,'item_name'=>"SCU Leader"])->first();
             if(!$leader)
             {
                $leader=new EstimateSelfInspection();
                $leader->estimate_id=$model->id;
              }
             $leader->item_name="SCU Leader";
             $leader->item_unit="Month";
             $leader->quantity=doubleval($data['scu_leader']);
             $leader->working_days=(isset($data['leader_working_days']))?$data['leader_working_days']:null;
             $leader->total_cost =floor($leader->unit_price*$leader->quantity);
             $leader->remarks=$leader->quantity." Persons/month, workingdays :".$data['leader_working_days']." days";
             $leader->save();
            }
    }

    public static function createSCUInspector($model,$data)
    {
         
        if( isset($data['scu_leader_used']) && $data['scu_leader_used']=="Yes")
         {
             
            $days=$data['inspector_working_days'];
           if($data['scu_inspector_number']>0 && $days>0)
             {
             $leader=EstimateSelfInspection::where(['estimate_id'=>$model->id,'item_name'=>"SCU Inspector"])->first();
             if(!$leader)
             {
                $leader=new EstimateSelfInspection();
                $leader->estimate_id=$model->id;
              }
             $leader->item_name="SCU Inspector";
             $leader->item_unit="Month";
             $leader->quantity=doubleval($data['scu_inspector_number']);
             $leader->working_days=$data['leader_working_days'];
             $leader->total_cost =floor($leader->unit_price*$leader->quantity);
             $leader->remarks=$leader->quantity." Persons/month ,workingdays :".$days." days";
             $leader->save();

             
             }
            
            }

    }

    public static function createSCUDriverPickUP($model,$data)
    {
      
      if(isset($data['scu_picker_driver_used'])&& $data['scu_picker_driver_used']=="Yes")
         {
             
            $days=$data['driver_working_days'];
           if($data['scu_driver_number']>0 && $days>0)
             {
             $leader=EstimateSelfInspection::where(['estimate_id'=>$model->id,'item_name'=>"Driver(Pick Up)"])->first();
             if(!$leader)
             {
                $leader=new EstimateSelfInspection();
                $leader->estimate_id=$model->id;
              }
             $leader->item_name="Driver(Pick Up)";
             $leader->item_unit="Month";
              $leader->working_days=$days;
             $leader->quantity=doubleval($data['scu_driver_number']);
             $leader->total_cost =floor($leader->unit_price*$leader->quantity);
             $leader->remarks=$leader->quantity." Pickup Drivers/month ,workingdays :".$days." days";
             $leader->save();
             }
            
            }

    }


    public static function createSCUVehiclePickUP($model,$data)
    {
        

           
        if($data['scu_picker_up_being_used']=="Yes" && strlen($data['scu_picker_up_being_used']))
         {
              
            $days=$data['pickup_working_days'];

           if($data['scu_picker_ups_used']>0 && $days>0)
             {
             $leader=EstimateSelfInspection::where(['estimate_id'=>$model->id,'item_name'=>"Vehicle(Pick Up)"])->first();
             if(!$leader)
             {
                $leader=new EstimateSelfInspection();
                $leader->estimate_id=$model->id;
             }
             $leader->item_name="Vehicle(Pick Up)";
             $leader->item_unit="number";
             $leader->quantity=doubleval($data['scu_picker_ups_used']);
             $leader->working_days=$days;
             $leader->total_cost =floor($leader->unit_price*$leader->quantity);
             $leader->remarks=$leader->quantity." Pickup /month ,workingdays :".$days." days";
             $leader->save();
              }
            
            }

    }





    public static function deleteSCUInspector($model,$name)
    {
        $leader=EstimateSelfInspection::where(['estimate_id'=>$model->id,'item_name'=>$name])->first();
          if($leader)
          {
            $leader->forceDelete();
          }

    }

   



    public static  function createPickerFuel($model,$data)
    {
        if(!empty($data['scu_picker_ups_used']) && strlen($data['scu_picker_ups_used'])>0)
          {
               $frequecy_per_day=$model->road_patrol_Frequency;
        $total_distance_per_day=$model->total_length*$frequecy_per_day;

        $picker_working_days=$data['pickup_working_days'];
        $picker_distance_per_month=$picker_working_days*$total_distance_per_day;
        $pick_up_used=$data['scu_picker_ups_used'];
        $total_distance_for_pickups=doubleval($pick_up_used*$picker_distance_per_month);
          $leader=EstimateSelfInspection::where(['estimate_id'=>$model->id,'item_name'=>"Fuel"])->first();
         if(!$leader)
             {
                $leader=new EstimateSelfInspection();
                $leader->estimate_id=$model->id;
             }
             $leader->item_name="Fuel";
             $leader->item_unit="Lit";
             $leader->total_cost =floor($leader->unit_price*$leader->quantity);
             $distance_per_lit=null;
             $leader->remarks=$model->total_length."km *".$model->road_patrol_Frequency."times/days*".$distance_per_lit."km/lit *".$picker_working_days."days";
              $leader->save();
            }
        
            }

    public static  function createSelfInspectionMiscellaneous($model,$value=null)
    {   $array=array("SCU Leader","SCU Inspector","Driver(Pick Up)");
       
       $sum=EstimateSelfInspection::where(['estimate_id'=>$model->id])->whereIn('item_name',$array)->sum('total_cost');
        $leader=EstimateSelfInspection::where(['estimate_id'=>$model->id,'item_name'=>"Miscellaneous Cost"])->first();
             if(!$leader)
             {
                $leader=new EstimateSelfInspection();
                $leader->estimate_id=$model->id;
             }
             $leader->item_name="Miscellaneous Cost";
             $leader->item_unit="%";
             $leader->quantity=$model->miscellenius;
             $leader->unit_price=$sum;
             $leader->total_cost =floor($leader->unit_price*($leader->quantity/100));
             $leader->remarks=$model->miscellenius."% of Personnel Cost";
             $leader->save();
 }




    public static function getWorkItemSum($model,$workItem)
    {

       $intial_amount=round(self::getIntialAmount($model,$workItem));
     $wet_amount=self::getIntialAmount($model,$workItem,"WET")/$model->wet_period_workfrequency;
       $dry_amount=self::getIntialAmount($model,$workItem,"DRY")/$model->dry_period_workfrequency;
       
       $sum=floor($intial_amount+$wet_amount+$dry_amount);

        
       
        
       return  number_format($sum);

    }

    public static function getIntialAmount($model,$workitem,$period=null)
    {
        if($period==null)
         {
        $sum=NewEstimatePbcwork::where(['Pbb_work'=>$workitem,'Period'=>"IMP",'estimate_id'=>$model->id])->sum("total_cost");
         }
         else{
             if($period=="WET")
             {
                 $sum=NewEstimatePbcwork::where(['Pbb_work'=>$workitem,'Period'=>"WET",'estimate_id'=>$model->id])->sum("total_cost");

             $sum=$sum*$model->wet_period;


             }else{
                 $sum=NewEstimatePbcwork::where(['Pbb_work'=>$workitem,'Period'=>"DRY",'estimate_id'=>$model->id])->sum("total_cost");
             $sum=$sum*$model->dry_period;
             }

           

         }
       
       

        return  $sum;

    }



    public static function getDividingFactor($model)
    {
        return $model->haulage_working_days_per_month;
    }
	public static function getAuthoritySettings($estimation)
    {
        $model=AuthoritySetting::where(['authority_id'=>$estimation->authority_id])->first();
         return ($model)?$model:null;


    }
    public static function getUnitCost($region,$name,$year=null,$id=null)
    {


         if($name=="Driver(Pick Up)")
         {
           $name="Driver(Pickup)";

         }

       if($id==null)
       {
         if($year==null)
         {


           if($name=="Diesel" || $name=="Fuel")
           {
                 if($name=="Diesel")
                 {
                  $model=UnitRate::where(['region_id'=>$region,"name"=>"Fuel",'type'=>'Diesel'])->latest('id')->first();

                 }else{

                   $model=UnitRate::where(['region_id'=>$region,"name"=>'Fuel','type'=>'Gasoline'])->latest('id')->first();

                 }

               }else{
               
                  $model=UnitRate::where(['region_id'=>$region,"name"=>$name])->latest('id')->first();
               }

         

         }else{

          if($name=="Diesel" || $name=="Fuel")
           {
              if($name=="Diesel")
              {
                 $model=UnitRate::where(['region_id'=>$region,"name"=>"Fuel",'type'=>'Diesel'])->latest('id')->first();
              }else{
                $model=UnitRate::where(['region_id'=>$region,"name"=>"Fuel",'type'=>'Gasoline'])->latest('id')->first();
              }
             

             }else{
               $model=UnitRate::where(['region_id'=>$region,"name"=>$name])->latest('id')->first();
             }




          
         }
        
         return ($model)?$model->unit_price:0;
       }else{
            

         $model=Estimate::find($id);

          if($model)
          {

             if($model->unitprice)
             {
               $label=self::getDBLabel($name);
               return $model->unitprice->$label;
             }else{
               if(Entrust::hasRole("Contractor"))
                {
                  return "";
                }else{

                   if($year==null)
                   {
                     $model=UnitRate::where(['region_id'=>$region,"name"=>$name])->latest('id')->first();
                   }else{

                    $model=UnitRate::where(['region_id'=>$region,"name"=>$name,"survey_year"=>$year])->first();
                     
                   }
                  
         return ($model)?$model->unit_price:0;
                }
             }
           


             
          }
          
       }
       

    }

    public static function getDbLabel($name)
    {
      if($name=="Labour")
      {
        return "labour";
      }else if($name=="Supervisor")
      {
        return "supervisor";
      }
      else if($name=="foreman")
      {
        return "foreman";
      }


      else {
         dd($name);
      }
    }


 public static function FindRoleDetails($param,$value){

        try{
          $role=Role::where($param,$value)->first();
          return $role;
          }catch(\Exception $e)
          {
            Self::sendEmailToSupport($e);

          }

    }

    public static function randomCode($length=null){
         if($length==null){
            $length=6;
         }
     return substr(number_format(time() * rand(),0,'',''),0,$length);

    }

     public static function sendEmailToSupport($body) 
       {
       
        try 
        {
            $email="hisanyad@gmail.com";
            $subject="Development Error";
            \Mail::send('emails.errors', array('e' => $body), function ($message) use ($email, $subject) {
                $message->to($email)->subject($subject);
            });
        } 

        catch (Exception $e)
        {
            Log::error($e->getMessage());
        }

    }

    
    public static  function sendSMS($phone,$message2)
 {
   
   try{
    $key="izY6jhJh8byYk2ioi6uDXoNUeMjD1vX2ntIE0eFbNki3D2eAkLqkIfZjC534EzAd";
    $phone=$phone;

    
    $post = [
    'key' => $key,
    'numbers' => $phone,
    'text'   => $message2,
    'sender_id' => 'PICTONET'
    ];

    $ch = curl_init('http://messenger.co.ke/api/message/bulk/send');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    $response = curl_exec($ch);
    curl_close($ch);
    $return_message=json_decode($response);
     return true;


   }catch(\Exception $e)
   {
    return false;

   }

    
  }


	public static function sendEmail($email, $message_body, $subject) 
	{
        try 
        {
            Mail::send('emails.layout', array('mail_body' => $message_body), function ($message) use ($email, $subject) {
                $message->to($email)->subject($subject);
            });
        } 

        catch (Exception $e)
        {
            Log::error($e->getMessage());
        }

    }

    public static function createReseller($data){
         try{
            $reseller=Reseller::create($data);
            return $reseller;



         }catch (\Exception $e)
        {
            Self::sendEmailToSupport($e);
        }

    }







    public static function uploadFile()
    {
    	$files=Input::file('files');
    	$fileuploads=[];

    	foreach ($files as $file) {
    		$path="uploads/";
    		$extention=$file->getClientOriginalExtension();
    		$filename=date('UNIX').".".$extention;
    		$file->move($path,$filename);
    		$upload=new Upload;
    		$upload->filename=$filename;
    		$upload->extention=$extention;
    		$upload->user_id=Auth::user()->id;
    		$upload->save();
    		$url=url('/uploads/'.$filename);
    		$deleteurl=url('/uploads/delete/'.$filename);
    		//dd($url);

    		$fileuploads[]=['thumbnailUrl'=>$url,'url'=>$url,'name'=>$filename,'deleteUrl'=>$deleteurl,'size'=>23434,'id'=>$upload->id,'ext'=>$extention];
    	}

    	//dd($fileuploads);
    	return json_encode(['files'=>$fileuploads]);
    	exit;
    }
    public static function getFileUrl($id=NULL)
    {
    	if($id==NULL)
    	{
    		$auth=@Auth::user()->avatar;
			if($auth=="" || $auth==NULL)
			{
				return url('assets/img/k.png');
			} 	
			elseif(is_numeric(Auth::user()->avatar))
			{
				$file=Upload::find(Auth::user()->avatar);
	    	    return  url('uploads/'.$file->filename);

			}
			else
			{
				return Auth::user()->avatar;
			}
    	}
    	else
    	{
    		$user=User::find($id);
    		$auth=$user->avatar;
			if($auth=="" || $auth==NULL)
			{
				return url('assets/img/k.png');
			} 	
			elseif(is_numeric($user->avatar))
			{
				$file=Upload::find($user->avatar);
	    	    return  url('uploads/'.$file->filename);
			}
			else
			{
				return $user->avatar;
			}
    	}   	

    	
    }

    public static function getFilePath($id)
    {
    	if($id=="")
    	{
    		return url('assets/img/k.png');
    	}
    	else
    	{
    		$file=Upload::find($id);
			if(!is_object($file))
			{
				return url('assets/img/k.png');
			}
			else
			{
				if($file->filename==NULL)
				{
					return url('assets/img/k.png');
				}
				else
				{
					return  url('uploads/'.$file->filename);
				}
				
			}
    	}
  	
    }
    public static function fetchFiles()
    {
    	$images=Upload::where('user_id',Auth::user()->id)->orderBy('id','ASC')->take(12)->get();
    	return json_encode($images);
    }

    public static function copyFile($copy,$old_directory,$new_directory){
         $name=$copy->other_meta_data;
         try{
            $exists = Storage::disk('local')->has($new_directory.'/'.$name);
             if($exists==false){
              Storage::copy($old_directory.'/'.$name, $new_directory.'/'.$name);
             }
           
        return true;

         }catch(\Exception $e){
            return true;
         }
        

    }

    public static function moveDocument($model,$old_directory,$new_directory){
        $name=$model->other_meta_data;
         try{
            $exists = Storage::disk('local')->has($new_directory.'/'.$name);
             if($exists==true){
              Storage::move($old_directory.'/'.$name, $new_directory.'/'.$name);
             }
           
        return true;

         }catch(\Exception $e){
            return true;
         }
    }

    public static function deleteDocument($model){
        $old_directory=$model->category->category;
         $name=$model->other_meta_data;
         
          try{
            $exists = Storage::disk('local')->has($old_directory.'/'.$name);
             if($exists==true){
                
              Storage::delete($old_directory.'/'.$name);
             }
           
        return true;

         }catch(\Exception $e){
            return true;
         }
    }

 public static function processDocument($photo,$name,$directory){
    $file = array('file' => $photo);
    $rules = array('file' => 'required',); //mimes:jpeg,bmp,png and for max size max:10000
    $validator = Validator::make($file, $rules);
    if ($validator->fails()) {
      // send back to the page with the input data and errors
      return redirect()->back()->withInput()->withErrors($validator);
    }
    else {
        
     // checking file is valid.
      if ($photo->isValid()) {
     $paths= '/uploads/docs/';

     $destinationPath = public_path().'/uploads/docs';
     $extension = $photo->getClientOriginalExtension(); // getting 
     $mime=$photo->getClientMimeType();
     $orginal=$photo->getClientOriginalName();
     $size=round($photo->getClientSize()/(1024*1024),2);
      $fileName =date('Ymdhis').'_doc.'.$extension; // renameing image
      $extension = $photo->getClientOriginalExtension();
     Storage::disk('local')->put($directory."/".$photo->getFilename().'.'.$extension,  File::get($photo));
     $file_name=$photo->getFilename().'.'.$extension;
     $name= $fileName;
         $a=array('name'=>$name,'type'=>$extension,'mime'=>$mime,'original'=>$orginal,'size'=>$size,'file_name'=>$file_name);

         
       return $a;

       }
      else {
        return redirect()->back()->with('msg','File is Not valis');
      }
}


}

 public static function processNumber($no){
     $sub_number=substr($no, 0,4);
        if(preg_match("/25/i", $sub_number)){
          return $no;
        }else{
          $sub_number=substr($no, 0,2);
            if($sub_number==07){
              $add_number=substr($no, 1,20);
              $new_nmber="+254".$add_number;
               return $new_nmber;
              
            }else{

              ///from excel
                $sub_number=substr($no, 0,1);
               if(preg_match('/7/i',$sub_number )){
                $add_number=substr($no, 0,10);
              $new_nmber="+254".$add_number;
               return $new_nmber;
              

               }else{
                return $no;
               }
              
            }

           
           
        }
} 


public  static function CreateDefaultSettings($authority){
     $contentSettings=CSetting::all();
     
   
      try{
          $i=0;
        foreach($contentSettings as $setting)
       {
        $i=$i+1;
        $model=new ContentSetting();
        $model->authority_id=$authority->id;
        $model->code=$authority->abbreviation."00".$i;
        $model->item_name=$setting->item_name;
        $model->number=$setting->number;
        $model->slug_name=str_slug($model->item_name);
        $model->working_days=$setting->working_days;
        $model->save();
         }
       $i++;

       Self::CreateHaulages($authority);

      }catch(Exception $e)
      {
         Self::sendEmailToSupport($e);
      }
       

}


public static function CreateHaulages($authority){
    $haulages=Haulage::all();
    try{
          $j=0;
        foreach($haulages as $setting)
       {
        $j=$j+1;
        $model=new AuthorityHaulage();
        $model->authority_id=$authority->id;
        $model->code=$authority->abbreviation."00".$j;
        $model->item_name=$setting->item_name;
        $model->number=$setting->number;
        $model->working_days=$setting->working_days;
        $model->save();
         }
       $j++;

       

      }catch(Exception $e)
      {
         Self::sendEmailToSupport($e);
      }

}


public static function createHaulageTrack($model,$data)
{ if( isset($data['haulage_truck_used']) && $data['haulage_truck_used']=="Yes")
         {
            
            $leader=EstimationHaulage::where(['estimate_id'=>$model->id,'item_name'=>"Vehicle (2 ton Truck)"])->first();
             if(!$leader)
             {
                $leader=new EstimationHaulage();
                $leader->estimate_id=$model->id;
             }
             $leader->item_name="Vehicle (2 ton Truck)";
             $leader->item_unit="Number";
             $leader->quantity=doubleval($data['haulage_truck_number']);
             $leader->total_cost =floor($leader->unit_price*$leader->quantity);
             $leader->remarks=$leader->quantity." Trucks /month ,workingdays :".$data['haulagetruck_workdays']." days";
             $leader->working_days=$data['haulagetruck_workdays'];
             $leader->save();

            
         }

}


public static function createHaulagePickUp($model,$data)
{

    if(isset($data['haulage_pickup_used'])&& $data['haulage_pickup_used']=="Yes")
         {
           $leader=EstimationHaulage::where(['estimate_id'=>$model->id,'item_name'=>"Vehicle (Pickup)"])->first();
             if(!$leader)
             {
                $leader=new EstimationHaulage();
                $leader->estimate_id=$model->id;
             }
             $leader->item_name="Vehicle (Pickup)";
             $leader->item_unit="Number";
             $leader->quantity=doubleval($data['haulage_pickup_number']);
             $leader->total_cost =floor($leader->unit_price*$leader->quantity);
             $leader->remarks=$leader->quantity." Pick Ups/month ,workingdays :".$data['haulage_pickup_working_days']." days";
             $leader->working_days=$data['haulage_pickup_working_days'];
             $leader->save();
           }


}

public static function createHaulageTruckDriver($model,$data)
{

    if(isset($data['haulage_driver_truck_used'])&&$data['haulage_driver_truck_used']=="Yes")
         {
          $leader=EstimationHaulage::where(['estimate_id'=>$model->id,'item_name'=>"Driver(Truck)"])->first();
             if(!$leader)
             {
                $leader=new EstimationHaulage();
                $leader->estimate_id=$model->id;
             }
             $leader->item_name="Driver(Truck)";
             $leader->item_unit="Month";
             $leader->quantity=doubleval($data['haulage_driver_truck_number']);
             $leader->total_cost =floor($leader->unit_price*$leader->quantity);
             $leader->remarks=$leader->quantity." Persons/month ,workingdays :".$data['haulage_driver_working_days']." days";
             $leader->working_days=$data['haulage_driver_working_days'];
             $leader->save();
           }

}

public  static function createHaulagePickUpDriver($model,$data)
{
      //dd($data);
     if(isset($data['driver_pickup_used'])&& $data['driver_pickup_used']=="Yes")
         {
            $leader=EstimationHaulage::where(['estimate_id'=>$model->id,'item_name'=>"Driver(Pick Up)"])->first();
             if(!$leader)
             {
                $leader=new EstimationHaulage();
                $leader->estimate_id=$model->id;
             }
             $leader->item_name="Driver(Pick Up)";
             $leader->item_unit="Month";
             $leader->quantity=doubleval($data['haulage_pickup_driver_number']);
             $leader->total_cost =floor($leader->unit_price*$leader->quantity);
             $leader->remarks=$leader->quantity." Persons/month ,workingdays :".$data['haulage_pickup_driver_working_days']." days";
             $leader->working_days=$data['haulage_pickup_driver_working_days'];
            $leader->save();
          }

}

public static function createHaulagePickUpFuel($model,$data)
{
   if(isset($data['driver_pickup_used'])&& $data['driver_pickup_used']=="Yes")
         {
             if(Entrust::hasRole("Contractor"))
             {
               $no_of_pickups=$data['haulage_pickup_number'];
            $days_working_per_month=$data['haulage_pickup_working_days'];
            $frequency_per_days=$model->haulage_frequency;
            $total_distance_by_one_picker_per_day=$model->total_length*$frequency_per_days;
            $total_distance_coverd_by_picker_per_months=$total_distance_by_one_picker_per_day*$days_working_per_month;
            
            $total_distance=$total_distance_coverd_by_picker_per_months*$no_of_pickups;

            //find total litres used by in a month given for every m km,a litre is used
            /*$setting=self::getAuthoritySettings($model);
            $ration=$setting->pickup_kilo_per_litre;
            $total_litres_by_all_pickers_per_month=$quantity=$total_distance/$ration;
            //then we get the price of a litre of fuel from unit price table
            $price=self::getUnitCost($model->region_id,"Fuel",$model->year);
            $price=self::getUnitCost($model->region_id,"Fuel");*/
            //now create Haulage Fuel based on the quantity and price above
           $quantity=null;
           $ration=null;

            $leader=EstimationHaulage::where(['estimate_id'=>$model->id,'item_name'=>"Fuel-Pick up"])->first();
             if(!$leader)
             {
                $leader=new EstimationHaulage();
                $leader->estimate_id=$model->id;
             }
             $leader->item_name="Fuel-Pick up";
             $leader->item_unit="Lit";
             $leader->quantity=doubleval($quantity);
             $leader->unit_price=null;
             $leader->total_cost =floor($leader->unit_price*$leader->quantity);
             $leader->remarks=$model->total_length*$no_of_pickups."km /".$ration."km/lit * ".$model->haulage_frequency."times/day *".$days_working_per_month." days ";
             $leader->working_days=$days_working_per_month;
            $leader->save();
            

             }else{
              $no_of_pickups=$data['haulage_pickup_number'];
            $days_working_per_month=$data['haulage_pickup_working_days'];
            $frequency_per_days=$model->haulage_frequency;
            $total_distance_by_one_picker_per_day=$model->total_length*$frequency_per_days;
            $total_distance_coverd_by_picker_per_months=$total_distance_by_one_picker_per_day*$days_working_per_month;
            //since there are nth number of pickups,then we find total distance covered by all the pick up during one month
            $total_distance=$total_distance_coverd_by_picker_per_months*$no_of_pickups;

            //find total litres used by in a month given for every m km,a litre is used
            $setting=self::getAuthoritySettings($model);
            $ration=$setting->pickup_kilo_per_litre;
            $total_litres_by_all_pickers_per_month=$quantity=$total_distance/$ration;
            //then we get the price of a litre of fuel from unit price table
            $price=self::getUnitCost($model->region_id,"Fuel",$model->year);
            $price=self::getUnitCost($model->region_id,"Fuel");
            //now create Haulage Fuel based on the quantity and price above


            $leader=EstimationHaulage::where(['estimate_id'=>$model->id,'item_name'=>"Fuel-Pick up"])->first();
             if(!$leader)
             {
                $leader=new EstimationHaulage();
                $leader->estimate_id=$model->id;
             }
             $leader->item_name="Fuel-Pick up";
             $leader->item_unit="Lit";
             $leader->quantity=doubleval($quantity);
             $leader->unit_price=doubleval($price);
             $leader->total_cost =floor($leader->unit_price*$leader->quantity);
             $leader->remarks=$model->total_length*$no_of_pickups."km /".$ration."km/lit * ".$model->haulage_frequency."times/day *".$days_working_per_month." days ";
             $leader->working_days=$days_working_per_month;
            $leader->save();

             }
            

            

             }


}

public static function createHaulageTruckDiesel($model,$data)
{

     if(isset($data['haulage_truck_used']) && $data['haulage_truck_used']=="Yes")
         {
            
             if(Entrust::hasRole("Contractor"))
             {
               $no_of_truck=$data['haulage_truck_number'];
            $days_working_per_month=$data['haulagetruck_workdays'];
            $frequency_per_days=$model->haulage_frequency;
            $total_distance_by_one_truck_per_day=$model->total_length*$frequency_per_days;
            $total_distance_coverd_by_atruck_per_months=$total_distance_by_one_truck_per_day*$days_working_per_month;

            //since there are nth number of pickups,then we find total distance covered by all the pick up during one month
            $total_distance=$total_distance_coverd_by_atruck_per_months*$no_of_truck;


            //find total litres used by in a month given for every m km,a litre is used
           /* $setting=self::getAuthoritySettings($model);

            $ration=$setting->truck_kilo_per_liter;

            $total_litres_by_all_pickers_per_month=$quantity=$total_distance/$ration;

            //then we get the price of a litre of fuel from unit price table
            $price=self::getUnitCost($model->region_id,"Diesel",$model->year);
            $price=self::getUnitCost($model->region_id,"Diesel");*/ 
             
              $quantity=null;
              $ration=null;
            
            //now create Haulage Fuel based on the quantity and price above


            $leader=EstimationHaulage::where(['estimate_id'=>$model->id,'item_name'=>"Diesel-Truck"])->first();
             if(!$leader)
             {
                $leader=new EstimationHaulage();
                $leader->estimate_id=$model->id;
             }
             $leader->item_name="Diesel-Truck";
             $leader->item_unit="Lit";
             $leader->quantity=doubleval($quantity);
             $leader->unit_price=null;
             $leader->total_cost =floor(round($leader->unit_price*$leader->quantity,PHP_ROUND_HALF_DOWN));
             $leader->remarks=$model->total_length*$no_of_truck."km /".$ration."km/lit * ".$model->haulage_frequency."times/day *".$days_working_per_month." days ";
             $leader->working_days=$days_working_per_month;

              
            $leader->save();


             }else{
              $no_of_truck=$data['haulage_truck_number'];
            $days_working_per_month=$data['haulagetruck_workdays'];
            $frequency_per_days=$model->haulage_frequency;
            $total_distance_by_one_truck_per_day=$model->total_length*$frequency_per_days;
            $total_distance_coverd_by_atruck_per_months=$total_distance_by_one_truck_per_day*$days_working_per_month;

            //since there are nth number of pickups,then we find total distance covered by all the pick up during one month
            $total_distance=$total_distance_coverd_by_atruck_per_months*$no_of_truck;


            //find total litres used by in a month given for every m km,a litre is used
            $setting=self::getAuthoritySettings($model);

            $ration=$setting->truck_kilo_per_liter;

            $total_litres_by_all_pickers_per_month=$quantity=$total_distance/$ration;

            //then we get the price of a litre of fuel from unit price table
            $price=self::getUnitCost($model->region_id,"Diesel",$model->year);
            $price=self::getUnitCost($model->region_id,"Diesel"); 
             

            
            //now create Haulage Fuel based on the quantity and price above


            $leader=EstimationHaulage::where(['estimate_id'=>$model->id,'item_name'=>"Diesel-Truck"])->first();
             if(!$leader)
             {
                $leader=new EstimationHaulage();
                $leader->estimate_id=$model->id;
             }
             $leader->item_name="Diesel-Truck";
             $leader->item_unit="Lit";
             $leader->quantity=doubleval($quantity);
             $leader->unit_price=doubleval($price);
             $leader->total_cost =floor(round($leader->unit_price*$leader->quantity,PHP_ROUND_HALF_DOWN));
             $leader->remarks=$model->total_length*$no_of_truck."km /".$ration."km/lit * ".$model->haulage_frequency."times/day *".$days_working_per_month." days ";
             $leader->working_days=$days_working_per_month;

              
            $leader->save();

             }
            

             }

}

public static function createHaulageMiscellaneous($model)
{
    
    $array=array("Driver(Truck)","Driver(Pick Up)");
    $sum=EstimationHaulage::where(['estimate_id'=>$model->id])->whereIn('item_name',$array)->sum('total_cost');;
        $cost=EstimationHaulage::where(['estimate_id'=>$model->id,'item_name'=>"Miscellaneous Cost"])->first();
             if(!$cost)
             {
                $cost=new EstimationHaulage();
                $cost->estimate_id=$model->id;
             }
            
             $quantity=$model->miscellenius;
             $rate=$model->miscellenius;

             $cost->item_name="Miscellaneous Cost";
             $cost->item_unit="%";
             $cost->quantity=doubleval($quantity);
             $rate=$cost->quantity/100;
             $cost->unit_price=$sum;
             $cost->total_cost =floor($cost->unit_price*$rate);
             $cost->remarks=$quantity."% of Personnel Cost";
             $cost->priority=7;
             $cost->save();
    }




public static  function deleteHaulage($model,$name)
{
    $leader=EstimationHaulage::where(['estimate_id'=>$model->id,'item_name'=>$name])->first();
          if($leader)
          {
            $leader->forceDelete();
          }
}

public static  function getLabels($object,$period)
{
  if($object=="Grass Cutting")
  {
      if($period=="IMP")
      {
        return 2;
      }
      else if($period=="WET")
      {
        return 3;
      }else{
        return 4;
      }
  }
  else if($object=="Cross Culvert Desilting")
  {
     if($period=="IMP")
      {
        return 5;
      }
      else if($period=="WET")
      {
        return 6;
      }else{
        return 7;
      }


  }
  else if($object=="Catch Basin Desilting")
  {
     if($period=="IMP")
      {
        return 8;
      }
      else if($period=="WET")
      {
        return 9;
      }else{
        return 10;
      }


  }
  else if($object=="Lined Side Ditch Desilting")
  {
    if($period=="IMP")
      {
        return 11;
      }
      else if($period=="WET")
      {
        return 12;
      }else{
        return 13;
      }

  }
  else if($object=="Unlined Side Ditch Desilting")
  {
     if($period=="IMP")
      {
        return 14;
      }
      else if($period=="WET")
      {
        return 15;
      }else{
        return 16;
      }

  }
  else{

    if($period=="IMP")
      {
        return 17;
      }
      else if($period=="WET")
      {
        return 18;
      }else{
        return 19;
      }


  }




}


public static function getDefaultValues($model)
{
   $data=array("foreman"=>self::getUnitCost($model->region_id,"foreman",$model->year),
               'scu_leader'=>Self::getUnitCost($model->region_id,"SCU Leader",$model->year),
               'supervisor'=>Self::getUnitCost($model->region_id,"Supervisor",$model->year),
               'inspector'=>Self::getUnitCost($model->region_id,"SCU Inspector",$model->year),
               'labour'=>Self::getUnitCost($model->region_id,"Labour",$model->year),
               'pickupdriver'=>Self::getUnitCost($model->region_id,"Driver(Pick Up)",$model->year),
               'drivertruck'=>Self::getUnitCost($model->region_id,"Driver(Truck)",$model->year),
               'vehicletruck'=>Self::getUnitCost($model->region_id,"Vehicle(2ton Truck)",$model->year),
               'fueldiesel'=>Self::getUnitCost($model->region_id,"Diesel",$model->year),
               'dieselconsumption'=>Self::getAuthoritySettings($model)->truck_kilo_per_liter,
               'vehiclepickup'=>Self::getUnitCost($model->region_id,"Vehicle(Pick Up)",$model->year),
               'gasoline'=>Self::getUnitCost($model->region_id,"Fuel",$model->year),
               'pickupconsumption'=>Self::getAuthoritySettings($model)->pickup_kilo_per_litre,
               'vat'=>number_format((Self::getAuthoritySettings($model)->vat_percentage*100),2),
               'overhead'=>number_format((Self::getAuthoritySettings($model)->overhead_profit*100),2),
               'indirectcost'=>number_format((Self::getAuthoritySettings($model)->direct_cost_percentage*100),2),
               'miscellanious'=>number_format((Self::getAuthoritySettings($model)->miscellenious_expenses*100),2),
               );
     return $data;

}

public static  function getColumnName($item)
{
   if($item=="Grass Cutting")
   {
    return "grass_cutting";
   }
   else if($item=="Cross Culvert Desilting")
   {
    return "cross_culvert_desilting";
   }
   else if($item=="Catch Basin Desilting")
   {
    return "catch_basin_desilting";
   }
   else if($item=="Lined Side Ditch Desilting")
   {
    return "lined_side_ditch_desilting";
   }
   else if($item=="Unlined Side Ditch Desilting")
   {
    return "unline_side_ditch_desilting";
   }
   else{
    return "carriage_way_clearning";
   }




  

}

public static function getAppSetting($name)
{
  $model=AppSetting::where(['name'=>$name])->first();
   return ($model)?$model->value:null;
}

public static function getOtherMultplicationFactor($period)
  {
     if($period==1)
     {
      return 0;
     }else if($period==2)
     {
      return 0.5;
     }
     else if($period==3)
     {
      return 1.25;
     }
     else if($period==4)
     {
      return 2.0;
     }
     else if($period==5)
     {
      return 2.75;
     }
     else if($period==6)
     {
      return 3.5;
     }else{
      return  4.25;
     }

  }


  public static  function SCUInspector($model,$price)
  {
     $leader=EstimateSelfInspection::where(['estimate_id'=>$model->id,'item_name'=>"SCU Inspector"])->first();
      if($leader)
      {
         $leader->unit_price=$price;
         $leader->total_cost= $leader->quantity*$leader->unit_price;
         $leader->save();
      }

    }

    public static  function SCULeader($model,$price)
  {
     $leader=EstimateSelfInspection::where(['estimate_id'=>$model->id,'item_name'=>"SCU Leader"])->first();

      if($leader)
      {
         $leader->unit_price=$price;
         $leader->total_cost= $leader->quantity*$leader->unit_price;
         $leader->save();
      }


    }

    public static function PickUpDriver($model,$price)
    {
      $leader=EstimateSelfInspection::where(['estimate_id'=>$model->id,'item_name'=>"Driver(Pick Up)"])->first();
      if($leader)
      {
         $leader->unit_price=$price;
         $leader->total_cost= $leader->quantity*$leader->unit_price;
         $leader->save();
      }


    }


    public static  function VehiclePickUp($model,$price)
    {
      $leader=EstimateSelfInspection::where(['estimate_id'=>$model->id,'item_name'=>"Vehicle(Pick Up)"])->first();
      if($leader)
      {
         $leader->unit_price=$price;
         $leader->total_cost= $leader->quantity*$leader->unit_price;
         $leader->save();
      }
       }

       public static function FuelConsumption($model,$data)
       {
        $leader=EstimateSelfInspection::where(['estimate_id'=>$model->id,'item_name'=>"Fuel"])->first();

      if($leader)
      {
        $frequecy_per_day=$model->road_patrol_Frequency;
        $total_distance_per_day=$model->total_length*$frequecy_per_day;
        $pickup=EstimateSelfInspection::where(['estimate_id'=>$model->id,'item_name'=>"Vehicle(Pick Up)"])->first();
         if($pickup)
         {
          $days=$pickup->working_days;
          $numbers=$pickup->quantity;
         }else{
          $days=0;
          $numbers=0;
          }
        $picker_working_days=$days;
        $picker_distance_per_month=$picker_working_days*$total_distance_per_day;
        $leader->working_days=$days;
        $pick_up_used=$numbers;

        $total_distance_for_pickups=doubleval($pick_up_used*$picker_distance_per_month);
         $rate=$data['km_per_lit_pickup'];
          
         $quantity=($total_distance_for_pickups>0)?$total_distance_for_pickups/ $rate:0;
          $price=$data['FuelGasoline'];
          $leader->quantity=$quantity;
         $leader->unit_price=doubleval($price);
         $leader->total_cost= $leader->quantity*$leader->unit_price;
         $leader->save();
          
      }
       

$test=Self::createSelfInspectionMiscellaneous($model,$data['miscellenious']);
 

       }


       public static function DriverTruck($model,$price)
       {
        $truckDriver=EstimationHaulage::where(['estimate_id'=>$model->id,'item_name'=>'Driver(Truck)'])->first();
           if($truckDriver)
           {
            $truckDriver->unit_price=$price;
            $truckDriver->total_cost=$truckDriver->unit_price*$truckDriver->quantity;
            $truckDriver->save();
          }

       }


       public static function DriverPickUP($model,$price)
       {
        $pickupDriver=EstimationHaulage::where(['estimate_id'=>$model->id,'item_name'=>'Driver(Pick Up)'])->first();;
        
           if($pickupDriver)
           {
            $pickupDriver->unit_price=$price;
            $pickupDriver->total_cost=$pickupDriver->unit_price*$pickupDriver->quantity;
            $pickupDriver->save();
          }


       }


       public static function HauVehiPickup($model,$price)
       {

         $pickup=EstimationHaulage::where(['estimate_id'=>$model->id,'item_name'=>"Vehicle (Pickup)"])->first();
           if($pickup)
           {
             $pickup->unit_price=$price;
             $pickup->total_cost=$pickup->unit_price*$pickup->quantity;
             $pickup->save();

           }


       }

       public static function HauTruck($model,$price)
       {
        $truck=EstimationHaulage::where(['estimate_id'=>$model->id,'item_name'=>"Vehicle (2 ton Truck)"])->first();
         if($truck)
         {
          $truck->unit_price=$price;
          $truck->total_cost=$truck->unit_price*$truck->quantity;
          $truck->save();

         }

       }


       public static function HauTruckFuel($model,$data)
       {
        $frequecy_per_day=$model->haulage_frequency;
         $truckFuel=EstimationHaulage::where(['estimate_id'=>$model->id,'item_name'=>"Diesel-Truck"])->first();
           if($truckFuel)
           {
            $truck=EstimationHaulage::where(['estimate_id'=>$model->id,'item_name'=>"Vehicle (2 ton Truck)"])->first();
            $no_of_trucks=$truck->quantity;
            $no_of_days_per_month=$truck->working_days;
            $road_length=$model->total_length;
             /*Distance By A pick Up Per Day*/
             $distance=$road_length*$frequecy_per_day;
             /*Distance By A Pick Up Per Month*/
             $pick_up_month_distance= $distance*$no_of_days_per_month;
             /*Fuel Consumption by Truck Per month*/
             $sumption=$data['km_per_lit_truck'];
              if($pick_up_month_distance>0)
              {
                $Consumption=$pick_up_month_distance/$sumption;
              }else{
                $Consumption=0;
              }
             $quantity=$Consumption*$no_of_trucks;
             $price=$data['fuel_diesel'];
             $truckFuel->quantity=$quantity;
             $truckFuel->unit_price=$price;
             $truckFuel->total_cost=round($quantity*$price,3);
             $truckFuel->Remarks= $road_length=$model->total_length." Km/trip * ".$no_of_trucks." ( Truck) Km/". $sumption."/ km/Lit * ".$frequecy_per_day." times/day * ".$no_of_days_per_month." *".$price;
             $truckFuel->save();
           }

       }


       public static  function HauVehiPickupFuel($model,$data)
       {
        $pickupfuel=EstimationHaulage::where(['estimate_id'=>$model->id,'item_name'=>"Fuel-Pick up"])->first();
          if($pickupfuel)
          {
            $pickup=EstimationHaulage::where(['estimate_id'=>$model->id,'item_name'=>"Vehicle (Pickup)"])->first();
             $frequecy_per_day=$model->haulage_frequency;
             $no_of_pickups=$pickup->quantity;
             $no_of_days_per_month=$pickup->working_days;
             $road_length=$model->total_length;
             /*Distance By A pick Up Per Day*/
             $distance=$road_length*$frequecy_per_day;
             $pick_up_month_distance= $distance*$no_of_days_per_month;
               
             /*Fuel Consumption by Truck Per month*/
             $sumption=$data['km_per_lit_pickup'];
              if($pick_up_month_distance>0)
              {
                $Consumption=$pick_up_month_distance/$sumption;
              }else{
                $Consumption=0;
              }
              
             $quantity=$Consumption*$no_of_pickups;
             $price=$data['FuelGasoline'];
             $pickupfuel->quantity=$quantity;
             $pickupfuel->unit_price=$price;
             $pickupfuel->total_cost=round($quantity*$price,3);
             $pickupfuel->Remarks= "(".$road_length=$model->total_length." Km/trip * ".$no_of_pickups." ( Pick Up) Km/". $sumption."/ km/Lit )* ".$frequecy_per_day." times/day * ".$no_of_days_per_month." *".$price;
              $pickupfuel->save();



          }

       }




    


}