<?php

namespace App\Listeners\Settlement;

use App\Events\SettlementEvent;
use App\Models\FifoQty;
use App\Models\GeneralDaily;
use App\Models\JournalizingDetails;
use App\Models\ProductSettlement;
use App\Models\ProductsStartPeriods;
use App\Models\Settlement;
use App\Models\StartPeriods;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use App\Traits\GeneralTrait;

use App\Models\Journalizing;
use App\Models\SubVirables;
use App\Models\ExpireDateQty;
use App\Models\ProductUnits;
use App\Models\ProductMoves;
use App\Models\ProductsQty;
use App\Models\Stores;
use App\Models\StoresDefaultData;
use App\Models\Products;
use DB;
use App\Services\Average;


class SettlementListener
{


    use GeneralTrait;

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

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


        $average = new Average ;

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



        //Notifications
        $order=[
            'noti_name_ar'=>'التسويه',
            'noti_name_en'=>'Settlements',
            'type_ar'=>'التسويه',
            'type_en'=>'Settlements',
            'type_code'=>$Bill->Code,
            'emp'=>null,
            'client'=>null,
            'product'=>null,
            'store'=>$event->requests['Store'],
            'safe'=>null,
            'notify_name'=>trans('admin.Settlements'),
        ];
        $this->CreateNotification($order);


