<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class PurchaseRequest extends Model
{
    
    use SoftDeletes;

    protected $fillable = [
        'project_id',
        'department_id',
        'task_id',
        'pr_type',
        'created_by',
        'status',
        'quotation_valid_date',
        'quotation_created_date',
        'note',
        'rfq_vendors',
        'head_person',
        'auth_person',
        'auth_person_date',
        'head_person_date',
        'remarks',
        'cancellation_remarks',
    ];

    public function department() {
        return $this->belongsTo('App\Department');
    }

     public function project() {
        return $this->belongsTo('App\Project');
    }     
    public function user() 
    {    
        return $this->belongsTo('App\User' , 'created_by');  
    }

    public function scopeWithAndWhereHas($query, $relation, $constraint){
    return $query->whereHas($relation, $constraint)
    ->with([$relation => $constraint]);
    }

   
      public function item()
   {
      return $this->hasMany('App\ItemPurchaseRequest' , 'purchase_request_id');
   }

     public function approvalStatus()
   {
      return $this->hasMany('App\ApprovelStatus' , 'purchase_request_id');
   }
    
       public function csApprovalStatus()
   {
      return $this->hasMany('App\CsApproval' , 'purchase_request_id');
   }

      public function comparativeStatements()
   {
      return $this->hasMany('App\ComparativeStatement' , 'purchase_request_id');
   }

       public function ItemPurchaseRequests()
   {
      return $this->hasMany('App\ItemPurchaseRequest' , 'purchase_request_id');
   }

        public function PurchaseOrders()
   {
      return $this->hasMany('App\PurchaseOrder' , 'purchase_request_id');
   }

    public function receipts()
   {
      return $this->hasMany('App\PurchaseOrderReceipt' , 'purchase_request_id');
   }


   public static function getPrStatus($pr_id = null)
   {
      $total_cs = 0;
      $total_rfq = 0;

      $pending_recipt = PurchaseOrderReceipt::where('purchase_request_id' , $pr_id)->whereNotIn('status' ,  [1,3])->count();

      $pending_po = PurchaseOrder::where('purchase_request_id' , $pr_id)->where('status' , '!=' , 2)->count();

      $purchase_request = PurchaseRequest::find($pr_id);

      if($purchase_request->status > 3)
      {
            $total_rfq = sizeof(json_decode($purchase_request->rfq_vendors));
      }

      if($purchase_request->status > 4)
      {
         $total_cs = ComparativeStatement::getVendorIds($purchase_request->id);
         $total_cs = sizeof($total_cs);
      }


   return ['pending_recipt' => $pending_recipt , 'pending_po' => $pending_po , 'total_rfq' => $total_rfq , 'total_cs' => $total_cs];
   }


    public static function getPoStatus( $status = null , $department_id = null)
   {
    $total = 0;
  
    $total_purchase_orders = PurchaseRequest::withAndWhereHas('PurchaseOrders', function($query) use ($status)
    {
    $query->where('status',  $status);
    })
    ->where('department_id' , $department_id )
    ->get();

      if($total_purchase_orders->count() > 0 )
      {
        $total_purchase_orders = json_decode(json_encode($total_purchase_orders));

      foreach ($total_purchase_orders as $key => $list) 
      {
         $total += count($list->purchase_orders);
      }
      }

    return $total;
   }

    public static function getReceiptStatus($status = null , $department_id = null)
    {
    $total = 0;
    $total_receipts = PurchaseRequest::withAndWhereHas('receipts', function($query) use ($status)
    {
    $query->where('status',  $status);
    })
    ->where('department_id' , $department_id )
    ->get();


   if ($total_receipts->count() > 0) 
   {
   $total_receipts = json_decode(json_encode($total_receipts));

   foreach ($total_receipts as $key => $list) 
   {
   $total += count($list->receipts);
   }

   }

    return $total;

    }

    public static function getPrWithStatus($status = null , $department_id = null)
    {
         $total = 0;
         $PrList = array();

         $purchase_request = PurchaseRequest::orderBy('id','DESC');

         if($status  == 'pending')
         {
          $purchase_request =  $purchase_request->where(  'status' , '>' , 2 )->where('department_id' , $department_id )->get();
         }

         if($status  == 'complete')
         {
          $purchase_request =  $purchase_request->where(  'status' , '=' , 7 )->where('department_id' , $department_id )->get();
         }

         foreach ( $purchase_request as $key => $list)
         {
              $pending_recipt = PurchaseOrderReceipt::where('purchase_request_id' , $list->id)->where('status' , '!=' , 1)->count();

            $pending_po = PurchaseOrder::where('purchase_request_id' , $list->id)->where('status' , '!=' , 2)->count();
            $total_rfq = 0;

          if(!empty($list->rfq_vendors))
          {
            $total_rfq = sizeof(json_decode($list->rfq_vendors)); 
          }
           

            $total_cs = ComparativeStatement::getVendorIds($list->id);
                $total_cs = sizeof($total_cs);
           
           if(($status == 'pending') && ($pending_recipt  > 0 || $pending_po > 0 || ($total_rfq > $total_cs)))
           {
             $total ++;
             $PrList[] = $list;
           }


            if(($status == 'complete') && $pending_recipt  == 0 && $pending_po == 0 && ($total_rfq == $total_cs))
           {
             $total ++;
             $PrList[] = $list;
           }


         }

         if($status  == 'cancel')
         {
          $cancel_purchase_request =  $purchase_request->where('status' , 2)->where('department_id' , $department_id )->get();
          $total = $cancel_purchase_request->count();
          $PrList = $cancel_purchase_request;
         }


         return  [$total , $PrList];
    }

public static function getrfqAndCsCount($department_id= null)
{
       $total_rfq  = 0;
       $total_receive = 0;
       $total_pending = 0;

       $total_sent_rfqs = PurchaseRequest::select('rfq_vendors','id' , 'status')
       ->whereIn('status' , [4 , 5])
       ->where('department_id' , $department_id )
       ->get();

        foreach ($total_sent_rfqs  as  $value)
        {
           foreach (json_decode($value->rfq_vendors) as  $vendors) 
            {
                $check_cs = ComparativeStatement::where('purchase_request_id' , $value->id)
                ->where('vendor_id' , $vendors)
                ->distinct()
                ->count('vendor_id');

                 if($check_cs == 0)
                 {
                   $total_rfq++;
                 }

                 if($check_cs > 0)
                 {
                   $total_receive ++;
                 }
            }
        }

        $total_rfq = $total_rfq +  $total_receive;
        $total_pending =  $total_rfq -  $total_receive;
        $total_receive = $total_receive;

        return [ $total_rfq ,  $total_pending ,  $total_receive ];

}
 

}