<?php


namespace App\Listeners\Manufacturing;

use App\Events\ManyfacturingEvent;
use App\Models\AcccountingManual;
use App\Models\ExecutingReceiving;
use App\Models\FifoQty;
use App\Models\GeneralDaily;
use App\Models\IncomManufacturingModel;
use App\Models\JournalizingDetails;
use App\Models\ManufacturingModel;
use App\Models\ManuStoreCount;
use App\Models\OutcomManufacturingModel;
use App\Models\ProductMoves;
use App\Models\Products;
use App\Models\ProductsExecutingReceiving;
use App\Models\ProductsPurchases;
use App\Models\ProductsQty;
use App\Models\ProductsStartPeriods;
use App\Models\ProductsStoresTransfers;
use App\Models\ProductUnits;
use App\Models\Stores;
use App\Models\StoresDefaultData;
use App\Models\StoresMoves;
use App\Traits\GeneralTrait;
use App\Models\Journalizing;
use Illuminate\Support\Facades\DB;
use App\Services\Average;
class ManyfacturingListener
{


    use GeneralTrait;

    public function __construct()
    {

    }


    public function handle(ManyfacturingEvent $event)
    {

        $ID=$event->ID;
        $Bill=ExecutingReceiving::findOrFail($ID);
        $average=new Average();
        $def=StoresDefaultData::orderBy('id','desc')->first();

        ManuStoreCount::truncate();
        $CodeT=ExecutingReceiving::findOrFail($ID)->Code;
        $ins=IncomManufacturingModel::where('Model',$event->requests['Model'])->get();
        $out=OutcomManufacturingModel::where('Model',$event->requests['Model'])->first();
        $model=ManufacturingModel::find($event->requests['Model']);
        $Tot=$event->requests['Totall'] * $event->requests['Qtyy'];

        // Outcome
        if(!empty($event->requests['Unit'])){
            $Product_Code=$event->requests['Product_Code'];
            $P_Ar_Name=$event->requests['P_Ar_Name'];
            $P_En_Name=$event->requests['P_En_Name'];
            $Qty=$event->requests['Qty'];
            $Price=$event->requests['Price'];
            $Product=$event->requests['Product'];
            $Store=$event->requests['Store'];
            $Unit=$event->requests['Unit'];

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


                $uu['Product_Code']=$Product_Code[$i];
                $uu['P_Ar_Name']=$P_Ar_Name[$i];
                $uu['P_En_Name']=$P_En_Name[$i];
                $uu['Qty']=$Qty[$i];
                $uu['Price']=$Price[$i];
                $uu['Total']=$Price[$i];
                $uu['Store']=$Store[$i];
                $uu['Product']=$Product[$i];
                $uu['Unit']=$Unit[$i];
                $uu['type']=1;
                $uu['Executing']=$ID;
                ProductsExecutingReceiving::create($uu);

                $unit=ProductUnits::where('Unit',$Unit[$i])->where('Product',$Product[$i])->first();
                $Quantity=$this->ProAvQties($Store[$i],$Product[$i],$Product_Code[$i]);

                if(!empty($Quantity)){

                    $qq= $unit->Rate * $event->requests['Qtyy'] ;
                    $newqty=$Quantity->Qty +  $qq ;

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

                    $ty=$average->AverageCost($Tot,$qq,$Product[$i],$Product_Code[$i],$Store[$i],$event->requests['Date'],$event->requests['Totall']);

                    $lastOperation=ProductMoves::latest('id')->where('Product',$Product[$i])->where('Store',$Store[$i])->first();

                    $in=$Tot;
                    $out=0;
                    if(!empty($lastOperation)){

                            $current=$lastOperation->CostCurrent + $Tot;

                    }else{
                        $current= $Tot;
                    }

                    $cur=$newqty * ($ty / $unit->Rate) ;
                    ProductsQty::where('id',$Quantity->id)->update(['Qty'=>$newqty,'Price'=>$ty , 'TotalCost'=>$cur]);


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

                    $move['Date']=$event->requests['Date'];
                    $move['Type']='مخرجات تصنيع';
                    $move['TypeEn']='Manufacturing Outcome';
                    $move['Bill_Num']=$CodeT;
                    $move['Incom']=$qq;
                    $move['Outcom']=0;
                    $move['Current']=$newqty;
                    $move['CostIn']=number_format((float)abs($in), 2, '.', '');
                    $move['CostOut']=number_format((float)abs($out), 2, '.', '');
                    $move['CostCurrent']=number_format((float)abs($current), 2, '.', '');
                    $move['P_Ar_Name']=$P_Ar_Name[$i];
                    $move['P_En_Name']=$P_En_Name[$i];
                    $move['P_Code']=$Product_Code[$i];
                    $move['Unit']=$Unit[$i];
                    $move['QTY']=$event->requests['Qtyy'];
                    $move['Group']=$prooooo->Group;
                    $move['Store']=$Store[$i];
                    $move['Product']=$Product[$i];
                    $move['V1']=null;
                    $move['V2']=null;
                    $move['User']=auth()->guard('admin')->user()->id;
                    $move['Brand']=$prooooo->Brand;
                    $move['Safe']=null;
                    $move['Branch']=$Sro->Branch;
                    $move['SalePrice']=null;
                    $move['ProductPrice']=null;
                    ProductMoves::create($move);

                }else{


                    $pp=ProductUnits::where('Product',$Product[$i])->where('Unit',$Unit[$i])->first();
                    $plow=ProductUnits::where('Product',$Product[$i])->where('Rate',1)->first();
                    $id_store = DB::table('products_stores')->insertGetId(

                        array(

                            'P_Ar_Name' => $P_Ar_Name[$i],
                            'P_En_Name' => $P_En_Name[$i],
                            'P_Code' =>   $Product_Code[$i],
                            'Exp_Date' => null,
                            'Product' => $Product[$i],
                            'Store' =>$Store[$i],
                            'V1' => null,
                            'V2' => null,
                            'V_Name' => null,
                            'VV_Name' => null,

                        )
                    );

                    $coco=array();
                    $CodesPrds=ProductUnits::where('Product',$Product[$i])->select('Barcode')->get();
                    foreach($CodesPrds as $cco){


                        array_push($coco,$cco->Barcode);

                    }

                    $pqty['P_Code']=$coco[0];

                    if(!empty($coco[1])){
                        $pqty['PP_Code']=$coco[1];
                    }else{
                        $pqty['PP_Code']=null;
                    }

                    if(!empty($coco[2])){
                        $pqty['PPP_Code']=$coco[2];
                    }else{
                        $pqty['PPP_Code']=null;
                    }

                    if(!empty($coco[3])){
                        $pqty['PPPP_Code']=$coco[3];
                    }else{
                        $pqty['PPPP_Code']=null;
                    }

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

                    $pqty['P_Ar_Name']=$P_Ar_Name[$i];
                    $pqty['P_En_Name']=$P_En_Name[$i];
                    $pqty['Qty']=$event->requests['Qtyy'] * $pp->Rate;
                    $pqty['Price']=($Price[$i] / $pp->Rate);
                    $pqty['TotalCost']=($Price[$i] / $pp->Rate) * ($event->requests['Qtyy'] * $pp->Rate);
                    $pqty['Pro_Stores']=$id_store;
                    $pqty['Store']=$Store[$i];
                    $pqty['Unit']=$Unit[$i];
                    $pqty['Low_Unit']=$plow->Unit;
                    $pqty['Product']=$Product[$i];
                    $pqty['V1']=null;
                    $pqty['V2']=null;
                    $pqty['V_Name']=null;
                    $pqty['VV_Name']=null;
                    $pqty['SearchCode1']=$prooooo->SearchCode1;
                    $pqty['SearchCode2']=$prooooo->SearchCode2;
                    $pqty['Group']=$prooooo->Group;
                    $pqty['Brand']=$prooooo->Brand;
                    $pqty['Branch']=$proooooStore->Branch;
                    ProductsQty::create($pqty);



                    $newQQty=$unit->Rate * $event->requests['Qtyy'];

                    $ty=$average->AverageCost($Tot,$newQQty,$Product[$i],$Product_Code[$i],$Store[$i],$event->requests['Date'],$event->requests['Totall']);

                    $lastOperation=ProductMoves::latest('id')->where('Product',$Product[$i])->where('Store',$Store[$i])->first();


                    $in=$Tot;
                    $out=0;
                    if(!empty($lastOperation)){

                            $current=$lastOperation->CostCurrent + $Tot;

                    }else{
                        $current= $Tot;
                    }



                    $prooooo=Products::find($Product[$i]);
                    $Sro=Stores::find($Store[$i]);
                    $move['Date']=$event->requests['Date'];
                    $move['Type']='مخرجات تصنيع';
                    $move['TypeEn']='Manufacturing Outcome';
                    $move['Bill_Num']=$CodeT;
                    $move['Incom']=$event->requests['Qtyy'] * $pp->Rate;
                    $move['Outcom']=0;
                    $move['Current']=$event->requests['Qtyy'] * $pp->Rate;
                    $move['CostIn']=number_format((float)abs($in), 2, '.', '');
                    $move['CostOut']=number_format((float)abs($out), 2, '.', '');
                    $move['CostCurrent']=number_format((float)abs($current), 2, '.', '');
                    $move['P_Ar_Name']=$P_Ar_Name[$i];
                    $move['P_En_Name']=$P_En_Name[$i];
                    $move['P_Code']=$Product_Code[$i];
                    $move['Unit']=$Unit[$i];
                    $move['QTY']=$event->requests['Qtyy'];
                    $move['Group']=$prooooo->Group;
                    $move['Store']=$Store[$i];
                    $move['Product']=$Product[$i];
                    $move['V1']=null;
                    $move['V2']=null;
                    $move['User']=auth()->guard('admin')->user()->id;
                    $move['Brand']=$prooooo->Brand;
                    $move['Safe']=null;
                    $move['Branch']=$Sro->Branch;
                    $move['SalePrice']=null;
                    $move['ProductPrice']=null;
                    ProductMoves::create($move);



                }



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

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

                    if(!empty($fifo)){

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

                        $qq= $unit->Rate * $event->requests['Qtyy'] ;

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

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

                    }else{



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

                        $pqty['P_Ar_Name']=$P_Ar_Name[$i];
                        $pqty['Exp_Date']=null;
                        $pqty['P_En_Name']=$P_En_Name[$i];
                        $pqty['Qty']=$event->requests['Qtyy'] * $pp->Rate;
                        $pqty['Original_Qty']=$event->requests['Qtyy'] * $pp->Rate;
                        $pqty['Cost_Price']=$Price[$i];
                        $pqty['Store']=$Store[$i];
                        $pqty['Unit']=$Unit[$i];
                        $pqty['Low_Unit']=$plow->Unit;
                        $pqty['Product']=$Product[$i];
                        $pqty['SearchCode1']=$prooooo->SearchCode1;
                        $pqty['SearchCode2']=$prooooo->SearchCode2;
                        $pqty['V1']=null;
                        $pqty['V2']=null;
                        $pqty['V_Name']=null;
                        $pqty['VV_Name']=null;
                        $pqty['P_Code']=$Product_Code[$i];
                        $pqty['Group']=$prooooo->Group;
                        $pqty['Brand']=$prooooo->Brand;
                        $pqty['Branch']=$proooooStore->Branch;
                        $pqty['Purchases_Date']=request('Date');
                        FifoQty::create($pqty);




                    }

                }




            }


        }


        // Income
        if(!empty($event->requests['UnitI'])){

            $Product_CodeI= $event->requests['Product_CodeI'] ;
            $P_Ar_NameI= $event->requests['P_Ar_NameI'] ;
            $P_En_NameI= $event->requests['P_En_NameI'] ;
            $QtyI= $event->requests['QtyHide'] ;
            $Dep= $event->requests['QtyI'] ;
            $PriceI= $event->requests['PriceI'] ;
            $ProductI= $event->requests['ProductI'] ;
            $StoreI= $event->requests['StoreI'] ;
            $UnitI= $event->requests['UnitI'] ;
            $INSTORE= $event->requests['inStore'] ;


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

                $uuz['Product_Code']=$Product_CodeI[$i];
                $uuz['P_Ar_Name']=$P_Ar_NameI[$i];
                $uuz['P_En_Name']=$P_En_NameI[$i];
                $uuz['Qty']=$QtyI[$i];
                $uuz['Dep']=$Dep[$i];
                $uuz['Price']=$PriceI[$i];
                $uuz['Total']=$PriceI[$i];
                $uuz['Store']=$StoreI[$i];
                $uuz['Product']=$ProductI[$i];
                $uuz['Unit']=$UnitI[$i];
                $uu['type']=0;
                $uuz['Executing']=$ID;
                ProductsExecutingReceiving::create($uuz);


                //Damaged
                if($INSTORE[$i] == 1){

                    $dd='0'.$Product_CodeI[$i];
                    $Quantity=$this->ProAvQtiesDamaged($StoreI[$i],$ProductI[$i],$dd);
                    $pp=ProductUnits::where('Product',$ProductI[$i])->where('Unit',$UnitI[$i])->first();

                    if(!empty($Quantity)){

                        $xx= $Quantity->Qty + ($QtyI[$i] * $pp->Rate)  ;
                        ProductsQty::where('id',$Quantity->id)->update(['Qty'=>$xx,'Price'=>0 , 'TotalCost'=>0]);

                        $prooooo=Products::find($ProductI[$i]);
                        $Sro=Stores::find($StoreI[$i]);
                        $move['Date']=$event->requests['Date'];
                        $move['Type']='هوالك';
                        $move['TypeEn']='Perished';
                        $move['Bill_Num']=$CodeT;
                        $move['Incom']=$QtyI[$i] ;
                        $move['Outcom']=0;
                        $move['Current']=$xx;
                        $move['CostIn']=0;
                        $move['CostOut']=0;
                        $move['CostCurrent']=0;
                        $move['P_Ar_Name']=$P_Ar_NameI[$i];
                        $move['P_En_Name']=$P_En_NameI[$i];
                        $move['P_Code']=$Product_CodeI[$i];
                        $move['Unit']=$UnitI[$i];
                        $move['QTY']=$QtyI[$i];
                        $move['Group']=$prooooo->Group;
                        $move['Store']=$StoreI[$i];
                        $move['Product']=$ProductI[$i];
                        $move['V1']=null;
                        $move['V2']=null;
                        $move['User']=auth()->guard('admin')->user()->id;
                        $move['Brand']=$prooooo->Brand;
                        $move['Safe']=null;
                        $move['Branch']=$Sro->Branch;
                        $move['SalePrice']=null;
                        $move['ProductPrice']=null;
                        ProductMoves::create($move);


                    }else{


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


                        $id_store = DB::table('products_stores')->insertGetId(
                            array(

                                'P_Ar_Name' => $prooooo->P_Ar_Name.'(هالك)',
                                'P_En_Name' => $prooooo->P_En_Name.'(Damage)',
                                'P_Code' =>   '0'.$prooooo->Barcode,
                                'Exp_Date' => null,
                                'Product' => $prooooo->Product,
                                'Store' =>$StoreI[$i],
                                'V1' => null,
                                'V2' => null,
                                'V_Name' => null,
                                'VV_Name' => null,

                            )
                        );

                        $Newprooooo=Products::find($prooooo->Product);
                        $proooooStore=Stores::find($StoreI[$i]);
                        $pqty['P_Ar_Name']=$prooooo->P_Ar_Name.'(هالك)';
                        $pqty['P_En_Name']=$prooooo->P_En_Name.'(Damage)';
                        $pqty['P_Code']='0'.$prooooo->Barcode;
                        $pqty['Qty']=$QtyI[$i] * $pp->Rate;
                        $pqty['Price']=0;
                        $pqty['TotalCost']=0;
                        $pqty['Pro_Stores']=$id_store;
                        $pqty['Store']=$StoreI[$i];
                        $pqty['Unit']=$UnitI[$i];
                        $pqty['Low_Unit']=$prooooo->Low_Unit;
                        $pqty['Product']=$prooooo->Product;
                        $pqty['V1']=null;
                        $pqty['V2']= null;
                        $pqty['V_Name']=null;
                        $pqty['VV_Name']=null;
                        $pqty['Original']='Damage';
                        $pqty['SearchCode1']=$Newprooooo->SearchCode1;
                        $pqty['SearchCode2']=$Newprooooo->SearchCode2;
                        $pqty['Group']=$Newprooooo->Group;
                        $pqty['Brand']=$Newprooooo->Brand;
                        $pqty['Branch']=$proooooStore->Branch;

                        ProductsQty::create($pqty);


                        $move['Date']=$event->requests['Date'];
                        $move['Type']='هوالك';
                        $move['TypeEn']='Perished';
                        $move['Bill_Num']=$CodeT;
                        $move['Incom']=$QtyI[$i] * $pp->Rate;
                        $move['Outcom']=0;
                        $move['Current']=$QtyI[$i] * $pp->Rate;
                        $move['CostIn']=0;
                        $move['CostOut']=0;
                        $move['CostCurrent']=0;
                        $move['P_Ar_Name']=$prooooo->P_Ar_Name.'(هالك)';
                        $move['P_En_Name']=$prooooo->P_En_Name.'(Damage)';
                        $move['P_Code']='0'.$Product_CodeI[$i];
                        $move['Unit']=$UnitI[$i];
                        $move['QTY']=$QtyI[$i];
                        $move['Group']=$Newprooooo->Group;
                        $move['Store']=$StoreI[$i];
                        $move['Product']=$ProductI[$i];
                        $move['V1']=null;
                        $move['V2']=null;
                        $move['User']=auth()->guard('admin')->user()->id;
                        $Sro=Stores::find($StoreI[$i]);
                        $move['Brand']=$Newprooooo->Brand;
                        $move['Safe']=null;
                        $move['Branch']=$Sro->Branch;
                        $move['SalePrice']=null;
                        $move['ProductPrice']=null;
                        ProductMoves::create($move);




                    }



                }




            }


        }


        //Income Minus Qty
        foreach($ins as $in){

            $Quantity=$this->ProAvQties($in->Store,$in->Product,$in->Product_Code);

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

            $ty=$average->AverageCostGetUnit($in->Product,$in->Product_Code,$in->Store,$in->Unit);

            if($in->Product()->first()->P_Type != 'Service'){
                $Qeqo=$event->requests['Qtyy'] * $in->Qty ;
                $qq= $unit->Rate *  $Qeqo;
                $newqty=$Quantity->Qty -  $qq ;
                $cur=$newqty * $ty ;
                ProductsQty::where('id',$Quantity->id)->update(['Qty'=>$newqty,'Price'=>$ty , 'TotalCost'=>$cur]);



                $inn=0;
                $out=$qq * $ty ;
                $current=$newqty * $ty;


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

                $totCost=0;

                $rr = ProductUnits::where("Unit",$in->Unit)->where('Product',$in->Product)->first();
                $fifo=$this->FifoAvQtyDate($in->Store,$in->Product,$in->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 >= $Qeqo){

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

                            }else{

                                $res=$Qeqo - $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 >= $Qeqo){

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

                        }else{

                            $res=$Qeqo - $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 *  $Qeqo;
                $ty=$average->AverageCostGetUnit($in->Product,$rr->Barcode,$in->Store,$rr->Unit);
                $CostTotalSale=$totCost;
                $inn=0;
                $out=$CostTotalSale;
                $lastOperation=ProductMoves::latest('id')->where('Product',$in->Product)->where('Store',$in->Store)->first();
                $current=($lastOperation->Current - $newQQty) *  $ty;

            }


            $prooooo=Products::find($in->Product);
            $Sro=Stores::find($in->Store);
            $move['Brand']=$prooooo->Brand;
            $move['Date']=$event->requests['Date'];
            $move['Type']='مدخلات تصنيع';
            $move['TypeEn']='Manufacturing Income';
            $move['Bill_Num']=$CodeT;
            $move['Incom']=0;
            $move['Outcom']=$qq;
            $move['Current']=$newqty;
            $move['CostIn']=number_format((float)abs($inn), 2, '.', '');
            $move['CostOut']=number_format((float)abs($out), 2, '.', '');
            $move['CostCurrent']=number_format((float)abs($current), 2, '.', '');
            $move['P_Ar_Name']=$in->P_Ar_Name;
            $move['P_En_Name']=$in->P_En_Name;
            $move['P_Code']=$in->Product_Code;
            $move['Unit']=$in->Unit;
            $move['QTY']=$event->requests['Qtyy'];
            $move['Group']=$prooooo->Group;
            $move['Store']=$in->Store;
            $move['Product']=$in->Product;
            $move['V1']=null;
            $move['V2']=null;
            $move['User']=auth()->guard('admin')->user()->id;
            $move['Safe']=null;
            $move['Branch']=$Sro->Branch;
            $move['SalePrice']=null;
            $move['ProductPrice']=null;
            ProductMoves::create($move);

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

                $fifo=$this->FifoAvQtyDate($in->Store,$in->Product,$in->Product_Code);

                if(!empty($fifo)){

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

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

                        $qq= $unit->Rate * $Qeqo ;

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

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

                    }else{


                        $resdiualQty=$Qeqo - $fifo->Qty ;

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

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

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



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


                    }


                }




            }

            }

            $Mkhazns=ManuStoreCount::all();

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

                $s['Store']=$in->Store;
                $s['Total']=$in->Total * $event->requests['Qtyy'];
                ManuStoreCount::create($s);

            }else{


                $m=ManuStoreCount::where('Store',$in->Store)->first();

                if(!empty($m)){


                    $newTot=$m->Total + ($in->Total * $event->requests['Qtyy'] ) ;

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

                }else{


                    $s['Store']=$in->Store;
                    $s['Total']=$in->Total * $event->requests['Qtyy'];
                    ManuStoreCount::create($s);

                }

            }

        }



        //===================   Joun ===============

        $NewMkhazns=ManuStoreCount::all();

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

            array(

                'Type' => 'التصنيع',
                'TypeEn' => 'Manufacturing',
                'Code_Type' => $CodeT,
                'Date' => $event->requests['Date'],
                'Draw' => $model->Draw,
                'Coin' =>$model->Coin,
                'Cost_Center' => $model->Cost_Center,
                'Total_Debaitor' => $model->Total_Price * $event->requests['Qtyy'],
                'Total_Creditor' => $model->Total_Price * $event->requests['Qtyy'],
                'Note' => null,

            )
        );

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

        foreach($NewMkhazns as $new){
            $out=OutcomManufacturingModel::where('Model',$event->requests['Model'])->first();
            $store=Stores::find($new->Store);
            $storeOut=Stores::find($out->Store);

            $PRODUCTSS['Joun_ID']=$JunID;
            $PRODUCTSS['Debitor']=0;
            $PRODUCTSS['Creditor']=$new->Total;
            $PRODUCTSS['Account']=$store->Account;
            $PRODUCTSS['Statement']=null;


            JournalizingDetails::create($PRODUCTSS);

            $Gen['Code']=$Code;
            $Gen['Code_Type']=$CodeT;
            $Gen['Date']=$event->requests['Date'];
            $Gen['Type']='التصنيع';
            $Gen['TypeEn']='Manufacturing';
            $Gen['Debitor']=0;
            $Gen['Creditor']=$new->Total;
            $Gen['Statement']=null;
            $Gen['Draw']=$model->Draw;
            $Gen['Debitor_Coin']= $model->Draw * 0;
            $Gen['Creditor_Coin']=$model->Draw * $new->Total;
            $Gen['Account']=$store->Account;
            $Gen['Coin']= $model->Coin;
            $Gen['Cost_Center']=$model->Cost_Center;
            $Gen['userr']= auth()->guard('admin')->user()->id;

            GeneralDaily::create($Gen);


            $PRODUCTSS['Joun_ID']=$JunID;
            $PRODUCTSS['Debitor']=$new->Total;
            $PRODUCTSS['Creditor']=0;
            $PRODUCTSS['Account']=$storeOut->Account;
            $PRODUCTSS['Statement']=null;


            JournalizingDetails::create($PRODUCTSS);

            $Gen['Code']=$Code;
            $Gen['Code_Type']=$CodeT;
            $Gen['Date']=$event->requests['Date'];
            $Gen['Type']='التصنيع';
            $Gen['TypeEn']='Manufacturing';
            $Gen['Debitor']=$new->Total;
            $Gen['Creditor']=0;
            $Gen['Statement']=null;
            $Gen['Draw']=$model->Draw;
            $Gen['Debitor_Coin']= $model->Draw * $new->Total;
            $Gen['Creditor_Coin']=$model->Draw * 0;
            $Gen['Account']=$storeOut->Account;
            $Gen['Coin']= $model->Coin;
            $Gen['Cost_Center']= $model->Cost_Center;
            $Gen['userr']= auth()->guard('admin')->user()->id;

            GeneralDaily::create($Gen);

        }

        if($event->requests['Sort'] == 2){


            $account=AcccountingManual::where('Name','تكلفه مصنعيه')->first();

            $PRODUCTSS['Joun_ID']=$JunID;
            $PRODUCTSS['Debitor']=$event->requests['Total_Workmentship'];
            $PRODUCTSS['Creditor']=0;
            $PRODUCTSS['Account']=$account->id;
            $PRODUCTSS['Statement']=null;


            JournalizingDetails::create($PRODUCTSS);

            $Gen['Code']=$Code;
            $Gen['Code_Type']=$CodeT;
            $Gen['Date']=$event->requests['Date'];
            $Gen['Type']='التصنيع';
            $Gen['TypeEn']='Manufacturing';
            $Gen['Debitor']=$event->requests['Total_Workmentship'];
            $Gen['Creditor']=0;
            $Gen['Statement']=null;
            $Gen['Draw']=$model->Draw;
            $Gen['Debitor_Coin']= $model->Draw * $event->requests['Total_Workmentship'];
            $Gen['Creditor_Coin']=$model->Draw * 0;
            $Gen['Account']=$account->id;
            $Gen['Coin']= $model->Coin;
            $Gen['Cost_Center']=$model->Cost_Center;
            $Gen['userr']= auth()->guard('admin')->user()->id;

            GeneralDaily::create($Gen);


            $PRODUCTSS['Joun_ID']=$JunID;
            $PRODUCTSS['Debitor']=0;
            $PRODUCTSS['Creditor']=$event->requests['Total_Workmentship'];
            $PRODUCTSS['Account']=$event->requests['Vendor'];
            $PRODUCTSS['Statement']=null;


            JournalizingDetails::create($PRODUCTSS);

            $Gen['Code']=$Code;
            $Gen['Code_Type']=$CodeT;
            $Gen['Date']=$event->requests['Date'];
            $Gen['Type']='التصنيع';
            $Gen['TypeEn']='Manufacturing';
            $Gen['Debitor']=0;
            $Gen['Creditor']=$event->requests['Total_Workmentship'];
            $Gen['Statement']=null;
            $Gen['Draw']=$model->Draw;
            $Gen['Debitor_Coin']= $model->Draw * 0;
            $Gen['Creditor_Coin']=$model->Draw * $event->requests['Total_Workmentship'];
            $Gen['Account']=$event->requests['Vendor'];
            $Gen['Coin']= $model->Coin;
            $Gen['Cost_Center']= $model->Cost_Center;
            $Gen['userr']= auth()->guard('admin')->user()->id;

            GeneralDaily::create($Gen);



        }


        // =====   Stores  Moves ===================

        $in=IncomManufacturingModel::where('Model',$event->requests['Model'])->latest('id')->first();

        $store=Stores::find($in->Store);

        $dataStMove['Date']=date('Y-m-d');
        $dataStMove['Code']=$CodeT;
        $dataStMove['Time']=date("h:i:s a", time());
        $dataStMove['Branch']=$store->Branch;
        $dataStMove['Store']=$in->Store;
        $dataStMove['Safe']=null;
        $dataStMove['Type']='مدخلات تصنيع';
        $dataStMove['TypeEn']='Income Manfcturing';
        $dataStMove['Cost_Center']=$model->Cost_Center;
        $dataStMove['User']=auth()->guard('admin')->user()->id;
        $dataStMove['Coin']=$model->Coin;
        $dataStMove['Note']=null;
        $dataStMove['Total_Qty']=$event->requests['Qtyy'];
        $dataStMove['Total_Price']=$Tot;
        $dataStMove['Account']=null;
        $dataStMove['Ship']=null;
        $dataStMove['ID']=$ID;
        StoresMoves::create($dataStMove);

        $store=Stores::find($out->Store);

        $dataStMove['Date']=date('Y-m-d');
        $dataStMove['Code']=$CodeT;
        $dataStMove['Time']=date("h:i:s a", time());
        $dataStMove['Branch']=$store->Branch;
        $dataStMove['Store']=$out->Store;
        $dataStMove['Safe']=null;
        $dataStMove['Type']='مخرجات تصنيع';
        $dataStMove['TypeEn']='Outcome Manfcturing';
        $dataStMove['Cost_Center']=$model->Cost_Center;
        $dataStMove['User']=auth()->guard('admin')->user()->id;
        $dataStMove['Coin']=$model->Coin;
        $dataStMove['Note']=null;
        $dataStMove['Total_Qty']=$event->requests['Qtyy'];
        $dataStMove['Total_Price']=$Tot;
        $dataStMove['Account']=null;
        $dataStMove['Ship']=null;
        $dataStMove['ID']=$ID;
        StoresMoves::create($dataStMove);




    }

}