        //Products Details and Qties
        if(!empty($event->requests['Unit'])){

            $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'];
            $P_Qty=$event->requests['Qty'];
            $P_Price=$event->requests['Price'];
            $Exp_Date=$event->requests['Exp_Date'];
            $P_Product=$event->requests['Product'];
            $P_VOne=$event->requests['VOne'];
            $P_VTwo=$event->requests['VTwo'];
            $V_Name=$event->requests['V_Name'];
            $VV_Name=$event->requests['VV_Name'];
            $P_Inventory=$event->requests['Inventory'] ;
            $P_Dificit=$event->requests['Dificit'] ;
            $P_Excess=$event->requests['Excess'] ;
            $TotalDificitP=$event->requests['TotalDificitP'] ;
            $TotalExcessP=$event->requests['TotalExcessP'] ;

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

                $uu['Set_ID']=$event->ID;
                $uu['P_Code']=$P_Code[$i];
                $uu['Av_Qty']=$P_Qty[$i];
                $uu['Inventory']=$P_Inventory[$i];
                $uu['Deficit']=$P_Dificit[$i];
                $uu['Excess']=$P_Excess[$i];
                $uu['Product']=$P_Product[$i];
                $uu['V1']=$P_VOne[$i];
                $uu['V2']=$P_VTwo[$i];
                $uu['Unit']=$Unit[$i];
                $uu['Price']=$P_Price[$i];
                $uu['TotalDificitP']=$TotalDificitP[$i];
                $uu['TotalExcessP']=$TotalExcessP[$i];
                $uu['Store']=$event->requests['Store'];
                $uu['Coin']=$event->requests['Coin'];
                $uu['User']=auth()->guard('admin')->user()->id;
                $uu['Date']=$event->requests['Date'];
                $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['Exp_Date']=$Exp_Date[$i];

                ProductSettlement::create($uu);



                $Quantity=$this->ProAvQties($event->requests['Store'],$P_Product[$i],$P_Code[$i]);

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

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


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


                    $newQQty= $unit->Rate * $P_Inventory[$i];


                    $ty=$average->AverageCostGetUnitTwo($P_Product[$i],$P_Code[$i],$event->requests['Store'],$Unit[$i]);



                    $current=$newQQty * ($ty / $unit->Rate);
                    $CostTotalSale=$ty * $newQQty;

                    $out=$CostTotalSale  ;
                    $in=0 ;
                    $inn=0;
                    $outt=$P_Dificit[$i];

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

                        $fifos =FifoQty::
                        where('Store',$event->requests['Store'])
                            ->where('Product',$P_Product[$i])
                            ->where('P_Code',$P_Code[$i])
                            ->orderBy('Purchases_Date','asc')
                            ->get();




                        if(!empty($fifos)){
                            foreach($fifos as $fifo){
                                if($fifo->Qty != 0){



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

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

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



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



                                }
                            }

                        }


                    }




                }else{


                    $newQQty= $unit->Rate * $P_Inventory[$i];


                    $ty=$average->AverageCostGetUnitTwo($P_Product[$i],$unit->Barcode,$event->requests['Store'],$unit->Unit);
                    $current=$newQQty * ($ty / $unit->Rate);
                    $CostTotalSale=$ty * $newQQty;

                    $in=$CostTotalSale ;
                    $out=0 ;
                    $inn=$P_Excess[$i] ;
                    $outt=0;






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

                        $fifos =FifoQty::
                        where('Store',request('Store'))
                            ->where('Product',$P_Product[$i])
                            ->where('P_Code',$P_Code[$i])
                            ->orderBy('Purchases_Date','asc')
                            ->get();



                        if(!empty($fifos)){
                            foreach($fifos as $fifo){


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

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

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



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

                            }

                        }


                    }





                }




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


                    $unit=ProductUnits::where('Unit',$Unit[$i])->where('Product',$P_Product[$i])->first();
                    $EXPO=$this->ExpireAvQties($event->requests['Store'],$P_Product[$i],$P_Code[$i]);



                    if(!empty($EXPO)){


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

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

                        }


                    }



                }


                ProductsQty::where('id',$Quantity->id)->update(['Qty'=>$qq,'Price'=>$ty, 'TotalCost'=>$current]);





                //Product Moves
                $move=[

                    'Date'=>$event->requests['Date'],
                    'Type'=>  'تسويه' ,
                    'TypeEn'=>'Settlement',
                    'Bill_Num'=>$Bill->Code,
                    'Incom'=>$inn,
                    'Outcom'=>$outt,
                    'Current'=>$qq,
                    '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'=>$P_Inventory[$i] + $P_Dificit[$i],
                    'Group'=>$prooooo->Group,
                    'Store'=>$event->requests['Store'],
                    'Product'=>$P_Product[$i],
                    'V1'=>$P_VOne[$i],
                    'V2'=>$P_VTwo[$i],
                    'Brand'=>$prooooo->Brand,
                    'Safe'=>null,
                    'Branch'=>$branch->Branch,
                    'SalePrice'=>$unit->Price,
                    'ProductPrice'=>null,
                    'Delegate'=>null,
                    'Payment_Method'=>null,
                    'User'=>auth()->guard('admin')->user()->id,

                ];

                $this->ProductMoves($move);


            }


        }




        //Joun

        if($event->requests['Total_Dificit_Price'] != 0){



            $JunID = DB::table('journalizings')->insertGetId(

                array(

                    'Type' => 'تسوية بالعجز',
                    'TypeEn' => 'Dificit Settlement',
                    'Code_Type' => $Bill->Code,
                    'Date' =>$event->requests['Date'] ,
                    'Draw' =>$event->requests['Draw'],
                    'Coin' =>$event->requests['Coin'],
                    'Cost_Center' => null,
                    'Total_Debaitor' => $event->requests['Total_Dificit_Price'],
                    'Total_Creditor' => $event->requests['Total_Dificit_Price'],
                    'Note' => $event->requests['Note'],

                )
            );


            $Code=Journalizing::findOrFail($JunID)->Code;



            $PRODUCTSS['Joun_ID']=$JunID;
            $PRODUCTSS['Debitor']=0;
            $PRODUCTSS['Creditor']=$event->requests['Total_Dificit_Price'];
            $PRODUCTSS['Account']=$store->Account;
            $PRODUCTSS['Statement']=$event->requests['Note'];


            JournalizingDetails::create($PRODUCTSS);

            $Gen['Code']=$Code;
            $Gen['Code_Type']=$Bill->Code;
            $Gen['Date']=$event->requests['Date'];
            $Gen['Type']= 'تسوية بالعجز';
            $Gen['TypeEn']='Dificit Settlement';
            $Gen['Debitor']=0;
            $Gen['Creditor']=$event->requests['Total_Dificit_Price'];
            $Gen['Statement']=$event->requests['Note'];
            $Gen['Draw']=$event->requests['Draw'];
            $Gen['Debitor_Coin']= $event->requests['Draw'] * 0;
            $Gen['Creditor_Coin']=$event->requests['Draw'] * $event->requests['Total_Dificit_Price'];
            $Gen['Account']=$store->Account;
            $Gen['Coin']= $event->requests['Coin'];
            $Gen['Cost_Center']=null;
            $Gen['userr']= auth()->guard('admin')->user()->id;

            GeneralDaily::create($Gen);


            $PRODUCTSS['Joun_ID']=$JunID;
            $PRODUCTSS['Debitor']=$event->requests['Total_Dificit_Price'];
            $PRODUCTSS['Creditor']=0;
            $PRODUCTSS['Account']=$event->requests['Account_Dificit'];
            $PRODUCTSS['Statement']=$event->requests['Note'];


            JournalizingDetails::create($PRODUCTSS);

            $Gen['Code']=$Code;
            $Gen['Code_Type']=$Bill->Code;
            $Gen['Date']=$event->requests['Date'];
            $Gen['Type']= 'تسوية بالعجز';
            $Gen['TypeEn']='Dificit Settlement';
            $Gen['Debitor']=$event->requests['Total_Dificit_Price'];
            $Gen['Creditor']=0;
            $Gen['Statement']=$event->requests['Note'];
            $Gen['Draw']=$event->requests['Draw'];
            $Gen['Debitor_Coin']= $event->requests['Draw'] * $event->requests['Total_Dificit_Price'];
            $Gen['Creditor_Coin']=$event->requests['Draw'] * 0;
            $Gen['Account']=$event->requests['Account_Dificit'];
            $Gen['Coin']= $event->requests['Coin'];
            $Gen['Cost_Center']= null;
            $Gen['userr']= auth()->guard('admin')->user()->id;

            GeneralDaily::create($Gen);

        }

        if($event->requests['Total_Excess_Price'] != 0){

            $JunID = DB::table('journalizings')->insertGetId(

                array(


                    'Type' => 'تسوية بالزيادة',
                    'TypeEn' => 'Execess Settlement',
                    'Code_Type' => $Bill->Code,
                    'Date' =>$event->requests['Date'] ,
                    'Draw' =>$event->requests['Draw'],
                    'Coin' =>$event->requests['Coin'],
                    'Cost_Center' => null,
                    'Total_Debaitor' => $event->requests['Total_Excess_Price'],
                    'Total_Creditor' => $event->requests['Total_Excess_Price'],
                    'Note' => $event->requests['Note'],

                )
            );

            $Code=Journalizing::findOrFail($JunID)->Code;



            $PRODUCTSS['Joun_ID']=$JunID;
            $PRODUCTSS['Debitor']=$event->requests['Total_Excess_Price'];
            $PRODUCTSS['Creditor']=0;
            $PRODUCTSS['Account']=$store->Account;
            $PRODUCTSS['Statement']=$event->requests['Note'];


            JournalizingDetails::create($PRODUCTSS);

            $Gen['Code']=$Code;
            $Gen['Code_Type']=$Bill->Code;
            $Gen['Date']=$event->requests['Date'];
            $Gen['Type']='تسوية بالزيادة';
            $Gen['TypeEn']='Execess Settlement';
            $Gen['Debitor']=$event->requests['Total_Excess_Price'];
            $Gen['Creditor']=0;
            $Gen['Statement']=$event->requests['Note'];
            $Gen['Draw']=$event->requests['Draw'];
            $Gen['Debitor_Coin']= $event->requests['Draw'] * $event->requests['Total_Excess_Price'];
            $Gen['Creditor_Coin']=$event->requests['Draw'] * 0;
            $Gen['Account']=$store->Account;
            $Gen['Coin']= $event->requests['Coin'];
            $Gen['Cost_Center']=null;
            $Gen['userr']= auth()->guard('admin')->user()->id;

            GeneralDaily::create($Gen);


            $PRODUCTSS['Joun_ID']=$JunID;
            $PRODUCTSS['Debitor']=0;
            $PRODUCTSS['Creditor']=$event->requests['Total_Excess_Price'];
            $PRODUCTSS['Account']=$event->requests['Account_Excess'];
            $PRODUCTSS['Statement']=$event->requests['Note'];


            JournalizingDetails::create($PRODUCTSS);

            $Gen['Code']=$Code;
            $Gen['Code_Type']=$Bill->Code;
            $Gen['Date']=$event->requests['Date'];
            $Gen['Type']='تسوية بالزيادة';
            $Gen['TypeEn']='Execess Settlement';
            $Gen['Debitor']=0;
            $Gen['Creditor']=$event->requests['Total_Excess_Price'];
            $Gen['Statement']=$event->requests['Note'];
            $Gen['Draw']=$event->requests['Draw'];
            $Gen['Debitor_Coin']= $event->requests['Draw'] * 0;
            $Gen['Creditor_Coin']=$event->requests['Draw'] * $event->requests['Total_Excess_Price'];
            $Gen['Account']=$event->requests['Account_Excess'];
            $Gen['Coin']= $event->requests['Coin'];
            $Gen['Cost_Center']= null;
            $Gen['userr']= auth()->guard('admin')->user()->id;

            GeneralDaily::create($Gen);

        }


        //Stores Moves
        $totpri=($event->requests['Total_Dificit_Price'] + $event->requests['Total_Excess_Price']) ;
        $TotQty=($event->requests['Total_Dificit'] + $event->requests['Total_Excess']) ;

        $dataStMove=[

            'Date'=>date('Y-m-d'),
            'Code'=>$Bill->Code ,
            'Time'=>date("h:i:s a", time()),
            'Branch'=>$branch->Branch,
            'Store'=>$event->requests['Store'],
            'Safe'=>null,
            'Type'=>'بدايه فتره',
            'TypeEn'=>'Start Period',
            'Cost_Center'=>null,
            'User'=>auth()->guard('admin')->user()->id,
            'Coin'=>$event->requests['Coin'],
            'Note'=>$event->requests['Note'],
            'Total_Qty'=>$TotQty,
            'Total_Price'=>$totpri,
            'Account'=>null,
            'Ship'=>null,
            'ID'=>$event->ID,

        ];

        $this->StoresMoves($dataStMove);



    }
}
