<?php

namespace App\Listeners\Sales;


use App\Events\SalesEventApi;
use App\Models\AssemblyProducts;
use App\Models\Coins;
use App\Models\Customers;
use App\Models\ExpireDateQty;
use App\Models\FifoQty;
use App\Models\InstallmentDates;
use App\Models\ProductMoves;
use App\Models\Products;
use App\Models\ProductSales;
use App\Models\ProductsQty;
use App\Models\ProductUnits;
use App\Models\Sales;
use App\Models\SalesFifoQty;
use App\Models\Shifts;
use App\Models\StoreCountSales;
use App\Models\Stores;
use App\Models\StoresDefaultData;
use App\Models\Taxes;
use App\Models\VAQty;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use App\Traits\GeneralTrait;

use App\Models\Journalizing;
use DB;
use App\Services\Average;
use App\Services\PurchasesService;

class SalesApiListener
{


    use GeneralTrait;

    public function __construct()
    {

    }


    public function handle(SalesEventApi $event)
    {


        $average = new Average ;

        $ID=$event->ID;
        $user=$event->admin_id;
        $def=StoresDefaultData::latest('id')->first();

        $Bill=Sales::findOrFail($ID);
        //rakm ftora llmkhzn
        $sel=Sales::where('Store',$event->requests['Store'])->count();
        $Sor=Stores::find($event->requests['Store']);
        $SorBil= $Sor->Letter . '' .  $sel ;
        Sales::where('id',$ID)->update(['Store_Code'=>$SorBil]);

        $custG=Customers::where('Account',$event->requests['Client'])->latest('id')->first();

        if(!empty($custG)){
            $CUSTGROP=$custG->Group;
        }else{
            $CUSTGROP=null;
        }

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

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

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

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

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

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


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


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


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


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


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

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


        //Noti
        if($event->requests['Status'] == 0){


            $order=[
                'noti_name_ar'=>'فاتوره مبيعات قيد انتظار',
                'noti_name_en'=>'Sales Bill Pending',
                'type_ar'=>'المبيعات',
                'type_en'=>'Sales',
                'type_code'=>$Bill->Code,
                'emp'=>$event->requests['Delegate'],
                'client'=>$event->requests['Client'],
                'product'=>null,
                'store'=>$event->requests['Store'],
                'safe'=>$event->requests['Safe'],
                'notify_name'=>trans('admin.SalesBillPending'),
            ];
            $this->CreateNotification($order);

        }

        if($event->requests['Payment_Method'] == 'Delivery'){



            $order=[
                'noti_name_ar'=>'طلب توصيل',
                'noti_name_en'=>'Delivery Request',
                'type_ar'=>'المبيعات',
                'type_en'=>'Sales',
                'type_code'=>$Bill->Code,
                'emp'=>$event->requests['Delivery'],
                'client'=>$event->requests['Client'],
                'product'=>null,
                'store'=>$event->requests['Store'],
                'safe'=>$event->requests['Safe'],
                'notify_name'=>trans('admin.Delivery_Request'),
            ];
            $this->CreateNotification($order);

        }


        //Event
        if(!empty($event->requests['Later_Due'])){


            $data=[

                'start_date'=>$event->requests['Later_Due'],
                'end_date'=>$event->requests['Later_Due'],
                'event_name_ar'=>'استحقاق فاتوره مبيعات آجل ',
                'event_name_en'=>'Due Sales invoice',
                'type'=>'المبيعات',
                'type_id'=>null,
                'type_code'=>$Bill->Code,
                'emp'=>$event->requests['Delegate'],
                'client'=>$event->requests['Client'],
                'product'=>null,
                'customer'=>null,

            ];


            $this->CreateEvent($data);

        }




        //Qty and Details

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


            StoreCountSales::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'];
            $AvQty=$event->requests['AvQty'];
            $Price=$event->requests['Price'];
            $Discount=$event->requests['Discount'];
            $TotalBFTax=$event->requests['TotalBFTax'];
            $TotalTax=$event->requests['TotalTax'];
            $PurchTax=$event->requests['PurchTax'];
            $Total=$event->requests['Total'];
            $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'];
            $Patch_Number=$event->requests['Patch_Number'];
            $TDiscount=$event->requests['TDiscPro'];
            $CostPrice=$event->requests['CostPrice'];

            if(!empty($event->requests['Total_Wight'])){
                $Total_Wight=$event->requests['Total_Wight'];
            }else{
                $Total_Wight=[];
            }

            if(!empty($event->requests['weight'])){
                $weight=$event->requests['weight'];
            }else{
                $weight=[];
            }

            if(!empty($event->requests['UnitRate'])){
                $UnitRate=$event->requests['UnitRate'];
            }else{
                $UnitRate=[];
            }



            $SalesProDesc=$event->requests['SalesProDesc'];
            $TotCostNew=$event->requests['TotCostNew'];
            $Total_Net=$event->requests['Total_Net'];


            if(!empty($event->requests['SubVID'])){
                $SubVID=$event->requests['SubVID'];
            }else{
                $SubVID=[];
            }




            if(!empty($event->requests['Pro_Note'])){
                $Pro_Note=$event->requests['Pro_Note'];
            }else{
                $Pro_Note=[];
            }



            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();
                $rr = ProductUnits::where("Unit",$Unit[$i])->where('Product',$Product[$i])->first();
                $SS=Stores::find($StorePurch[$i]);
                $PSS=Products::find($Product[$i]);
                $Aomla=Coins::find($event->requests['Coin']);
                $dreba=Taxes::find($PurchTax[$i]);
                $prooooo=Products::find($Product[$i]);

                $uu['Product_Code']=$P_Code[$i];
                $uu['SmallCode']=$plow->Barcode;
                $uu['P_Ar_Name']=$P_Ar_Name[$i];
                $uu['P_En_Name']=$P_En_Name[$i];

                if(!empty($weight[$i])) {
                    $uu['weight']=$weight[$i];
                }else{
                    $uu['weight'] = null;
                }

                $uu['V_Name']=$V_Name[$i];
                $uu['VV_Name']=$VV_Name[$i];
                if(!empty($Total_Wight[$i])) {
                    $uu['Total_Wight']=$Total_Wight[$i];
                }else{
                    $uu['Total_Wight'] = null;
                }
                if(!empty($SubVID[$i])) {
                    $uu['SubVID'] = $SubVID[$i];
                }else{
                    $uu['SubVID'] = null;
                }
                if(!empty($Pro_Note[$i])) {
                    $uu['Pro_Note'] = $Pro_Note[$i];
                }else{
                    $uu['Pro_Note'] = null;
                }

                $uu['Original_Qty']=$Qty[$i];
                $uu['Qty']=$Qty[$i];
                $uu['SmallQty']=$Qty[$i] * $pp->Rate;
                $uu['AvQty']=$AvQty[$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];

                if(!empty($Total_Net[$i])) {
                    $uu['Total_Net']=$Total_Net[$i];
                }else{
                    $uu['Total_Net'] = null;
                }
                $uu['Store']=$StorePurch[$i];
                $uu['TDiscount']=$Discount[$i] * $Qty[$i];

                if(!empty($UnitRate[$i])) {
                    $uu['UnitRate']=$UnitRate[$i];
                }else{
                    $uu['UnitRate'] = null;
                }
                $uu['Product']=$Product[$i];
                $uu['Unit']=$Unit[$i];
                $uu['Exp_Date']=$Exp_Date[$i];
                $uu['Sales']=$ID;
                $uu['V1']=$VOne[$i];
                $uu['V2']=$VTwo[$i];
                $uu['Date']=$event->requests['Date'];
                $uu['Code']=$Bill->Code;
                $uu['Refernce_Number']=$event->requests['Refernce_Number'];
                $uu['Safe']=$event->requests['Safe'];
                $uu['Client']=$event->requests['Client'];
                $uu['Executor']=$event->requests['Executor'];
                $uu['Delegate']=$event->requests['Delegate'];
                $uu['Coin']=$event->requests['Coin'];
                $uu['Ship']=$event->requests['Ship'];
                $uu['User']=$user;
                $uu['Cost_Center']=$event->requests['Cost_Center'];
                $uu['Type']='مبيعات';
                $uu['TypeEn']='Sales';
                if(!empty($Patch_Number[$i])) {
                    $uu['Patch_Number'] = $Patch_Number[$i];
                }else{
                    $uu['Patch_Number'] = null;
                }
                if(!empty($SalesProDesc[$i])) {
                    $uu['SalesProDesc']=$SalesProDesc[$i];
                }else{
                    $uu['SalesProDesc'] = null;
                }

                $uu['CostPrice']=$CostPrice[$i];
                $uu['Branch']=$SS->Branch;
                $uu['Group']=$PSS->Group;
                $uu['Brand']=$PSS->Brand;
                $uu['CustomerGroup']=$CUSTGROP;
                $uu['Status']=$event->requests['Status'];
                $uu['Payment_Method']=$event->requests['Payment_Method'];
                if(!empty($TotCostNew[$i])) {
                    $uu['TotCostNew']=$TotCostNew[$i];
                }else{
                    $uu['TotCostNew'] = null;
                }
                $uu['CoinCode']=$Aomla->Code;
                if($Aomla->Code == 'EGP'){
                    $uu['CoinRate']=0.00;
                    $uu['CoinPrice']=0.00;
                    $uu['AmountEGP']=$Price[$i];
                }else{
                    $uu['CoinRate']=$Aomla->Draw;
                    $uu['CoinPrice']=$Price[$i];
                    $uu['AmountEGP']=$Aomla->Draw * $Price[$i];
                }
                $uu['SalesTotal']=$Price[$i] * $Qty[$i] ;
                $uu['DiscountAmount']=$Discount[$i] * $Qty[$i] ;
                $uu['NetTotal']=($Price[$i] * $Qty[$i])  - ($Discount[$i] * $Qty[$i]) ;
                $NET=($Price[$i] * $Qty[$i])  - ($Discount[$i] * $Qty[$i]);
                if(!empty($dreba)){
                    $TAM=($dreba->Rate / 100 ) * $NET ;
                    $uu['TaxType']=$dreba->CodeTax ;
                    $uu['TaxSubType']=$dreba->SubType ;
                    $uu['TaxRate']=$dreba->Rate ;
                    $uu['TaxAmount']=($dreba->Rate / 100 ) * $NET ;
                    $uu['TotalBill']=$NET + $TAM ;
                }

                ProductSales::create($uu);



                //7sab Taklft Mkhazn

                if($prooooo->P_Type != 'Service' and $prooooo->P_Type != 'Assembly'){

                    $Cost=$average->AverageCostGetUnit($Product[$i],$P_Code[$i],$StorePurch[$i],$Unit[$i]);

                    $Mkhazns=StoreCountSales::all();

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



                        $s['Total']=$Cost * $Qty[$i];
                        $s['Store']=$StorePurch[$i];
                        $s['Tax']=$PurchTax[$i];
                        StoreCountSales::create($s);
                    }else{


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

                        if(!empty($m)){

                            $newTot=$m->Total + ($Cost * $Qty[$i]) ;
                            StoreCountSales::where('id',$m->id)->update(['Total'=>$newTot]);

                        }else{

                            $s['Total']=$Cost * $Qty[$i];
                            $s['Store']=$StorePurch[$i];
                            $s['Tax']=$PurchTax[$i];
                            StoreCountSales::create($s);


                        }



                    }




                }elseif($prooooo->P_Type == 'Variable_Aggregate'){




                    $AVs=VAQty::where('Product',$Product[$i])->where('SubV',$SubVID[$i])->get();

                    foreach($AVs as $av){


                        $Mkhazns=StoreCountSales::all();

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


                            $Cost=$average->AverageCostGetUnit($av->ProductID,$av->VAProductID()->first()->Product_Code,$StorePurch[$i],$av->VAProductID()->first()->Unit);

                            $s['Total']=$Cost * $Qty[$i];
                            $s['Store']=$StorePurch[$i];
                            $s['Tax']=$PurchTax[$i];
                            StoreCountSales::create($s);
                        }else{


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

                            if(!empty($m)){

                                $Cost=$average->AverageCostGetUnit($av->ProductID,$av->VAProductID()->first()->Product_Code,$StorePurch[$i],$av->VAProductID()->first()->Unit);

                                $newTot=$m->Total + ($Cost * $Qty[$i]) ;
                                StoreCountSales::where('id',$m->id)->update(['Total'=>$newTot]);

                            }else{


                                $Cost=$average->AverageCostGetUnit($av->ProductID,$av->VAProductID()->first()->Product_Code,$StorePurch[$i],$av->VAProductID()->first()->Unit);

                                $s['Total']=$Cost * $Qty[$i];
                                $s['Store']=$StorePurch[$i];
                                $s['Tax']=$PurchTax[$i];
                                StoreCountSales::create($s);


                            }






                        }





                    }





                }else{



                    if($prooooo->P_Type == 'Service'){

                        $Mkhazns=StoreCountSales::all();
                        if(count($Mkhazns) == 0){

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

                        }else{
                            $m=StoreCountSales::where('Store',$StorePurch[$i])->first();

                            if(!empty($m)){

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

                            }else{

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


                            }

                        }
                    }else{


                        $Asembs=AssemblyProducts::where('p_id',$Product[$i])->get();

                        foreach($Asembs as $ass){


                            $Mkhazns=StoreCountSales::all();
                            $Cost=$average->AverageCostGetUnit($ass->Product,$ass->P_Code,$StorePurch[$i],$ass->Unit);

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

                                $s['Total']=$Cost * $Qty[$i];
                                $s['Store']=$StorePurch[$i];
                                $s['Tax']=$PurchTax[$i];
                                StoreCountSales::create($s);
                            }else{


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

                                if(!empty($m)){

                                    $newTot=$m->Total + ($Cost * $Qty[$i]) ;
                                    StoreCountSales::where('id',$m->id)->update(['Total'=>$newTot]);

                                }else{



                                    $s['Total']=$Cost * $Qty[$i];
                                    $s['Store']=$StorePurch[$i];
                                    $s['Tax']=$PurchTax[$i];
                                    StoreCountSales::create($s);


                                }






                            }






                        }




                    }




                }


                if($prooooo->P_Type == 'Assembly'){

                    $Asembs=AssemblyProducts::where('p_id',$Product[$i])->get();

                    foreach($Asembs as $ass){

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

                        if(!empty($Quantity)){

                            $prooooo=Products::find($ass->Product);
                            $unit=ProductUnits::where('Unit',$ass->Unit)->where('Product',$ass->Product)->first();
                            $plow=ProductUnits::where('Product',$ass->Product)->where('Def',1)->first();
                            $pp=ProductUnits::where('Product',$ass->Product)->where('Unit',$ass->Unit)->first();

                            $qq= $unit->Rate * ($Qty[$i] * $ass->Qty) ;
                            $newqty=$Quantity->Qty -  $qq ;


                            if($newqty < 0){
                                return 5;
                            }



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

                                $totCost=0;

                                $rr = ProductUnits::where("Unit",$ass->Unit)->where('Product',$ass->Product)->first();
                                $fifo=$this->FifoAvQtyDate($StorePurch[$i],$ass->Product,$ass->P_Code);

                                if(!empty($fifo)){

                                    if($fifo->Qty == 0){



                                        $NNQuntatity=$this->FindQty($fifo->Store,$fifo->Product,$fifo->P_Code,$fifo->id,$fifo->Purchases_Date);


                                        if($NNQuntatity == 0){


                                            $NNQuntatity=$this->FindQty($fifo->Store,$fifo->Product,$fifo->P_Code,$fifo->id,$fifo->Purchases_Date);


                                        }else{



                                            if($NNQuntatity >= ($Qty[$i] * $ass->Qty)){

                                                $totCost += $fifo->Cost_Price * $Qty[$i] ;

                                            }else{

                                                $res=($Qty[$i] * $ass->Qty) - $NNQuntatity ;


                                                $totCost += $fifo->Cost_Price * $NNQuntatity ;

                                                $ResdiualCost=$this->MoreThanQty($fifo->Store,$fifo->Product,$fifo->P_Code,$fifo->id,$fifo->Purchases_Date,$res);

                                                $totCost +=$ResdiualCost;

                                            }


                                        }



                                    }else{


                                        if($fifo->Qty >= ($Qty[$i] * $ass->Qty)){

                                            $totCost += $fifo->Cost_Price * ($Qty[$i] * $ass->Qty) ;

                                        }else{

                                            $res=($Qty[$i] * $ass->Qty) - $fifo->Qty ;


                                            $totCost += $fifo->Cost_Price * $fifo->Qty ;

                                            $ResdiualCost=$this->MoreThanQty($fifo->Store,$fifo->Product,$fifo->P_Code,$fifo->id,$fifo->Purchases_Date,$res);

                                            $totCost +=$ResdiualCost;

                                        }



                                    }


                                }

                                $newQQty= $unit->Rate * ($Qty[$i] * $ass->Qty) ;
                                $CostTotalSale=$totCost;

                                $in=0;
                                $out=$CostTotalSale;

                                $current=$newqty *  $totCost;




                                $cur= $totCost ;
                                $ty= $totCost / $newQQty;

                                if($event->requests['Status'] == 1) {
                                    ProductsQty::where('id', $Quantity->id)->update(['Qty' => $newqty, 'Price' => $ty, 'TotalCost' => $cur]);
                                }



                            }else{


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


                                $newQQty= $unit->Rate * $Qty[$i] ;
                                $CostTotalSale=$ty ;
                                $in=0;
                                $out=$CostTotalSale;


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

                                $cur=$newqty * ($ty / $unit->Rate) ;
                                if($event->requests['Status'] == 1) {
                                    ProductsQty::where('id', $Quantity->id)->update(['Qty' => $newqty, 'Price' => $ty, 'TotalCost' => $cur]);
                                }

                            }

                            if($event->requests['Status'] == 1) {


                                //Products Moves
                                $move = [

                                    'Date' => $event->requests['Date'],
                                    'Type' => 'مبيعات',
                                    'TypeEn' => 'Sales',
                                    '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' => $ass->P_Ar_Name,
                                    'P_En_Name' => $ass->P_En_Name,
                                    'P_Code' => $ass->P_Code,
                                    'Unit' => $ass->Unit,
                                    'Qty' => $Qty[$i] * $ass->Qty,
                                    'Group' => $prooooo->Group,
                                    'Store' => $StorePurch[$i],
                                    'Product' => $ass->Product,
                                    'V1' =>null,
                                    'V2' => null,
                                    'Brand' => $prooooo->Brand,
                                    'Safe' => $event->requests['Safe'],
                                    'Branch' => $Sor->Branch,
                                    'SalePrice' => $Price[$i],
                                    'ProductPrice' => $pp->Price,
                                    'Delegate' => $event->requests['Delegate'],
                                    'Payment_Method' => $event->requests['Payment_Method'],
                                    'User' => $user,

                                ];

                                $this->ProductMoves($move);


                            }

                        }


                        if($event->requests['Status'] == 1) {

                            //Expire Date
                            if (!empty($Exp_Date[$i])) {
                                $unit = ProductUnits::where('Unit', $ass->Unit)->where('Product', $ass->Product)->first();

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


                                $EXPO = ExpireDateQty::find($Exp_Date[$i]);
                                $NewExpQty = $EXPO->Qty - $qq;

                                if($NewExpQty < 0){
                                    return 5;
                                }
                                ExpireDateQty::where('id', $Exp_Date[$i])->update(['Qty' => $NewExpQty]);


                            }

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

                                $fifo=$this->FifoAvQtyDate($StorePurch[$i],$ass->Product, $ass->P_Code);


                                if (!empty($fifo)) {

                                    if ($fifo->Qty >= ($Qty[$i] * $ass->Qty)) {


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

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

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

                                        if($newqty < 0){
                                            return 5;
                                        }
                                        FifoQty::where('id', $fifo->id)->update(['Qty' => $newqty]);


                                        $fifQty['Sales_Qty'] = ($Qty[$i] * $ass->Qty);
                                        $fifQty['Sales_ID'] = $ID;
                                        $fifQty['Fifo_ID'] = $fifo->id;
                                        $fifQty['Store'] = $fifo->Store;
                                        $fifQty['Product'] = $fifo->Product;
                                        $fifQty['Cost_Price'] = $fifo->Cost_Price;
                                        $fifQty['Purchases_Date'] = $fifo->Purchases_Date;

                                        SalesFifoQty::create($fifQty);


                                    } else {


                                        $resdiualQty = ($Qty[$i] * $ass->Qty) - $fifo->Qty;

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

                                        $qq = $unit->Rate * ($fifo->Qty * $ass->Qty);

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

                                        if($newqty < 0){
                                            return 5;
                                        }

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


                                        $fifQty['Sales_Qty'] = $fifo->Qty;
                                        $fifQty['Sales_ID'] = $ID;
                                        $fifQty['Fifo_ID'] = $fifo->id;
                                        $fifQty['Store'] = $fifo->Store;
                                        $fifQty['Product'] = $fifo->Product;
                                        $fifQty['Cost_Price'] = $fifo->Cost_Price;
                                        $fifQty['Purchases_Date'] = $fifo->Purchases_Date;

                                        SalesFifoQty::create($fifQty);

                                        $ResdiualCost = $this->FifoStoreAssemblyQty($fifo->Store, $fifo->Product, $fifo->P_Code, $fifo->id, $fifo->Purchases_Date, $resdiualQty, $ass->Unit, $ass->Qty, $ID);


                                    }


                                }


                            }
                        }


                    }


                }elseif($prooooo->P_Type == 'Variable_Aggregate'){



                    $AVs=VAQty::where('Product',$Product[$i])->where('SubV',$SubVID[$i])->get();


                    foreach($AVs as $av){

                        $Quantity=$this->ProAvQties($StorePurch[$i],$av->ProductID,$av->VAProductID()->first()->Product_Code);

                        if(!empty($Quantity)){


                            $unit=ProductUnits::where('Unit',$av->VAProductID()->first()->Unit)->where('Product',$av->ProductID)->first();
                            $qq= $unit->Rate * ($Qty[$i] * $av->Qty) ;
                            $newqty=$Quantity->Qty -  $qq ;

                            if($newqty < 0){
                                return 5;
                            }


                            $prooooo=Products::find($av->ProductID);

                            $plow=ProductUnits::where('Product',$av->ProductID)->where('Def',1)->first();
                            $pp=ProductUnits::where('Product',$av->ProductID)->where('Unit',$av->VAProductID()->first()->Unit)->first();


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

                                $totCost=0;

                                $rr = ProductUnits::where("Unit",$av->VAProductID()->first()->Unit)->where('Product',$av->ProductID)->first();
                                $fifo=$this->FifoAvQtyDate($StorePurch[$i],$av->ProductID,$av->VAProductID()->first()->Product_Code);

                                if(!empty($fifo)){

                                    if($fifo->Qty == 0){



                                        $NNQuntatity=$this->FindQty($fifo->Store,$fifo->Product,$fifo->P_Code,$fifo->id,$fifo->Purchases_Date);


                                        if($NNQuntatity == 0){


                                            $NNQuntatity=$this->FindQty($fifo->Store,$fifo->Product,$fifo->P_Code,$fifo->id,$fifo->Purchases_Date);


                                        }else{



                                            if($NNQuntatity >= ($Qty[$i] * $av->Qty)){

                                                $totCost += $fifo->Cost_Price * $Qty[$i] ;

                                            }else{

                                                $res=($Qty[$i] * $av->Qty) - $NNQuntatity ;


                                                $totCost += $fifo->Cost_Price * $NNQuntatity ;

                                                $ResdiualCost=$this->MoreThanQty($fifo->Store,$fifo->Product,$fifo->P_Code,$fifo->id,$fifo->Purchases_Date,$res);

                                                $totCost +=$ResdiualCost;

                                            }


                                        }



                                    }else{


                                        if($fifo->Qty >= ($Qty[$i] * $av->Qty)){

                                            $totCost += $fifo->Cost_Price * ($Qty[$i] * $av->Qty) ;

                                        }else{

                                            $res=($Qty[$i] * $av->Qty) - $fifo->Qty ;


                                            $totCost += $fifo->Cost_Price * $fifo->Qty ;

                                            $ResdiualCost=$this->MoreThanQty($fifo->Store,$fifo->Product,$fifo->P_Code,$fifo->id,$fifo->Purchases_Date,$res);

                                            $totCost +=$ResdiualCost;

                                        }



                                    }


                                }

                                $newQQty= $unit->Rate * ($Qty[$i] * $av->Qty) ;
                                $CostTotalSale=$totCost;

                                $in=0;
                                $out=$CostTotalSale;

                                $current=$newqty *  $totCost;

                                $cur= $totCost ;
                                $ty= $totCost / $newQQty;

                                if($event->requests['Status'] == 1) {
                                    ProductsQty::where('id', $Quantity->id)->update(['Qty' => $newqty, 'Price' => $ty, 'TotalCost' => $cur]);
                                }



                            }else{


                                $ty=$average->AverageCostGetUnit($av->ProductID,$av->VAProductID()->first()->Product_Code,$StorePurch[$i],$av->VAProductID()->first()->Unit);


                                $newQQty= $unit->Rate * ($Qty[$i] * $av->Qty) ;
                                $CostTotalSale=$ty ;
                                $in=0;
                                $out=$CostTotalSale;


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

                                $cur=$newqty * ($ty / $unit->Rate) ;
                                if($event->requests['Status'] == 1) {
                                    ProductsQty::where('id', $Quantity->id)->update(['Qty' => $newqty, 'Price' => $ty, 'TotalCost' => $cur]);
                                }

                            }

                            if($event->requests['Status'] == 1) {


                                //Products Moves
                                $move = [

                                    'Date' => $event->requests['Date'],
                                    'Type' => 'مبيعات',
                                    'TypeEn' => 'Sales',
                                    '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' => $av->ProductID()->first()->P_Ar_Name,
                                    'P_En_Name' => $av->ProductID()->first()->P_En_Name,
                                    'P_Code' => $av->VAProductID()->first()->Product_Code,
                                    'Unit' => $av->VAProductID()->first()->Unit,
                                    'Qty' => $Qty[$i] * $av->Qty,
                                    'Group' => $prooooo->Group,
                                    'Store' => $StorePurch[$i],
                                    'Product' => $av->ProductID,
                                    'V1' =>null,
                                    'V2' => null,
                                    'Brand' => $prooooo->Brand,
                                    'Safe' => $event->requests['Safe'],
                                    'Branch' => $Sor->Branch,
                                    'SalePrice' => $Price[$i],
                                    'ProductPrice' => $pp->Price,
                                    'Delegate' => $event->requests['Delegate'],
                                    'Payment_Method' => $event->requests['Payment_Method'],
                                    'User' => auth()->guard('admin')->user()->id,

                                ];

                                $this->ProductMoves($move);


                            }

                            if($event->requests['Status'] == 1) {

                                //Expire Date
                                if (!empty($Exp_Date[$i])) {
                                    $unit = ProductUnits::where('Unit', $av->VAProductID()->first()->Unit)->where('Product', $av->ProductID)->first();

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


                                    $EXPO = ExpireDateQty::find($Exp_Date[$i]);
                                    $NewExpQty = $EXPO->Qty - $qq;

                                    if($NewExpQty < 0){
                                        return 5;
                                    }
                                    ExpireDateQty::where('id', $Exp_Date[$i])->update(['Qty' => $NewExpQty]);


                                }

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

                                    $fifo=$this->FifoAvQtyDate($StorePurch[$i],$av->ProductID, $av->VAProductID()->first()->Product_Code);


                                    if (!empty($fifo)) {

                                        if ($fifo->Qty >= ($Qty[$i] * $av->Qty)) {


                                            $unit = ProductUnits::where('Unit', $av->VAProductID()->first()->Unit)->where('Product', $av->ProductID)->first();

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

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

                                            if($newqty < 0){
                                                return 5;
                                            }
                                            FifoQty::where('id', $fifo->id)->update(['Qty' => $newqty]);


                                            $fifQty['Sales_Qty'] = ($Qty[$i] * $av->Qty);
                                            $fifQty['Sales_ID'] = $ID;
                                            $fifQty['Fifo_ID'] = $fifo->id;
                                            $fifQty['Store'] = $fifo->Store;
                                            $fifQty['Product'] = $fifo->Product;
                                            $fifQty['Cost_Price'] = $fifo->Cost_Price;
                                            $fifQty['Purchases_Date'] = $fifo->Purchases_Date;

                                            SalesFifoQty::create($fifQty);


                                        } else {


                                            $resdiualQty = ($Qty[$i] * $av->Qty) - $fifo->Qty;

                                            $unit = ProductUnits::where('Unit', $av->VAProductID()->first()->Unit)->where('Product', $av->ProductID)->first();

                                            $qq = $unit->Rate * ($fifo->Qty * $av->Qty);

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

                                            if($newqty < 0){
                                                return 5;
                                            }

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


                                            $fifQty['Sales_Qty'] = $fifo->Qty;
                                            $fifQty['Sales_ID'] = $ID;
                                            $fifQty['Fifo_ID'] = $fifo->id;
                                            $fifQty['Store'] = $fifo->Store;
                                            $fifQty['Product'] = $fifo->Product;
                                            $fifQty['Cost_Price'] = $fifo->Cost_Price;
                                            $fifQty['Purchases_Date'] = $fifo->Purchases_Date;

                                            SalesFifoQty::create($fifQty);

                                            $ResdiualCost = $this->FifoStoreAssemblyQty($fifo->Store, $fifo->Product, $fifo->P_Code, $fifo->id, $fifo->Purchases_Date, $resdiualQty, $av->VAProductID()->first()->Unit, $av->Qty, $ID);


                                        }


                                    }


                                }
                            }


                        }



                    }






                }elseif($prooooo->P_Type != 'Service' and $prooooo->P_Type != 'Subscribe'){

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

                    if(!empty($Quantity)){
                        $unit=ProductUnits::where('Unit',$Unit[$i])->where('Product',$Product[$i])->first();

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

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

                        if($newqty < 0){
                            return 5 ;
                        }



                        //Products Qties
                        if($def->Cost_Price == 2){
                            $totCost=0;

                            $fifo=$this->FifoAvQtyDate($StorePurch[$i],$Product[$i],$P_Code[$i]);

                            if(!empty($fifo)){

                                if($fifo->Qty == 0){

                                    $NNQuntatity=$this->FindQty($fifo->Store,$fifo->Product,$fifo->P_Code,$fifo->id,$fifo->Purchases_Date);


                                    if($NNQuntatity == 0){


                                        $NNQuntatity=$this->FindQty($fifo->Store,$fifo->Product,$fifo->P_Code,$fifo->id,$fifo->Purchases_Date);


                                    }else{



                                        if($NNQuntatity >= $Qty[$i]){

                                            $totCost += $fifo->Cost_Price * $Qty[$i] ;

                                        }else{

                                            $res=$Qty[$i] - $NNQuntatity ;


                                            $totCost += $fifo->Cost_Price * $NNQuntatity ;

                                            $ResdiualCost=$this->MoreThanQty($fifo->Store,$fifo->Product,$fifo->P_Code,$fifo->id,$fifo->Purchases_Date,$res);

                                            $totCost +=$ResdiualCost;

                                        }


                                    }



                                }else{


                                    if($fifo->Qty >= $Qty[$i]){

                                        $totCost += $fifo->Cost_Price * $Qty[$i] ;

                                    }else{

                                        $res=$Qty[$i] - $fifo->Qty ;


                                        $totCost += $fifo->Cost_Price * $fifo->Qty ;

                                        $ResdiualCost=$this->MoreThanQty($fifo->Store,$fifo->Product,$fifo->P_Code,$fifo->id,$fifo->Purchases_Date,$res);

                                        $totCost +=$ResdiualCost;

                                    }



                                }


                            }

                            $newQQty= $unit->Rate * $Qty[$i] ;
                            $CostTotalSale=$totCost;

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



                            $in=0;
                            $out=$CostTotalSale;



                            $current=$newqty *  $totCost;


                            $cur= $totCost ;

                            $ty=$cur / $newQQty ;
                            if($event->requests['Status'] == 1) {
                                ProductsQty::where('id', $Quantity->id)->update(['Qty' => $newqty, 'Price' => $ty, 'TotalCost' => $cur]);
                            }



                        }else{


                            $newQQty= $unit->Rate * $Qty[$i] ;
                            $ty=$average->AverageCostGetUnit($Product[$i],$P_Code[$i],$StorePurch[$i],$Unit[$i]);
                            $CostTotalSale=$ty ;
                            $prooooo=Products::findOrFail($Product[$i]);
                            $in=0;
                            $out=$CostTotalSale;
                            $current= $newqty *  ($ty / $unit->Rate);
                            $cur=$newqty * ($ty / $unit->Rate) ;

                            if($event->requests['Status'] == 1) {
                                ProductsQty::where('id', $Quantity->id)->update(['Qty' => $newqty, 'Price' => $ty, 'TotalCost' => $cur]);
                            }
                        }



                        if($event->requests['Status'] == 1) {
                            //Products Moves
                            $move = [

                                'Date' => $event->requests['Date'],
                                'Type' => 'مبيعات',
                                'TypeEn' => 'Sales',
                                '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' => $Qty[$i],
                                'Group' => $prooooo->Group,
                                'Store' => $StorePurch[$i],
                                'Product' => $Product[$i],
                                'V1' => $VOne[$i],
                                'V2' => $VTwo[$i],
                                'Brand' => $prooooo->Brand,
                                'Safe' => $event->requests['Safe'],
                                'Branch' => $Sor->Branch,
                                'SalePrice' => $Price[$i],
                                'ProductPrice' => $pp->Price,
                                'Delegate' => $event->requests['Delegate'],
                                'Payment_Method' => $event->requests['Payment_Method'],
                                'User' => $user,

                            ];

                            $this->ProductMoves($move);
                        }

                    }

                    if($event->requests['Status'] == 1) {
                        if (!empty($Exp_Date[$i])) {
                            $unit = ProductUnits::where('Unit', $Unit[$i])->where('Product', $Product[$i])->first();

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



                            $EXPO = ExpireDateQty::find($Exp_Date[$i]);
                            $NewExpQty = $EXPO->Qty - $qq;


                            if($NewExpQty < 0){

                                return 5;
                            }


                            ExpireDateQty::where('id', $Exp_Date[$i])->update(['Qty' => $NewExpQty]);


                        }

                        //Fifo

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

                            $fifo=$this->FifoAvQtyDate($StorePurch[$i] ,$Product[$i],$P_Code[$i]);


                            if (!empty($fifo)) {

                                if ($fifo->Qty >= $Qty[$i]) {


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

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

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

                                    if($newqty < 0){
                                        return 5;
                                    }


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


                                    $fifQty['Sales_Qty'] = $Qty[$i];
                                    $fifQty['Sales_ID'] = $ID;
                                    $fifQty['Fifo_ID'] = $fifo->id;
                                    $fifQty['Store'] = $fifo->Store;
                                    $fifQty['Product'] = $fifo->Product;
                                    $fifQty['Cost_Price'] = $fifo->Cost_Price;
                                    $fifQty['Purchases_Date'] = $fifo->Purchases_Date;

                                    SalesFifoQty::create($fifQty);


                                } else {


                                    $resdiualQty = $Qty[$i] - $fifo->Qty;

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

                                    $qq = $unit->Rate * $fifo->Qty;

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

                                    if($newqty < 0){
                                        return 5;
                                    }


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


                                    $fifQty['Sales_Qty'] = $fifo->Qty;
                                    $fifQty['Sales_ID'] = $ID;
                                    $fifQty['Fifo_ID'] = $fifo->id;
                                    $fifQty['Store'] = $fifo->Store;
                                    $fifQty['Product'] = $fifo->Product;
                                    $fifQty['Cost_Price'] = $fifo->Cost_Price;
                                    $fifQty['Purchases_Date'] = $fifo->Purchases_Date;

                                    SalesFifoQty::create($fifQty);


                                    $ResdiualCost = $this->FifoStoreQty($fifo->Store, $fifo->Product, $fifo->P_Code, $fifo->id, $fifo->Purchases_Date, $resdiualQty, $Unit[$i], $ID);


                                }


                            }


                        }

                    }



                }


            }
        }



        //lw el be3a qst
        if($event->requests['Payment_Method'] == 'Installment'){


            $installmentsID = DB::table('installments')->insertGetId(
                array(

                    'presenter' => $event->requests['presenter'],
                    'annual_interest' => $event->requests['annual_interest'],
                    'monthly_installment' => $event->requests['monthly_installment'],
                    'Years_Number' => $event->requests['Years_Number'],
                    'total' => $event->requests['total'],
                    'installment_Num' => $event->requests['installment_Num'],
                    'Date_First_installment' => $event->requests['Date_First_installment'],
                    'Residual' => $event->requests['total'] - $event->requests['presenter'],
                    'Status' => 0,
                    'Client' => $event->requests['Client'],
                    'Sales' => $ID,


                )
            );

            $resd= $event->requests['total'] - $event->requests['presenter'] ;
            $Precent= $event->requests['annual_interest'] / 100 ;

            $resdPrecent= $resd * $Precent ;

            $resdYears = $resdPrecent * $event->requests['Years_Number'] ;

            $resdTotal= $resd + $resdYears ;

            $monthly = $event->requests['Years_Number'] * 12 ;

            $valueMonth = $resdTotal / $monthly ;

            $date=$event->requests['Date_First_installment'];
            for($i=0 ; $i < $monthly ; $i++){

                $inst['Date']=$date;
                $inst['Value']=$valueMonth;
                $inst['Status']=0;
                $inst['Client']=$event->requests['Client'];
                $inst['Install']=$installmentsID;
                InstallmentDates::create($inst);


                $dataEvent=[

                    'start_date'=>$date,
                    'end_date'=>$date,
                    'event_name_ar'=>'قسط عميل',
                    'event_name_en'=>'Client Installment',
                    'type'=>'المبيعات',
                    'type_id'=>null,
                    'type_code'=>$Bill->Code,
                    'emp'=>null,
                    'client'=>$event->requests['Client'],
                    'product'=>null,
                    'customer'=>null,

                ];
                $this->CreateEvent($dataEvent);


                $date = date('Y-m-d',strtotime('+31 days',strtotime($date))) ;

            }
        }



        //Stores Moves
        $totpri=($event->requests['Total_Taxes'] +  $event->requests['Total_Price'] + $event->requests['ProfitTax']) -  ($event->requests['Total_Discount'] + $event->requests['DiscountBill']);

        $dataStMove=[

            'Date'=>date('Y-m-d'),
            'Code'=>$Bill->Code ,
            'Time'=>date("h:i:s a", time()),
            'Branch'=>$Sor->Branch,
            'Store'=>$event->requests['Store'],
            'Safe'=>$event->requests['Safe'],
            'Type'=>'مبيعات',
            'TypeEn'=>'Sales',
            'Cost_Center'=>$event->requests['Cost_Center'],
            'User'=>$user,
            'Coin'=>$event->requests['Coin'],
            'Note'=>$event->requests['Note'],
            'Total_Qty'=>$event->requests['Total_Qty'],
            'Total_Price'=>$totpri,
            'Account'=>$event->requests['Client'],
            'Ship'=>$event->requests['Ship'],
            'ID'=>$event->ID,

        ];

        $this->StoresMoves($dataStMove);



    }
}
