<?php

namespace App\Listeners\HR;

use App\Events\SalaryDue;
use App\Models\AccountsDefaultData;
use App\Models\AllowencesEmp;
use App\Models\Borrowa;
use App\Models\Deduction;
use App\Models\DepartureEmp;
use App\Models\DiscountsEmp;
use App\Models\EmpInstallmentDetails;
use App\Models\Employess;
use App\Models\EmpRatio;
use App\Models\EmpsProducationPoint;
use App\Models\EmpsProducationQuantity;
use App\Models\Entitlement;
use App\Models\Holidays;
use App\Models\Journalizing;
use App\Models\PaySalary;
use App\Models\RegOverTime;
use App\Models\Sales;
use App\Models\Settlement;
use App\Models\ShippingList;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use App\Traits\GeneralTrait;
use App\Models\JournalizingDetails;
use App\Models\GeneralDaily;
use App\Models\Assets;
use DB;
use DateTime;

class SalaryDueListener
{


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

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

        $Emps=Employess::where('Active',1)->whereNotIn('id',[38,39,40,41,42])->get();
        $AccDefff=AccountsDefaultData::latest('id')->first();
        $Alls=GeneralDaily::where('Type','استحقاق راتب')->whereBetween('Date',[date('Y-m-01'),date('Y-m-31')])->get();
        if(count($Alls) != 0){



            if($AccDefff->Salary == 2){

                foreach($Emps as $emp){



                    $Emp=$emp->id;
                    $Month=date('Y-m');
                    $Sal=Employess::find($Emp);
                    $x = Borrowa::where("Month",$Month)->where('Emp',$Emp)->get()->sum('Amount');
                    $pp = EmpsProducationPoint::where("Month",$Month)->where('Emp',$Emp)->get()->sum('Point');
                    $point=0;
                    $newpp=0;

                    $Qties=EmpsProducationQuantity::where('Emp',$Emp)->get();

                    foreach($Qties as $qty){

                        if($qty->FromQ <= $pp){
                            if($qty->ToQ <= $pp){
                                $newpp=$pp - $qty->ToQ ;
                                $point+=$qty->ValueQ * ($pp - $newpp);

                            }

                            if($qty->ToQ >= $pp){
                                if($newpp != 0){
                                    $point+=$qty->ValueQ * $newpp;
                                }else{

                                    $point+=$qty->ValueQ * $pp;
                                }
                            }

                        }

                    }
                    $PaySalary = PaySalary::where("Month",$Month)->where('Emp',$Emp)->first();

                    $month=$Month.'01';

                    $SETT=Settlement::
                    where('Date','>=',$month)
                        ->where('Account_Dificit',$Sal->Account)->get()->sum('Total_Dificit_Price');

                    $saleslater=Sales::
                    where('Status',1)
                        ->where('Date','>=',$month)
                        ->where('Delegate',$Emp)
                        ->where('Payment_Method','Later')
                        ->where('Later_Collection',0)
                        ->get()
                        ->sum('Total_Price');



                    $LATER= 0  ;


                    $s=0;
                    $xx=0;
                    $xxx=0;
                    $xxxx=0;


                    $sales=Sales::
                    where('Status',1)
                        ->where('Delegate',$Emp)
                        ->get();

                    $Ex=Sales::
                    where('Status',1)
                        ->where('Executor',$Emp)
                        ->get();

                    $ShP=ShippingList::
                    where('Status',1)
                        ->where('Driver',$Emp)
                        ->get();



                    $Ratios=EmpRatio::where('Emp',$Emp)->get();

                    foreach($sales as $sel){

                        $date=$sel->Date;
                        $time=strtotime($date);
                        $month=date("Y-m",$time);

                        if($month == $Month){
                            $s += $sel->Total_Price;
                        }

                    }

                    foreach($Ex as $ex){

                        $date=$ex->Date;

                        $time=strtotime($date);
                        $month=date("Y-m",$time);

                        if($month == $Month){
                            $xx += $ex->Total_Price;
                        }

                    }

                    foreach($ShP as $shp){

                        $date=$shp->Date;

                        $time=strtotime($date);
                        $month=date("Y-m",$time);

                        if($month == $Month){
                            $xxxx += $shp->Total_Price;
                        }

                    }




                    $DED=Deduction::where('Month',$Month)->where('Emp',$Emp)->get()->sum('Amount') ;
                    $ENTIT=Entitlement::where('Month',$Month)->where('Emp',$Emp)->get()->sum('Amount') ;

                    $EmpDets=EmpInstallmentDetails::where('Emp',$Emp)->get() ;

                    foreach($EmpDets as $emD){

                        $date=$emD->Date;

                        $time=strtotime($date);
                        $month=date("Y-m",$time);

                        if($month == $Month){
                            $xxx += $emD->Value;
                        }

                    }

                    $OVER=RegOverTime::where('Month',$Month)->where('Emp',$Emp)->get()->sum('Amount') ;
                    $Attendence=DepartureEmp::where('Month',$Month)->where('Emp',$Emp)->get()->sum('Hours_Number') ;
                    $DiscountLate=DepartureEmp::where('Month',$Month)->where('Emp',$Emp)->get()->sum('Disc_Late') ;
                    $DiscountDeparture=DepartureEmp::where('Month',$Month)->where('Emp',$Emp)->get()->sum('Disc_Early') ;


                    $HourCost=$Sal->Salary / $Sal->Hours_Numbers ;

                    $disc= $Attendence * $HourCost ;
                    $discT= $Sal->Salary - $disc ;

                    $Holidays=Holidays::where('Month',$Month)->where('Emp',$Emp)->where('Discount',1)->get()->sum('Num_of_Days') ;

                    $WorkDay =  $Sal->Hours_Numbers / 30 ;
                    $HoliDiscount = ($HourCost * $WorkDay) * $Holidays ;


                    if(!empty($PaySalary)){

                        $New = 1 ;

                    }else{

                        $New = 0 ;
                    }

                    $e=0;
                    $PS=0;
                    $PEX=0;
                    foreach($Ratios as $r){

                        if($r->Typee == 1){

                            if($r->From  <=  $xxxx  and $r->To  >=  $xxxx ){

                                $z=$r->Rate  / 100 ;
                                $zz= $z *  $xxxx ;
                                $e += $zz;

                            }else{

                                $e+=0;

                            }


                        }


                        if($r->Typee == 1){

                            if($r->From  <=  $s  and $r->To  >=  $s ){

                                $z=$r->Rate  / 100 ;
                                $zz= $z *  $s ;
                                $PS += $zz;

                            }else{

                                $PS+=0;

                            }


                        }


                        if($r->Typee == 2){

                            if($r->From  <=  $xx  and $r->To  >=  $xx ){

                                $z=$r->Rate  / 100 ;
                                $zz= $z *  $xx ;
                                $PEX += $zz;

                            }else{

                                $PEX+=0;

                            }


                        }

                    }



                    $Allowances=AllowencesEmp::where('Emp',$Emp)->get()->sum('AmountAllow');
                    $Discounts=DiscountsEmp::where('Emp',$Emp)->get()->sum('AmountDiscount');


                    $Borrow = $x ;
                    $Salary = $Sal->Salary ;
                    $Deduction =$DED ;
                    $Entitlement =$ENTIT;
                    $Loan =$xxx ;
                    $Overtime =$OVER ;
                    $Attendence_Discount =$discT ;
                    $Holiday_Discount=$HoliDiscount;
                    $Settlements=$SETT;
                    $Later_Sales_Bill=$LATER;
                    $Allowances =$Allowances;
                    $Discounts=$Discounts;
                    $ProducationPoints=$point;
                    $DiscountLate=$DiscountLate;
                    $DiscountDeparture=$DiscountDeparture;
                    $Shipping_Precent =$e;


                    $Sales = $PS;
                    $Exec =$PEX ;
                    $HWork =$Sal->Hours_Numbers ;
                    $Att =$Attendence  ;
                    $Holi = $Holidays  ;
                    $Neww=$New;

                    //de bta3t khsm 3adm 7door shelha lma yzbtha
                    $Attendence_Discount=0;
                    //de bta3t khsm  Agzat shelha lma yzbtha
                    $Holiday_Discount=0;



                    $result =

                        ( $Salary +  $Entitlement + $Overtime + $Allowances + $ProducationPoints + $Shipping_Precent )

                        -

                        ($Borrow + $Deduction + $Loan + $Attendence_Discount + $Holiday_Discount + $Settlements + $Later_Sales_Bill + $Discounts + $DiscountLate + $DiscountDeparture )

                    ;


                    $S = $New ;

                    if($S != 1){

                        $RS= $result;
                        if($RS == 0 || $RS < 0){


                            $Resduial_Salary = 0 ;

                        }else{

                            $Resduial_Salary = $result ;

                        }

                    }





                    if($Resduial_Salary != 0){

                        $res=Journalizing::orderBy('id','desc')->first();

                        if(!empty($res->Code)){

                            $Code=$res->Code + 1 ;
                        }else{
                            $Code=1;

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

                            array(

                                'Code' => $Code,
                                'Type' => 'استحقاق راتب',
                                'TypeEn' => 'Salary Due',
                                'Code_Type' => $Code,
                                'Date' =>date('Y-m-d'),
                                'Draw' => $AccDefff->Draw,
                                'Coin' => $AccDefff->Coin,
                                'Cost_Center' => null,
                                'Total_Debaitor' => $Resduial_Salary,
                                'Total_Creditor' => $Resduial_Salary,
                                'Note' => request('Note'),

                            )
                        );




                        $PRODUCTSS['Joun_ID']=$ID;
                        $PRODUCTSS['Debitor']=$Resduial_Salary;
                        $PRODUCTSS['Creditor']=0;
                        $PRODUCTSS['Account']=$emp->Account_Emp;
                        $PRODUCTSS['Statement']=null;
                        JournalizingDetails::create($PRODUCTSS);

                        $Gen['Code']=$Code;
                        $Gen['Code_Type']=$Code;
                        $Gen['Date']=date('Y-m-d');
                        $Gen['Type']='استحقاق راتب';
                        $Gen['TypeEn']= 'Salary Due';
                        $Gen['Debitor']=$Resduial_Salary;
                        $Gen['Creditor']=0;
                        $Gen['Statement']=null;
                        $Gen['Draw']=$AccDefff->Draw;
                        $Gen['Debitor_Coin']= $AccDefff->Draw * $Resduial_Salary;
                        $Gen['Creditor_Coin']=$AccDefff->Draw * 0;
                        $Gen['Account']=$emp->Account_Emp;
                        $Gen['Coin']=  $AccDefff->Coin;
                        $Gen['Cost_Center']= null;
                        $Gen['userr']= 1;

                        GeneralDaily::create($Gen);

                        $PRODUCTSS['Joun_ID']=$ID;
                        $PRODUCTSS['Debitor']=0;
                        $PRODUCTSS['Creditor']=$Resduial_Salary;
                        $PRODUCTSS['Account']=$emp->Merit;
                        $PRODUCTSS['Statement']=null;
                        JournalizingDetails::create($PRODUCTSS);

                        $Gen['Code']=$Code;
                        $Gen['Code_Type']=$Code;
                        $Gen['Date']=date('Y-m-d');
                        $Gen['Type']='استحقاق راتب';
                        $Gen['TypeEn']= 'Salary Due';
                        $Gen['Debitor']=0;
                        $Gen['Creditor']=$Resduial_Salary;
                        $Gen['Statement']=null;
                        $Gen['Draw']=$AccDefff->Draw;
                        $Gen['Debitor_Coin']= $AccDefff->Draw * 0;
                        $Gen['Creditor_Coin']=$AccDefff->Draw * $Resduial_Salary;
                        $Gen['Account']=$emp->Merit;
                        $Gen['Coin']=  $AccDefff->Coin;
                        $Gen['Cost_Center']= null;
                        $Gen['userr']=1;

                        GeneralDaily::create($Gen);
                    }


                }




            }



        }





    }
}
