<?php

namespace App\Listeners\Purchases;

use App\Events\ReturnPurchasesEvent;
use App\Models\FifoQty;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use App\Traits\GeneralTrait;

use App\Models\Journalizing;
use App\Models\StoreCount;
use App\Models\SubVirables;
use App\Models\ReturnPurchProducts;
use App\Models\ExpireDateQty;
use App\Models\ProductUnits;
use App\Models\ProductMoves;
use App\Models\ProductsQty;
use App\Models\Purchases;
use App\Models\Stores;
use App\Models\StoresDefaultData;
use App\Models\Products;
use App\Models\ReturnPurch;
use App\Models\ProductsPurchases;



use App\Events\AddJournalizingEvent;
use DB;
use App\Services\Average;
use App\Services\PurchasesService;

class ReturnPurchasesListener
{


     use GeneralTrait;

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  \App\Events\TestEvent  $event
     * @return void
     */
    public function handle(ReturnPurchasesEvent $event)
    {

       $service = new PurchasesService ;
       $average = new Average ;

      $Bill=ReturnPurch::findOrFail($event->ID);
      $branch=Stores::findOrFail($event->requests['Store']);
      $def=StoresDefaultData::latest('id')->first();



        if(!empty($event->requests['Delegate'])){

            $Delegate=$event->requests['Delegate'];
        }else{
            $Delegate=null;

        }

          //Notifications

                $order=[
                'noti_name_ar'=>'مرتجع مشتريات',
                'noti_name_en'=>'Purchases Return',
                'type_ar'=>'مرتجع مشتريات',
                'type_en'=>'Purchases Return',
                'type_code'=>$Bill->Code,
                'emp'=>$Delegate,
                'client'=>$event->requests['Vendor'],
                'product'=>null,
                'store'=>$event->requests['Store'],
                'safe'=>$event->requests['Safe'],
                'notify_name'=>trans('admin.PurchasesReturn'),
            ];
            $this->CreateNotification($order);




        //Products Details and Qties

          if(!empty($event->requests['Unit'])){

            StoreCount::truncate();

              $P_Ar_Name=$event->requests['P_Ar_Name'];
              $P_En_Name=$event->requests['P_En_Name'];
              $Unit=$event->requests['Unit'];
              $P_Code=$event->requests['P_Code'];
              $Qty=$event->requests['Qty'];
              $Price=$event->requests['Price'];
              $Discount=$event->requests['Discount'];
              $TotalBFTax=$event->requests['TransTotalBF'];
              $TotalTax=$event->requests['TransTotTax'];
              $PurchTax=$event->requests['PurchTax'];
              $Total=$event->requests['TransTotal'];
              $StorePurch=$event->requests['StorePurch'];
              $Exp_Date=$event->requests['Exp_Date'];
              $Product=$event->requests['Product'];
              $VOne=$event->requests['VOne'];
              $VTwo=$event->requests['VTwo'];
              $V_Name=$event->requests['V_Name'];
              $VV_Name=$event->requests['VV_Name'];
              $Exp_Date=$event->requests['Exp_Date'];
              $OQty=$event->requests['Original_Qty'];
              $RQty=$event->requests['Return_Qty'];
              $TDiscount=$event->requests['TDiscPro'];

            for($i=0 ; $i < count($Unit) ; $i++){

            $pp=ProductUnits::where('Product',$Product[$i])->where('Unit',$Unit[$i])->first();
            $plow=ProductUnits::where('Product',$Product[$i])->where('Def',1)->first();

                $uu['Product_Code']=$P_Code[$i];
                $uu['P_Ar_Name']=$P_Ar_Name[$i];
                $uu['P_En_Name']=$P_En_Name[$i];
                $uu['V_Name']=$V_Name[$i];
                $uu['VV_Name']=$VV_Name[$i];
                $uu['Original_Qty']=$OQty[$i];
                $uu['Return_Qty']=$RQty[$i];
                $uu['Qty']=$Qty[$i];
                $uu['Price']=$Price[$i];
                $uu['Discount']=$Discount[$i];
                $uu['Tax']=$PurchTax[$i];
                $uu['Total_Bf_Tax']=$TotalBFTax[$i];
                $uu['Total_Tax']=$TotalTax[$i];
                $uu['Total']=$Total[$i];
                $uu['Store']=$StorePurch[$i];
                $uu['Product']=$Product[$i];
                $uu['Unit']=$Unit[$i];
                $uu['Exp_Date']=$Exp_Date[$i];
                $uu['Return']=$event->ID;
                $uu['Date']=$event->requests['Date'];
                $uu['Code']=$Bill->Code;
                    $uu['TDiscount']=$TDiscount[$i];
                $uu['Refernce_Number']=$event->requests['Refernce_Number'];
                $uu['Safe']=$event->requests['Safe'];
                $uu['Vendor']=$event->requests['Vendor'];
                $uu['Delegate']=$event->requests['Delegate'];
                $uu['Coin']=$event->requests['Coin'];
                $uu['User']=auth()->guard('admin')->user()->id;
                $uu['Cost_Center']=$event->requests['Cost_Center'];
                $uu['Type']='مرتجع مشتريات';
                $uu['TypeEn']='Purchases Return';
                 $uu['Ship']=$event->requests['Ship'];
                if( !empty($V_Name[$i]) and !empty($VV_Name[$i])){

                $my_value = $V_Name[$i];
                $first_word = explode(' - ',trim($my_value))[0];
                $second_word = explode(' - ',trim($my_value))[1];

                $vId=SubVirables::where('Name','like', $first_word.'%')->first();
                $vvId=SubVirables::where('Name','like', $second_word.'%')->first();
                if(empty($vId)){
                $vId=SubVirables::where('NameEn','like', $first_word.'%')->first();
                }

                if(empty($vvId)){
                $vvId=SubVirables::where('NameEn','like', $second_word.'%')->first();
                }
                $uu['V1']=$vId->id;
                $uu['V2']=$vvId->id;

                }else{

                $uu['V1']=$VOne[$i];
                $uu['V2']=$VTwo[$i];
                }

               ReturnPurchProducts::create($uu);



         $Quantity=$this->ProAvQties($StorePurch[$i],$Product[$i],$P_Code[$i]);


              if(!empty($Quantity)){

                  //if have old Qty

              $unit=ProductUnits::where('Unit',$Unit[$i])->where('Product',$Product[$i])->first();
              $plow=ProductUnits::where('Product',$Product[$i])->where('Def',1)->first();

              $qq= $unit->Rate * $RQty[$i] ;
              $newqty=$Quantity->Qty - $qq ;

             $ty=$average->AverageCostGetUnit($Product[$i],$plow->Barcode,$StorePurch[$i],$Unit[$i]);

                $CostTotalSale=$ty * $qq;
                      $in=0;
                    $out=$CostTotalSale;
                  $current=$newqty * ($ty / $unit->Rate);
                  $cur=$newqty * ($ty / $unit->Rate) ;

                  //Remove Qty from Store
              ProductsQty::where('id',$Quantity->id)->update(['Qty'=>$newqty,'Exp_Date'=>$Exp_Date[$i],'Price'=>$ty , 'TotalCost'=>$cur]);

              $prooooo=Products::find($Product[$i]);

                            //Product Moves
        $move=[

            'Date'=>$event->requests['Date'],
            'Type'=>'مرتجع مشتريات' ,
            'TypeEn'=>'Purchases Return',
            'Bill_Num'=>$Bill->Code,
            'Incom'=>0,
            'Outcom'=>$qq,
            'Current'=>$newqty,
             'CostIn'=>number_format((float)$in, 2, '.', ''),
            'CostOut'=>number_format((float)$out, 2, '.', ''),
            'CostCurrent'=>number_format((float)$current, 2, '.', ''),
            'P_Ar_Name'=>$P_Ar_Name[$i],
            'P_En_Name'=>$P_En_Name[$i],
            'P_Code'=>$P_Code[$i],
            'Unit'=>$Unit[$i],
            'Qty'=>$RQty[$i],
            'Group'=>$prooooo->Group,
            'Store'=>$StorePurch[$i],
            'Product'=>$Product[$i],
            'V1'=>$VOne[$i],
            'V2'=>$VTwo[$i],
            'Brand'=>$prooooo->Brand,
            'Safe'=>$event->requests['Safe'],
            'Branch'=>$branch->Branch,
            'SalePrice'=>$plow->Price,
            'ProductPrice'=>null,
            'Delegate'=>$event->requests['Delegate'],
            'Payment_Method'=>$event->requests['Payment_Method'],
            'User'=>auth()->guard('admin')->user()->id,

        ];

    $this->ProductMoves($move);


              }

                if(!empty($Exp_Date[$i])){


                    $unit=ProductUnits::where('Unit',$Unit[$i])->where('Product',$Product[$i])->first();

         $EXPO=$this->ExpireAvQties($StorePurch[$i],$Product[$i],$P_Code[$i]);

                    if(!empty($EXPO)){


                        if($EXPO->Exp_Date == $Exp_Date[$i]){


                                       $qq= $unit->Rate * $Qty[$i] ;
              $NewExpQty=$EXPO->Qty - $qq ;
              ExpireDateQty::where('id',$EXPO->id)->update(['Qty'=>$NewExpQty]);


                        }


                    }



                }

                            //Fifo
                if($def->Cost_Price == 2){

          $fifo=$this->FifoAvQty($StorePurch[$i],$Product[$i],$P_Code[$i],$event->requests['Date']);

    if(!empty($fifo)){

           $unit=ProductUnits::where('Unit',$Unit[$i])->where('Product',$Product[$i])->first();

           $qq= $unit->Rate * $Qty[$i] ;

           $newqty=$fifo->Qty -  $qq ;

               FifoQty::where('id',$fifo->id)->update(['Qty'=>$newqty,'Original_Qty'=>$newqty]);

    }




    }



                 $Mkhazns=StoreCount::all();

                 if(count($Mkhazns) == 0){

                 $s['Store']=$StorePurch[$i];
                 $s['Total']=$TotalBFTax[$i];
                 $s['Tax']=$PurchTax[$i];
                 StoreCount::create($s);

                 }else{


                 $m=StoreCount::where('Store',$StorePurch[$i])->first();

                 if(!empty($m)){


                 $newTot=$m->Total + $TotalBFTax[$i] ;

                 StoreCount::where('id',$m->id)->update(['Total'=>$newTot]);

                 }else{


                 $s['Store']=$StorePurch[$i];
                 $s['Total']=$TotalBFTax[$i];
                 $s['Tax']=$PurchTax[$i];
                 StoreCount::create($s);

                 }

                 }

                  if($RQty[$i] != 0){

           $prooo= ProductsPurchases::where('Purchase',$Bill->Purchase)
                ->where('Product_Code',$P_Code[$i])
                ->where('Store',$StorePurch[$i])
                ->where('Product',$Product[$i])
                ->where('Unit',$Unit[$i])
                ->first();


            $NSQty= $prooo->SmallQty - ($RQty[$i] * $pp->Rate) ;
            $NQty= $prooo->Qty - $RQty[$i] ;
            $NBF= $prooo->Total_Bf_Tax - $TotalBFTax[$i] ;
            $NTtax= $prooo->Total_Tax - $TotalTax[$i] ;
            $NTot= $prooo->Total - $Total[$i] ;
            $NTotNet= $prooo->Total_Net - ($Total[$i]+$TotalTax[$i] - ($RQty[$i] * $prooo->Discount)) ;


 ProductsPurchases::where('id',$prooo->id)->update(['Qty'=> $NQty,'SmallQty'=>$NSQty,'Total_Bf_Tax'=>$NBF,'Total_Tax'=>$NTtax,'Total'=>$NTot,'Total_Net'=>$NTotNet]);

            }

            }


          }


             //Stores Moves
          $totpri=$event->requests['Total_Return_Qty'];

         $dataStMove=[

            'Date'=>date('Y-m-d'),
            'Code'=>$Bill->Code ,
            'Time'=>date("h:i:s a", time()),
            'Branch'=>$branch->Branch,
            'Store'=>$event->requests['Store'],
            'Safe'=>$event->requests['Safe'],
            'Type'=>'مرتجع مشتريات',
            'TypeEn'=>'Purchases Return',
            'Cost_Center'=>$event->requests['Cost_Center'],
            'User'=>auth()->guard('admin')->user()->id,
            'Coin'=>$event->requests['Coin'],
            'Note'=>$event->requests['Note'],
            'Total_Qty'=>$event->requests['Total_Return_Qty'],
            'Total_Price'=>$totpri,
            'Account'=>$event->requests['Vendor'],
            'Ship'=>$event->requests['Ship'],
            'ID'=>$event->ID,

        ];

         $this->StoresMoves($dataStMove);










    }
}
