<?php

namespace App\Listeners\ReciptVoucher;

use App\Events\AddReciptVoucherEvent;
use App\Models\ProductSales;
use App\Models\Sales;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use App\Traits\GeneralTrait;
use App\Models\Journalizing;
use App\Models\ReciptVoucherDetails;
use App\Models\ReciptVoucher;
use App\Models\SafesBanks;
use App\Events\AddJournalizingEvent;
use DB;

class AddReciptVoucherListener
{


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

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

        if(empty($event->requests['Sales_Bill'])){
            $event->requests['Sales_Bill']=null;
        }


        $IDD = DB::table('recipt_vouchers')->insertGetId(

        array(


            'Date' => $event->requests['Date'],
             'Draw' => $event->requests['Draw'],
            'Coin' => $event->requests['Coin'],
            'Safe' => $event->requests['Safe'],
            'Cost_Center' => $event->requests['Cost_Center'],
            'Total_Creditor' =>$event->requests['Total_Creditor'],
            'Note' =>$event->requests['Note'],
            'Collector' =>$event->requests['Collector'],
            'Sales_Bill' =>$event->requests['Sales_Bill'],
             'Status' => $event->status,
             'File' => $event->zfile,

        )
    );




         $Debitor = $event->requests['Creditor'];
         $Account = $event->requests['Account'];
         $Statement = $event->requests['Statement'];
         $Bill_Num = $event->requests['Bill_Num'];


        for($z=0 ; $z < count($Debitor) ; $z++){

        $PRODUCTS['RV_ID']=$IDD;
        $PRODUCTS['Creditor']=$Debitor[$z];
        $PRODUCTS['Account']=$Account[$z];
        $PRODUCTS['Bill_Num']=$Bill_Num[$z];
        $PRODUCTS['Statement']=$Statement[$z];

         ReciptVoucherDetails::create($PRODUCTS);



            //Sales Bill
            if($event->status == 1) {
                if ($Bill_Num[$z] != null) {


                    $item = Sales::where('Code', $Bill_Num[$z])->latest('id')->first();

                    if (!empty($item)) {


                        $resdiual=$item->Total_Net - $item->Pay ;

                        $recipt=ReciptVoucherDetails::whereRelation('RV_ID','Status',1)->whereRelation('RV_ID','Delete',null)->whereRelation('RV_ID','Edit',null)->where('Bill_Num',$item->Code)->get()->sum('Creditor');

                        $totRes= $resdiual -  $recipt ;

                        $paid=$totRes - $Debitor[$z] ;


                        if($paid == 0){

                            Sales::where('id', $item->id)->update(['Later_Collection' => 1]);


                            $Pros = ProductSales::where('Sales', $item->id)->get();

                            foreach ($Pros as $pro) {

                                ProductSales::where('id', $pro->id)->update(['Later_Collection' => 1]);

                            }

                        }
                    }

                }
            }







        }



        //Notifications

        if($event->status == 0){

              $order=[
                'noti_name_ar'=>' سند قبض يحتاج للتأكيد',
                'noti_name_en'=>'Receipt Voucher Need Confirmation',
                'type_ar'=>'سند قبض',
                'type_en'=>'Receipt Voucher',
                'type_code'=>$event->requests['Code'],
                'emp'=>null,
                'client'=>null,
                'product'=>null,
                'store'=>null,
                'safe'=>null,
                'notify_name'=>trans('admin.Receipt_Voucher_Need_Confirmation'),
            ];
            $this->CreateNotification($order);


        }


      //Recipt Jounralizing
         if($event->status == 1){

             $type_ar= 'سند قبض';
             $type_en= 'Receipt Voucher';
             $type=0;
             $Status=1;
             $custom=1;
             $Branch=SafesBanks::where('Account',$event->requests['Safe'])->latest('id')->first()->Branch;
             $code_type=ReciptVoucher::findOrFail($IDD);

             $custom_data=[
             'Debitor'=>$event->requests['Total_Creditor'],
             'Creditor'=>0,
             'Account'=>$event->requests['Safe'],
             'Statement'=>$event->requests['Note'],
             'Safe'=>$event->requests['Safe'],
             'Branch'=>$Branch,
             'Code_Type'=>$code_type->Code,
             'Date'=>$event->requests['Date'],
             'Draw'=>$event->requests['Draw'],
             'Coin'=>$event->requests['Coin'],
             'Cost_Center'=>$event->requests['Cost_Center'],

             ];



             AddJournalizingEvent::dispatch($event->requests,$Status,$type,$type_ar,$type_en,$custom,$custom_data);


         }






    }
}
