<?php

namespace App\Http\Controllers;

use App\Imports\ProductUnit;
use App\Models\CrmDefaultData;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

use App\Models\AcccountingManual;
use App\Models\OutcomManufacturingModel;
use App\Models\UsersMoves;
use App\Models\Admin;
use App\Models\Stores;
use App\Models\Measuerments;
use App\Models\Brands;
use App\Models\Assets;
use App\Models\Virables;
use App\Models\SubVirables;
use App\Models\Taxes;
use App\Models\ItemsGroups;
use App\Models\ProductMoves;
use App\Models\ProductUnits;
use App\Models\Products;
use App\Models\SubImages;
use App\Models\AssemblyProducts;
use App\Models\Coins;
use App\Models\StartPeriods;
use App\Models\ProductsStartPeriods;
use App\Models\ProductsStores;
use App\Models\ProductsQty;
use App\Models\Journalizing;
use App\Models\JournalizingDetails;
use App\Models\GeneralDaily;
use App\Models\ProductsVira;
use App\Models\SubscribeTypes;
use App\Models\Inventory;
use App\Models\ProductInventory;
use App\Models\Settlement;
use App\Models\ProductSettlement;
use App\Models\StorsTransfers;
use App\Models\ProductsStoresTransfers;
use App\Models\BarcodeSettings;
use App\Models\BarcodeProducts;
use App\Models\BarcodeShow;
use App\Models\ProductsPurchases;
use App\Models\ProductSales;
use App\Models\Employess;
use App\Models\EmpPOSStores;
use App\Models\ShippingCompany;
use App\Models\CostCenter;
use App\Models\SalesDefaultData;
use App\Models\StoresDefaultData;
use App\Models\PermissionToRecivedGoods;
use App\Models\ProductsPermissionToRecivedGoods;
use App\Models\PermissionToExchangeGoods;
use App\Models\StoreCountSales;
use App\Models\Branches;
use App\Models\Consists;
use App\Models\ManufactureCompany;
use App\Models\ProductsConsists;
use App\Models\DefaultDataShowHide;
use App\Models\ProductsPermissionToExchangeGoods;
use App\Models\Customers;
use App\Models\EmpExc;
use App\Models\ImportNewProds;
use App\Models\ImportNewProdsStart;
use App\Models\PurchasesDefaultData;
use App\Models\MaintainceDefaultData;
use App\Models\ModuleSettingsNum;
use App\Models\Vendors;
use App\Models\Purchases;
use App\Models\ChecksTypes;
use App\Models\ReciptVoucher;
use App\Models\PaymentVoucher;
use App\Models\Vouchers;
use App\Models\ReciptVoucherDetails;
use App\Models\PaymentVoucherDetails;
use App\Models\StoresMoves;
use App\Models\ReturnStorsTransfer;
use App\Models\ReturnProductsStoresTransfers;
use App\Models\Sales;
use App\Models\InstallmentCompanies;
use App\Models\SafesBanks;
use App\Models\ProductSalesSubscribes;
use App\Models\ProductsExecutingReceiving;
use App\Models\ProductsQuote;
use App\Models\ProductSalesOrder;
use App\Models\ProductsPurchasesOrder;
use App\Models\AdditionalProducts;
use App\Models\VAProducts;
use App\Models\VAPrice;
use App\Models\VAQty;
use App\Models\Notifications;
use App\Models\ExpireDateQty;
use App\Models\AttendDepartureImport;
use App\Models\Attendance;
use App\Models\Departure;
use App\Models\AttendanceEmp;
use App\Models\DepartureEmp;
use App\Models\AttendencePolicyEmp;
use App\Models\DepaarturePolicyEmp;
use App\Models\FifoQty;
use App\Models\ProductTypeDefault;

use Str;
use DB;
use DateTime;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

use App\Traits\GeneralTrait;

use App\Services\BarcodeService;
use App\Services\ProductService;
use App\Services\StoresService;
use App\Services\Average;
use App\Services\SalesService;

use App\Events\AddProductEvent;
use App\Events\StartPeriodEvent;
use App\Events\SettlementEvent;
use App\Events\ConsistEvent;
use App\Events\StoresTransferEvent;
use App\Events\SalesEvent;
use App\Events\PurchasesEvent;

use App\Http\Requests\NameRequest;
use App\Http\Requests\ProductRequest;
use App\Http\Requests\InventoryRequest;
use App\Http\Requests\StoresTransferRequest;
use App\Http\Requests\SalesRequest;
use App\Http\Requests\PurchasesRequest;



class StoresController extends Controller
{

      use GeneralTrait;

function __construct()
{

$this->middleware('permission:عرض المخازن', ['only' => ['StoresPage','AddStores','EditStores','DeleteStores']]);
$this->middleware('permission:شركات الشحن', ['only' => ['ShippingCompanyPage','AddShippingCompany','EditShippingCompany','DeleteShippingCompany']]);
$this->middleware('permission:وحدات القياس', ['only' => ['Measurement_UnitsPage','AddMeasurement_Units','EditMeasurement_Units','DeleteMeasurement_Units']]);
$this->middleware('permission:مجموعه الاصناف', ['only' => ['Items_GroupsPage','AddItems_Groups','EditItems_Groups','DeleteItems_Groups']]);
$this->middleware('permission:الصناعه و الماركات', ['only' => ['ManufacturePage','AddManufacture','EditManufacture','DeleteManufacture']]);
$this->middleware('permission:المتغيرات', ['only' => ['VirablesPage','AddVirables','EditVirables','DeleteVirables','Sub_VirablesPage','AddSub_Virables','EditSub_Virables','DeleteSub_Virables']]);
$this->middleware('permission:الضرائب', ['only' => ['TaxesPage','AddTaxes','EditTaxes','DeleteTaxes']]);
$this->middleware('permission:انواع الاشتراكات', ['only' => ['SubscribeTypesPage','AddSubscribeTypes','EditSubscribeTypes','DeleteSubscribeTypes']]);
$this->middleware('permission:دليل الاصناف', ['only' => ['ItemsGuidePage','UpdatePrice']]);
$this->middleware('permission:اضافه صنف', ['only' => ['Add_ItemsPage','PostAddProduct']]);
$this->middleware('permission:جدول الاصناف', ['only' => ['Products_SechdulePage','DeleteItem','EditItems','PostEditProduct']]);
$this->middleware('permission:اضافه جرد', ['only' => ['InventoryPage','AddInventory']]);
$this->middleware('permission:جدول الجرد', ['only' => ['Inventory_SechdulePage','DeleteInventory','EditInvntory','SettlementInvntory','PostEditInventory','PostSettlement']]);
$this->middleware('permission:جدول التسويه', ['only' => ['Settlement_SechdulePage']]);
$this->middleware('permission:اضافه اصناف بدايه فتره', ['only' => ['StartPeriodProductsPage','AddStartPeriod']]);
$this->middleware('permission:جدول اصناف بدايه فتره', ['only' => ['StartPeriodSechdulePage','DeleteStartPeriod','EditStartPeriod','PostEditStartPeriod']]);
$this->middleware('permission:اضافه تحويلات المخازن', ['only' => ['StoresTransfersPage','AddStoresTransfers']]);
$this->middleware('permission:جدول تحويلات المخازن', ['only' => ['StoresTransfersSechdulePage']]);
$this->middleware('permission:طباعه الباركود', ['only' => ['BarcodeـPrintingPage','UpdateBarcodePrint']]);
$this->middleware('permission:اعدادات طباعه الباركود', ['only' => ['BarcodeـPrinting_SettingsPage','AddBaPriSett','EditBaPriSett','DeleteBaPriSett']]);
$this->middleware('permission:اذن صرف بضاعه', ['only' =>['Permission_to_exchange_goods']]);
$this->middleware('permission:اذن استلام بضاعه', ['only' =>['Permission_to_receive_goods']]);
$this->middleware('permission:جدول صرف بضاعه', ['only' =>['ExchangeGoodsSechdulePage']]);
$this->middleware('permission:جدول استلام بضاعه', ['only' =>['ReceiveGoodsSechdule']]);
$this->middleware('permission:تالف', ['only' =>['ConsistsPage']]);
$this->middleware('permission:جدول التوالف', ['only' =>['ConsistsSechdule']]);
$this->middleware('permission:كميات المخازن', ['only' =>['StoresQtyPage']]);
$this->middleware('permission:جدول مبيعات  تحويلات المخازن', ['only' =>['Stores_Sales_Transfers_Sechdule']]);
$this->middleware('permission:عينات', ['only' =>['Samples']]);
$this->middleware('permission:جدول العينات', ['only' =>['SamplesSechdule']]);

}


     //End Mtwst Sa3r Sharaa  ================================

        //====== Stores =======
        public function StoresPage(){
        $items=Stores::all();
        $Branchs=Branches::all();
        $Code=$this->ReturnCode(Stores::class);
        return view('admin.Stores.Stores',get_defined_vars());
        }

        public function AddStores(NameRequest $request){

            try {

                DB::beginTransaction();


        $validated = $request->validated();

        if(!empty(request('NameEn'))){

        $english_name=request('NameEn');
        }else{

        $english_name=request('Name');
        }


        $stDef=StoresDefaultData::latest('id')->first();

        $result=$this->MaxUse('Store_Select',Stores::class,'Store_Num');
        if($result == 1){

        session()->flash('error',trans('admin.Alert_Maximum_Add'));
        return back();

        }



        $Acc=$this->CreateAccount(request('Name'),$english_name ,27 ,null);



        $dataa['Date']=date('Y-m-d');
        $dataa['Time']=date("h:i:s a", time());
        $dataa['Name']=request('Name');
        $dataa['NameEn']=$english_name;
        $dataa['Phone']=request('Phone');
        $dataa['Address']=request('Address');
        $dataa['Account']=$Acc;
        $dataa['Branch']=request('Branch');
        $dataa['Letter']=request('Letter');
        $dataa['User']=auth()->guard('admin')->user()->id;

        Stores::create($dataa);



        if($stDef->Client_Store_Account == 1){
        $ar=request('Name').' '.' عميل مخزن ';
        $en=$english_name.' '.' Store Client ';
        $Store_Acc=$this->CreateAccount($ar,$en ,24 ,null);
        $store=Stores::latest('id')->first();
        Stores::where('id',$store->id)->update(['Account_Client'=>$Store_Acc]);
        }

        $dataUser=[
        'screen_ar'=>'المخازن',
        'screen_en'=>'Stores',
        'explain_ar'=>request('Name'),
        'explain_en'=>$english_name,
        ];
        $this->UserCreateMoves($dataUser);


                DB::commit();
        session()->flash('success',trans('admin.Added_Successfully'));
        return back();

            }catch(\Exception $ex){

                $MODEL=Stores::class;
                DB::rollBack();
                Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

                session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
                return back();

            }catch(\Error $ex){


                $MODEL=Stores::class;
                DB::rollBack();
                Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

                session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
                return back();

            }




        }

        public function EditStores($id,NameRequest $request){


        try {

        DB::beginTransaction();

        $validated = $request->validated();

        $safe=Stores::find($id);
        AcccountingManual::where('id',$safe->Account)->update(['Name'=>request('Name'),'NameEn'=>request('NameEn')]);
        AcccountingManual::where('id',$safe->Account_Client)->update(['Name'=>request('Name').' عميل مخزن ','NameEn'=>request('NameEn').' Store Client ']);


        $dataa['Code']=request('Code');
        $dataa['Date']=request('Date');
        $dataa['Time']=request('Time');
        $dataa['Name']=request('Name');
        $dataa['NameEn']=request('NameEn');
        $dataa['Phone']=request('Phone');
        $dataa['Address']=request('Address');
        $dataa['Account']=request('Account');
        $dataa['User']=request('User');
        $dataa['Branch']=request('Branch');
        $dataa['Letter']=request('Letter');
        Stores::where('id',$id)->update($dataa);


        $dataUser=[
        'screen_ar'=>'المخازن',
        'screen_en'=>'Stores',
        'explain_ar'=>request('Name'),
        'explain_en'=>request('NameEn'),
        ];
        $this->UserUpdateMoves($dataUser);


        DB::commit();

        session()->flash('success',trans('admin.Updated'));
        return back();


        }catch(\Exception $ex){

        $MODEL=Stores::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=Stores::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }



        }

        public function DeleteStores($id){

        try {

        DB::beginTransaction();

        $st=$this->DefaultDataDelete(StoresDefaultData::class,$id,'Store');
        $pu=$this->DefaultDataDelete(PurchasesDefaultData::class,$id,'Store');
        $sa=$this->DefaultDataDelete(SalesDefaultData::class,$id,'Store');
        $result= $st+ $pu + $sa ;
        if($result != 0){
        session()->flash('error',trans('admin.Cant_Delete_Default_Data'));
        return back();

        }

        $del=Stores::find($id);
        AcccountingManual::where('id',$del->Account)->delete();
        AcccountingManual::where('id',$del->Account_Client)->delete();


        $dataUser=[
        'screen_ar'=>'المخازن',
        'screen_en'=>'Stores',
        'explain_ar'=>$del->Name,
        'explain_en'=>$del->NameEn,
        ];
        $this->UserDeleteMoves($dataUser);


        DB::commit();

        $del->delete();
        session()->flash('error',trans('admin.Deleted'));
        return back();


        }catch(\Exception $ex){

        $MODEL=Stores::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=Stores::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }


        }


        //====== Measuerments =======
        public function Measurement_UnitsPage(){
        $items=Measuerments::all();
        return view('admin.Stores.Measuerments',get_defined_vars());
        }

        public function AddMeasurement_Units(NameRequest $request){

        try {
        DB::beginTransaction();

        $validated = $request->validated();

        if(!empty(request('English_Name'))){
        $english_name=request('English_Name');
        }else{
        $english_name=request('Arabic_Name');
        }



        $data['Name']=request('Name');
        $data['NameEn']=$english_name;
        $data['Note']=request('Note');
        $data['Code']=request('Code');


        Measuerments::create($data);


        $dataUser=[
        'screen_ar'=>'وحدات القياس',
        'screen_en'=>'Measurement Units',
        'explain_ar'=>request('Name'),
        'explain_en'=>$english_name,
        ];
        $this->UserCreateMoves($dataUser);


        DB::commit();

        session()->flash('success',trans('admin.Added_Successfully'));
        return back();

        }catch(\Exception $ex){

        $MODEL=Measuerments::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=Measuerments::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }

        }

        public function EditMeasurement_Units($id,NameRequest $request){


        try {
        DB::beginTransaction();

        $validated = $request->validated();

        $data['Name']=request('Name');
        $data['NameEn']=request('NameEn');
        $data['Note']=request('Note');
        $data['Code']=request('Code');
        Measuerments::where('id',$id)->update($data);

        $dataUser=[
        'screen_ar'=>'وحدات القياس',
        'screen_en'=>'Measurement Units',
        'explain_ar'=>request('Name'),
        'explain_en'=>request('NameEn'),
        ];
        $this->UserUpdateMoves($dataUser);


        DB::commit();

        session()->flash('success',trans('admin.Updated'));
        return back();


        }catch(\Exception $ex){

        $MODEL=Measuerments::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=Measuerments::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }



        }

        public function DeleteMeasurement_Units($id){

        try {
        DB::beginTransaction();

        $st=$this->DefaultDataDelete(StoresDefaultData::class,$id,'Unit');
        $result= $st ;
        if($result != 0){
        session()->flash('error',trans('admin.Cant_Delete_Default_Data'));
        return back();

        }


        $del=Measuerments::find($id);

        $dataUser=[
        'screen_ar'=>'وحدات القياس',
        'screen_en'=>'Measurement Units',
        'explain_ar'=>$del->Name,
        'explain_en'=>$del->NameEn,
        ];
        $this->UserCreateMoves($dataUser);

        $del->delete();


        DB::commit();

        session()->flash('error',trans('admin.Deleted'));
        return back();



        }catch(\Exception $ex){

        $MODEL=Measuerments::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=Measuerments::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }


        }

        //====== Manufacture =======
        public function ManufacturePage(){
        $items=Brands::all();
        return view('admin.Stores.Manufacture',get_defined_vars());
        }

        public function AddManufacture(NameRequest $request){

        try {
        DB::beginTransaction();

        $validated = $request->validated();

        if(!empty(request('NameEn'))){

        $english_name=request('NameEn');
        }else{

        $english_name=request('Name');
        }


        $image=request()->file('Image');
        $zFile=$this->UploadFile($image);

        $data['Image']=$zFile;
        $data['Name']=request('Name');
        $data['NameEn']=$english_name;
        $data['Note']=request('Note');
        $data['Sales_Show']=request('Sales_Show');
        $data['Store_Show']=request('Store_Show');
        $data['Sales_Precet']=request('Sales_Precet');

        Brands::create($data);



        $dataUser=[
        'screen_ar'=>'الماركات',
        'screen_en'=>'Brands',
        'explain_ar'=>request('Name'),
        'explain_en'=>$english_name,
        ];
        $this->UserCreateMoves($dataUser);


        DB::commit();

        session()->flash('success',trans('admin.Added_Successfully'));
        return back();


        }catch(\Exception $ex){

        $MODEL=Brands::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=Brands::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }


        }

        public function EditManufacture($id,NameRequest $request){

        try {
        DB::beginTransaction();


        $validated = $request->validated();

        $image=request()->file('Image');
        $zFile=$this->UploadFile($image);

        if(!empty($zFile)){

        $data['Image']=$zFile;

        }else{

        $data['Image']=request('Images');
        }


        $data['Name']=request('Name');
        $data['NameEn']=request('NameEn');
        $data['Note']=request('Note');
        $data['Sales_Show']=request('Sales_Show');
        $data['Store_Show']=request('Store_Show');
        $data['Sales_Precet']=request('Sales_Precet');
        Brands::where('id',$id)->update($data);


        $dataUser=[
        'screen_ar'=>'الماركات',
        'screen_en'=>'Brands',
        'explain_ar'=>request('Name'),
        'explain_en'=>request('NameEn'),
        ];
        $this->UserUpdateMoves($dataUser);


        DB::commit();


        session()->flash('success',trans('admin.Updated'));
        return back();

        }catch(\Exception $ex){

        $MODEL=Brands::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=Brands::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }



        }

        public function DeleteManufacture($id){

        try {
        DB::beginTransaction();

        $del=Brands::find($id);

        $dataUser=[
        'screen_ar'=>'الماركات',
        'screen_en'=>'Brands',
        'explain_ar'=>$del->Name,
        'explain_en'=>$del->NameEn,
        ];
        $this->UserDeleteMoves($dataUser);


        $del->delete();

        DB::commit();


        session()->flash('error',trans('admin.Deleted'));
        return back();

        }catch(\Exception $ex){

        $MODEL=Brands::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=Brands::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }



        }


        //====== Virables =======
        public function VirablesPage(){
        $items=Virables::all();
        return view('admin.Stores.Virables',get_defined_vars());
        }

        public function AddVirables(NameRequest $request){

        try {
        DB::beginTransaction();

        $validated = $request->validated();

        if(!empty(request('NameEn'))){

        $english_name=request('NameEn');
        }else{

        $english_name=request('Name');
        }


        $data['Name']=request('Name');
        $data['NameEn']=$english_name;

        Virables::create($data);


        $dataUser=[
        'screen_ar'=>'المتغيرات',
        'screen_en'=>'Virables',
        'explain_ar'=>request('Name'),
        'explain_en'=>$english_name,
        ];
        $this->UserCreateMoves($dataUser);


        DB::commit();
        session()->flash('success',trans('admin.Added_Successfully'));
        return back();

        }catch(\Exception $ex){

        $MODEL=Virables::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=Virables::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }

        }

        public function EditVirables($id,NameRequest $request){


        try {
        DB::beginTransaction();

        $validated = $request->validated();


        $data['Name']=request('Name');
        $data['NameEn']=request('NameEn');
        Virables::where('id',$id)->update($data);


        $dataUser=[
        'screen_ar'=>'المتغيرات',
        'screen_en'=>'Virables',
        'explain_ar'=>request('Name'),
        'explain_en'=>request('NameEn'),
        ];
        $this->UserUpdateMoves($dataUser);

        DB::commit();
        session()->flash('success',trans('admin.Updated'));
        return back();


        }catch(\Exception $ex){

        $MODEL=Virables::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=Virables::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }



        }

        public function DeleteVirables($id){

        try {
        DB::beginTransaction();

        $Count=SubVirables::where('V_ID',$id)->count();

        if($Count == 0){

        $del=Virables::find($id);

        $dataUser=[
        'screen_ar'=>'المتغيرات',
        'screen_en'=>'Virables',
        'explain_ar'=>$del->Name,
        'explain_en'=>$del->NameEn,
        ];
        $this->UserDeleteMoves($dataUser);

        $del->delete();

        DB::commit();

        session()->flash('error',trans('admin.Deleted'));
        return back();

        }else{
        session()->flash('error',trans('admin.CantDeleteThisItem'));
        return back();

        }


        }catch(\Exception $ex){

        $MODEL=Virables::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=Virables::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }




        }


        //====== Sub Virables =======
        public function Sub_VirablesPage($id){
        $items=SubVirables::where('V_ID',$id)->get();
        $ID=$id;
        return view('admin.Stores.SubVirables',get_defined_vars());
        }

        public function AddSub_Virables(NameRequest $request){

        try {
        DB::beginTransaction();

        $validated = $request->validated();


        if(!empty(request('NameEn'))){

        $english_name=request('NameEn');
        }else{

        $english_name=request('Name');
        }


        $data['Name']=request('Name');
        $data['NameEn']=$english_name;
        $data['V_ID']=request('V_ID');
        SubVirables::create($data);


        $dataUser=[
        'screen_ar'=>'المتغيرات الفرعيه',
        'screen_en'=>'Sub Virables',
        'explain_ar'=>request('Name'),
        'explain_en'=>$english_name,
        ];
        $this->UserCreateMoves($dataUser);

        DB::commit();
        session()->flash('success',trans('admin.Added_Successfully'));
        return back();


        }catch(\Exception $ex){

        $MODEL=SubVirables::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=SubVirables::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }


        }

        public function EditSub_Virables($id,NameRequest $request){


        try {
        DB::beginTransaction();

        $validated = $request->validated();

        $data['V_ID']=request('V_ID');
        $data['Name']=request('Name');
        $data['NameEn']=request('NameEn');
        SubVirables::where('id',$id)->update($data);


        $dataUser=[
        'screen_ar'=>'المتغيرات الفرعيه',
        'screen_en'=>'Sub Virables',
        'explain_ar'=>request('Name'),
        'explain_en'=>request('NameEn'),
        ];
        $this->UserUpdateMoves($dataUser);


        DB::commit();
        session()->flash('success',trans('admin.Updated'));
        return back();


        }catch(\Exception $ex){

        $MODEL=SubVirables::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=SubVirables::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }



        }

        public function DeleteSub_Virables($id){



        try {
        DB::beginTransaction();

        $del=SubVirables::find($id);

        $dataUser=[
        'screen_ar'=>'المتغيرات الفرعيه',
        'screen_en'=>'Sub Virables',
        'explain_ar'=>$del->Name,
        'explain_en'=>$del->NameEn,
        ];
        $this->UserUpdateMoves($dataUser);

        $del->delete();

        DB::commit();
        session()->flash('error',trans('admin.Deleted'));
        return back();



        }catch(\Exception $ex){

        $MODEL=SubVirables::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=SubVirables::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }

        }



        //====== SubscribeTypes =======
        public function SubscribeTypesPage(){
        $items=SubscribeTypes::all();

        return view('admin.Stores.SubscribeTypes',get_defined_vars());
        }

        public function AddSubscribeTypes(NameRequest $request){

        try {
        DB::beginTransaction();

        $validated = $request->validated();


        if(!empty(request('NameEn'))){

        $english_name=request('NameEn');
        }else{

        $english_name=request('Name');
        }


        $data['Name']=request('Name');
        $data['NameEn']=$english_name;
        SubscribeTypes::create($data);



        $dataUser=[
        'screen_ar'=>'انواع الاشتراكات',
        'screen_en'=>'Subscribe Types',
        'explain_ar'=>request('Name'),
        'explain_en'=>$english_name,
        ];
        $this->UserCreateMoves($dataUser);

        DB::commit();

        session()->flash('success',trans('admin.Added_Successfully'));
        return back();


        }catch(\Exception $ex){

        $MODEL=SubscribeTypes::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=SubscribeTypes::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }



        }

        public function EditSubscribeTypes($id,NameRequest $request){

        try {
        DB::beginTransaction();

        $validated = $request->validated();


        $data['Name']=request('Name');
        $data['NameEn']=request('NameEn');


        SubscribeTypes::where('id',$id)->update($data);


        $dataUser=[
        'screen_ar'=>'انواع الاشتراكات',
        'screen_en'=>'Subscribe Types',
        'explain_ar'=>request('Name'),
        'explain_en'=>request('NameEn'),
        ];
        $this->UserUpdateMoves($dataUser);

        DB::commit();


        session()->flash('success',trans('admin.Updated'));
        return back();


        }catch(\Exception $ex){

        $MODEL=SubscribeTypes::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=SubscribeTypes::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }




        }

        public function DeleteSubscribeTypes($id){


        try {
        DB::beginTransaction();
        $del=SubscribeTypes::find($id);

        $dataUser=[
        'screen_ar'=>'انواع الاشتراكات',
        'screen_en'=>'Subscribe Types',
        'explain_ar'=>$del->Name,
        'explain_en'=>$del->NameEn,
        ];
        $this->UserDeleteMoves($dataUser);


        $del->delete();
        DB::commit();


        session()->flash('error',trans('admin.Deleted'));
        return back();



        }catch(\Exception $ex){

        $MODEL=SubscribeTypes::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=SubscribeTypes::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }



        }


        //====== ItemsGroups =======

        public function Items_GroupsPage(){
        $parents=ItemsGroups::where('Parent',0)->get();
        $parentss=ItemsGroups::get();

        return view('admin.Stores.ItemsGroups',get_defined_vars());
        }

        public function AddItems_Groups(NameRequest $request){

        try {
        DB::beginTransaction();

        $validated = $request->validated();


        if(!empty(request('NameEn'))){

        $english_name=request('NameEn');
        }else{

        $english_name=request('Name');
        }


        $image=request()->file('Image');
        $zFile=$this->UploadFile($image);

        $data['Image']=$zFile;
        if(!empty(request('Parent'))){
        $data['Parent']=request('Parent');
        $type=1;
        }else{

        $data['Parent']=0;
        $type=0;
        }
        $data['Name']=request('Name');
        $data['NameEn']=$english_name;
        $data['Discount']=request('Discount');
        $data['Type']=$type;
        $data['Note']=request('Note');
        $data['Sales_Show']=request('Sales_Show');
        $data['Store_Show']=request('Store_Show');
        $data['Printer']=request('Printer');
        $data['Arrange']=request('Arrange');
        $data['Sales_Precet']=request('Sales_Precet');
        ItemsGroups::create($data);


        $dataUser=[
        'screen_ar'=>'مجموعات الاصناف',
        'screen_en'=>'Items Groups',
        'explain_ar'=>request('Name'),
        'explain_en'=>$english_name,
        ];
        $this->UserCreateMoves($dataUser);

        DB::commit();

        session()->flash('success',trans('admin.Added_Successfully'));
        return back();

        }catch(\Exception $ex){

        $MODEL=ItemsGroups::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=ItemsGroups::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }



        }

        public function EditItems_Groups(NameRequest $request){

        try {
        DB::beginTransaction();

            $id=request('ID');
        $validated = $request->validated();



        $image=request()->file('Image');
        $zFile=$this->UploadFile($image);

        if(!empty($zFile)){

        $data['Image']=$zFile;

        }else{

        $data['Image']=request('Images');
        }

        if(!empty(request('Parent'))){
        $data['Parent']=request('Parent');
        }else{
        $data['Parent']=0;
        }



   if(!empty(request('Sales_Show'))){

        $data['Sales_Show']=request('Sales_Show');
        }

   if(!empty(request('Store_Show'))){
        $data['Store_Show']=request('Store_Show');
        }

        $data['Code']=request('Code');
        $data['Name']=request('Name');
        $data['NameEn']=request('NameEn');
        $data['Type']=request('Type');
        $data['Note']=request('Note');
        $data['Discount']=request('Discount');
        $data['Printer']=request('Printer');
        $data['Arrange']=request('Arrange');
        $data['Sales_Precet']=request('Sales_Precet');
        ItemsGroups::where('id',$id)->update($data);


        $dataUser=[
        'screen_ar'=>'مجموعات الاصناف',
        'screen_en'=>'Items Groups',
        'explain_ar'=>request('Name'),
        'explain_en'=>request('NameEn'),
        ];
        $this->UserUpdateMoves($dataUser);


        DB::commit();
        session()->flash('success',trans('admin.Updated'));
        return back();


        }catch(\Exception $ex){

        $MODEL=ItemsGroups::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=ItemsGroups::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }




        }

        public function DeleteItems_Groups(){


        try {
        DB::beginTransaction();


        $id=request('Parent');

        $st=$this->DefaultDataDelete(StoresDefaultData::class,$id,'Group');
        $result= $st;
        if($result != 0){
        session()->flash('error',trans('admin.Cant_Delete_Default_Data'));
        return back();

        }



        $Count=ItemsGroups::where('Parent',$id)->count();

        if($Count == 0){

        $del=ItemsGroups::find($id);

        $dataUser=[
        'screen_ar'=>'مجموعات الاصناف',
        'screen_en'=>'Items Groups',
        'explain_ar'=>$del->Name,
        'explain_en'=>$del->NameEn,
        ];
        $this->UserDeleteMoves($dataUser);


        $del->delete();
        DB::commit();


        session()->flash('error',trans('admin.Deleted'));
        return back();
        }else{
        session()->flash('error',trans('admin.CantDeleteThisItem'));
        return back();

        }




        }catch(\Exception $ex){

        $MODEL=ItemsGroups::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=ItemsGroups::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }




        }

        function SupGroubsFilter(Request $request)
            {

    if($request->ajax())
    {
    $output = '';
    $parent = $request->get('Parent');


    if($parent != '')
    {



$Childs=ItemsGroups::where('Parent',$parent)->get();


    }


    $total_row = $Childs->count();
    if($total_row > 0)
    {





    foreach($Childs as $child){

      if( app()->getLocale() == 'ar'){
            $name=$child->Name;
        }else{
               $name=$child->NameEn;
        }

    $output .= '



   <li class="parent_li">


     <span onclick="SupGroups('.$child->id.')"><i class="fal fa-folder"></i>
    ('.$name.') ('.$child->Discount.')
     </span>



        <button style="display:none" type="button" class="btn btn-default" data-toggle="modal" data-target="#default-example-modal-center'.$child->id.'"><i class="fal fa-trash-alt"></i></button>

        <button style="display:none" type="button" class="btn btn-default" data-toggle="modal" data-target="#default-example-modal-lg-edit'.$child->id.'"><i class="fal fa-edit"></i></button>

               <ul class="Data'.$child->id.'">




                  </ul>




    </li>


    ';


    }


    }
    else
    {
    $output = '
    <div class="col-md-3">'.trans('admin.No_Data_Find').'</div>
    ';
    }
    $data = array(
    'table_data' => $output,

    );
    echo json_encode($data);
    }
    }

    function EditGroubsFilter(Request $request)
    {

        $group=request('group');

        $item=ItemsGroups::findOrFail($group);

        if($item->Store_Show == 1){

            $show=trans('admin.Storee');
        }elseif($item->Store_Show == 2){
            $show=trans('admin.Price_List');

        }elseif($item->Store_Show == 3){

            $show=trans('admin.Both');
        }elseif($item->Store_Show == 0){
            $show=trans('admin.NO');

        }

        if($item->Sales_Show == 0){

            $show2=trans('admin.NO');
        }elseif($item->Sales_Show == 1){
            $show2=trans('admin.Yes');

        }

        if(!empty($item->Parent()->first()->Name)){
            $Parent=$item->Parent()->first()->Name;
        }else{
            $Parent=0;
        }


        $states=[
            'Images'=>$item->Image,
            'Code'=>$item->Code,
            'Type'=>$item->Type,
            'Name'=>$item->Name,
            'NameEn'=>$item->NameEn,
            'Discount'=>$item->Discount,
            'Arrange'=>$item->Arrange,
            'Printer'=>$item->Printer,
            'Note'=>$item->Note,
            'Store_Show'=>$show,
            'Sales_Show'=>$show2,
            'Parent'=>$Parent,
            'Sales_Precet'=>$item->Sales_Precet,

        ];

        return response()->json($states);


    }



    //====== Shipping Companies =======

        public function ShippingCompanyPage(){
        $items=ShippingCompany::all();

        return view('admin.Stores.ShippingCompany',get_defined_vars());
        }

        public function AddShippingCompany(NameRequest $request){

        try {
        DB::beginTransaction();

        $validated = $request->validated();

        if(!empty(request('NameEn'))){

        $english_name=request('NameEn');
        }else{

        $english_name=request('Name');
        }



        $Acc=$this->CreateAccount(request('Name'),$english_name ,97 ,null);



        $dataa['Name']=request('Name');
        $dataa['NameEn']=$english_name;
        $dataa['Phone']=request('Phone');
        $dataa['Tax_Card']=request('Tax_Card');
        $dataa['Commercial_Register']=request('Commercial_Register');
        $dataa['Account']=$Acc;

        ShippingCompany::create($dataa);


        $dataUser=[
        'screen_ar'=>'شركات الشحن',
        'screen_en'=>'Shipping Compaines',
        'explain_ar'=>request('Name'),
        'explain_en'=>$english_name,
        ];
        $this->UserCreateMoves($dataUser);

        DB::commit();

        session()->flash('success',trans('admin.Added_Successfully'));
        return back();


        }catch(\Exception $ex){

        $MODEL=ShippingCompany::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=ShippingCompany::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }

        }

        public function EditShippingCompany($id,NameRequest $request){

        try {
        DB::beginTransaction();

        $validated = $request->validated();

        $safe=ShippingCompany::find($id);
        AcccountingManual::where('id',$safe->Account)->update(['Name'=>request('Name'),'NameEn'=>request('NameEn')]);


        $dataa['Name']=request('Name');
        $dataa['NameEn']=request('NameEn');
        $dataa['Phone']=request('Phone');
        $dataa['Tax_Card']=request('Tax_Card');
        $dataa['Commercial_Register']=request('Commercial_Register');
        $dataa['Account']=request('Account');

        ShippingCompany::where('id',$id)->update($dataa);


        $dataUser=[
        'screen_ar'=>'شركات الشحن',
        'screen_en'=>'Shipping Compaines',
        'explain_ar'=>request('Name'),
        'explain_en'=>request('NameEn'),
        ];
        $this->UserCreateMoves($dataUser);

        DB::commit();

        session()->flash('success',trans('admin.Updated'));
        return back();



        }catch(\Exception $ex){

        $MODEL=ShippingCompany::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=ShippingCompany::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }


        }

        public function DeleteShippingCompany($id){



        try {
        DB::beginTransaction();

        $del=ShippingCompany::find($id);
        AcccountingManual::where('id',$del->Account)->delete();


        $dataUser=[
        'screen_ar'=>'شركات الشحن',
        'screen_en'=>'Shipping Compaines',
        'explain_ar'=>$del->Name,
        'explain_en'=>$del->NameEn,
        ];
        $this->UserDeleteMoves($dataUser);


        $del->delete();
        DB::commit();


        session()->flash('error',trans('admin.Deleted'));
        return back();




        }catch(\Exception $ex){

        $MODEL=ShippingCompany::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=ShippingCompany::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }


        }


        //Barcode Printing Settings

        public function BarcodeـPrinting_SettingsPage(){

        $items=BarcodeSettings::all();
        $Code=$this->ReturnCode(BarcodeSettings::class);

        return view('admin.Stores.BarcodePrintingSettings',get_defined_vars());
        }

        public function AddBaPriSett(NameRequest $request){

        try {
        DB::beginTransaction();

        $validated = $request->validated();

        if(!empty(request('NameEn'))){

        $english_name=request('NameEn');
        }else{

        $english_name=request('Name');
        }

        $data['Code']=request('Code');
        $data['Name']=request('Name');
        $data['NameEn']=$english_name;
        $data['Type']=request('Type');
        $data['Direction']=request('Direction');
        $data['Width']=request('Width');
        $data['Height']=request('Height');
        $data['Padding_L']=request('Padding_L');
        $data['Padding_R']=request('Padding_R');
        $data['Padding_T']=request('Padding_T');
        $data['Padding_B']=request('Padding_B');
        $data['Margin_L']=request('Margin_L');
        $data['Margin_R']=request('Margin_R');
        $data['Margin_T']=request('Margin_T');
        $data['Margin_B']=request('Margin_B');
        $data['Barcode_Width']=request('Barcode_Width');
        $data['Barcode_Height']=request('Barcode_Height');
        $data['Font_Size']=request('Font_Size');
        $data['Line_Height']=request('Line_Height');
        $data['Width_Logo']=request('Width_Logo');
        $data['Height_Logo']=request('Height_Logo');

        BarcodeSettings::create($data);


        $dataUser=[
        'screen_ar'=>'اعدادات طباعه الباركود',
        'screen_en'=>'Barcode Printing Settings',
        'explain_ar'=>request('Name'),
        'explain_en'=>$english_name,
        ];
        $this->UserCreateMoves($dataUser);

        DB::commit();

        session()->flash('success',trans('admin.Added_Successfully'));
        return back();


        }catch(\Exception $ex){

        $MODEL=BarcodeSettings::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=BarcodeSettings::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }


        }

        public function EditBaPriSett($id,NameRequest $request){


        try {
        DB::beginTransaction();

        $validated = $request->validated();


        $data['Code']=request('Code');
        $data['Name']=request('Name');
        $data['NameEn']=request('NameEn');
        $data['Type']=request('Type');
        $data['Direction']=request('Direction');
        $data['Width']=request('Width');
        $data['Height']=request('Height');
        $data['Padding_L']=request('Padding_L');
        $data['Padding_R']=request('Padding_R');
        $data['Padding_T']=request('Padding_T');
        $data['Padding_B']=request('Padding_B');
        $data['Margin_L']=request('Margin_L');
        $data['Margin_R']=request('Margin_R');
        $data['Margin_T']=request('Margin_T');
        $data['Margin_B']=request('Margin_B');
        $data['Barcode_Width']=request('Barcode_Width');
        $data['Barcode_Height']=request('Barcode_Height');
        $data['Font_Size']=request('Font_Size');
        $data['Line_Height']=request('Line_Height');
        $data['Width_Logo']=request('Width_Logo');
        $data['Height_Logo']=request('Height_Logo');


        BarcodeSettings::where('id',$id)->update($data);


        $dataUser=[
        'screen_ar'=>'اعدادات طباعه الباركود',
        'screen_en'=>'Barcode Printing Settings',
        'explain_ar'=>request('Name'),
        'explain_en'=>request('NameEn'),
        ];
        $this->UserUpdateMoves($dataUser);

        DB::commit();


        session()->flash('success',trans('admin.Updated'));
        return back();



        }catch(\Exception $ex){

        $MODEL=BarcodeSettings::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=BarcodeSettings::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }



        }

        public function DeleteBaPriSett($id){


        try {
        DB::beginTransaction();
        $del=BarcodeSettings::find($id);

        $dataUser=[
        'screen_ar'=>'اعدادات طباعه الباركود',
        'screen_en'=>'Barcode Printing Settings',
        'explain_ar'=>$del->Name,
        'explain_en'=>$del->NameEn,
        ];
        $this->UserDeleteMoves($dataUser);

        DB::commit();

        $del->delete();


        session()->flash('error',trans('admin.Deleted'));
        return back();



        }catch(\Exception $ex){

        $MODEL=BarcodeSettings::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=BarcodeSettings::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }


        }


        //Barcode Printing
        public function BarcodeـPrintingPage(){

        $Settings=BarcodeSettings::all();

        return view('admin.Stores.BarcodeـPrinting',get_defined_vars());
        }

        public function UpdateBarcodePrint(BarcodeService $service , Request $request){

        try {
        DB::beginTransaction();


        $service->CreateBarcode($request->all());

        $Settings=BarcodeSettings::all();
        $Set=BarcodeSettings::find(request('Style'));
        $Show=BarcodeShow::orderBy('id','desc')->first();
        $Pros=BarcodeProducts::all();


        DB::commit();

        if(request('SORT') == 1){
        return view('admin.Stores.UpdateBarcode',get_defined_vars());
        }else{

        return view('admin.Stores.UpdateBarcodeA4',get_defined_vars());
        }




        }catch(\Exception $ex){

        $MODEL=BarcodeSettings::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){

        $MODEL=BarcodeSettings::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }

        }


        //Barcode Printing
        public function QRـPrinting(){

        $Settings=BarcodeSettings::all();

        return view('admin.Stores.QRـPrinting',get_defined_vars());
        }

        public function UpdateQRـPrinting(BarcodeService $service , Request $request){

        try {
        DB::beginTransaction();


        $service->CreateBarcode($request->all());

        $Settings=BarcodeSettings::all();
        $Set=BarcodeSettings::find(request('Style'));
        $Show=BarcodeShow::orderBy('id','desc')->first();
        $Pros=BarcodeProducts::all();


        DB::commit();

        if(request('SORT') == 1){
        return view('admin.Stores.UpdateQR',get_defined_vars());
        }else{

        return view('admin.Stores.UpdateQRA4',get_defined_vars());
        }



        }catch(\Exception $ex){

        $MODEL=BarcodeSettings::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){

        $MODEL=BarcodeSettings::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }




        }

        public function BarcodeFilter(BarcodeService $service , Request $request)
        {

        if($request->ajax())
        {
        $output = '';
        $search = $request->get('search');

        if($search != '')
        {
        $data=$this->FilterProduct($search);
        $Prodss=$this->FilterProductQty($search,null);

        }

        $total_row1 = $data->count();
        $total_row2 = $Prodss->count();
        $total_row3 = $total_row1 + $total_row2;
        if($total_row3 > 0)
        {

        foreach($data as $row){

        $rr=ProductUnits::where('Product',$row->Product)->where('Def',1)->first();

        if(app()->getLocale() == 'ar' ){

        $ProName=$row->P_Ar_Name;
        $ProGroup=$row->Product()->first()->Group()->first()->Name;
        $unit=$row->Unit()->first()->Name;

        }else{

        $ProName=$row->P_En_Name;
        $ProGroup=$row->Product()->first()->Group()->first()->Name;
        $unit=$row->Unit()->first()->NameEn;

        }


        $Array=[
        'name'=>$ProName,
        'ar_name'=>$row->P_Ar_Name,
        'en_name'=>$row->P_En_Name,
        'product'=>$row->Product,
        'row_id'=>$row->Product,
        'barcode'=>$rr->Barcode,
        'group'=>$ProGroup,
        'v_one'=>'',
        'v_two'=>'',
        'v_name'=>'',
        'vv_name'=>'',
        'unit_name'=>$unit,
        'price'=>$rr->Price,
        'v_real_name'=>'',
        'vv_real_name'=>'',
        'type'=>1,

        ];

        $output .= $service->ProductsFilter($Array);



        }

        if($total_row1 == 0){
        foreach($Prodss as $row){

        if(app()->getLocale() == 'ar' ){

        $ProName=$row->P_Ar_Name;
        $ProGroup=$row->Product()->first()->Group()->first()->Name;

        if(!empty($row->V1()->first()->Name)){
        $ProV=$row->V1()->first()->Name;
        }else{
        $ProV='';
        }

        if(!empty($row->V2()->first()->Name)){
        $ProVV=$row->V2()->first()->Name;
        }else{
        $ProVV='';
        }


        }else{

        $ProName=$row->P_En_Name;
        $ProGroup=$row->Product()->first()->Group()->first()->Name;

        if(!empty($row->V1()->first()->NameEn)){
        $ProV=$row->V1()->first()->NameEn;
        }else{
        $ProV='';
        }

        if(!empty($row->V2()->first()->NameEn)){
        $ProVV=$row->V2()->first()->NameEn;
        }else{
        $ProVV='';
        }


        }

        $Array=[
        'name'=>$ProName,
        'ar_name'=>$row->P_Ar_Name,
        'en_name'=>$row->P_En_Name,
        'product'=>$row->Product,
        'row_id'=>$row->Product,
        'barcode'=>$rr->Barcode,
        'group'=>$ProGroup,
        'v_one'=>$row->V1,
        'v_two'=>$row->V2,
        'v_name'=>$row->V_Name,
        'vv_name'=>$row->VV_Name,
        'unit_name'=>$unit,
        'price'=>$row->Price,
        'v_real_name'=>$ProV,
        'vv_real_name'=>$ProVV,
        'type'=>2,


        ];

        $output .= $service->ProductsFilter($Array);


        }
        }

        }
        else
        {
        $output = '
        <div class="col-md-3"> '.trans('admin.No_Data_Find').'</div>
        ';
        }
        $data = array(
        'table_data' => $output,
        );
        echo json_encode($data);
        }
        }



        // ========== Items Guide ==============
        public function ItemsGuidePage(){
        $ItemsGroups=ItemsGroups::all();
        $items=ProductUnits::latest('id')->paginate(200);
        $Brands=Brands::all();
            $Def=StoresDefaultData::orderBy('id','desc')->first();
            $show=DefaultDataShowHide::orderBy('id','desc')->first();
        return view('admin.Stores.ItemsGuide',get_defined_vars());
        }

        public function ItemsGuide2(){
        $ItemsGroups=ItemsGroups::all();
        $items=ProductUnits::latest('id')->paginate(200);
            $Def=StoresDefaultData::orderBy('id','desc')->first();
            $show=DefaultDataShowHide::orderBy('id','desc')->first();
        return view('admin.Stores.ItemsGuide2',get_defined_vars());
        }

        public function UpdatePrice(){

        try {
        DB::beginTransaction();


            $id=request('r');
$P=request('P');
$PP=request('PP');
$PPP=request('PPP');
$Code=request('Code');

        ProductUnits::where('id',$id)->update(['Barcode'=>$Code,'Price'=>$P,'Price_Two'=>$PP,'Price_Three'=>$PPP]);


        $pr=ProductUnits::find($id);

        Products::where('id',$pr->Product)->update(['Show_Other_Store'=>request('Show_Other_Store'),'Store_Show'=>request('Store_Show')]);


        $data=0;
        DB::commit();
        echo json_encode($data);

        }catch(\Exception $ex){

        $MODEL=Products::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=Products::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }


        }

        public function TypeGuideFilter(){

        $ItemsGroups=ItemsGroups::all();
        $items=ProductUnits::latest('id')->where('P_Type',request('P_Type'))->paginate(100);
        $Brands=Brands::all();
            $Def=StoresDefaultData::orderBy('id','desc')->first();
            $show=DefaultDataShowHide::orderBy('id','desc')->first();
            $items->appends(request()->query());
        return view('admin.Stores.ItemsGuide',get_defined_vars());
        }

        public function GroupGuideFilter(){

        $ItemsGroups=ItemsGroups::all();

        $items=ProductUnits::latest('id')

        ->when(!empty(request('Group')), function ($query) {

                $AllGroups=ItemsGroups::where('Parent',request('Group'))->get('id');
                $query->whereRelation('Product','Group', request('Group'))->orWhereIn('Group',$AllGroups);

        })


        ->when(!empty(request('Brand')), function ($query) {
        $query->whereRelation('Product','Brand', request('Brand'));
        })


        ->paginate(100);

        $Brands=Brands::all();
            $Def=StoresDefaultData::orderBy('id','desc')->first();
            $show=DefaultDataShowHide::orderBy('id','desc')->first();
        $items->appends(request()->query());
        return view('admin.Stores.ItemsGuide',get_defined_vars());
        }

        public function BrandsGuideFilter(){

        $ItemsGroups=ItemsGroups::all();
        $Brands=Brands::all();
        $items=ProductUnits::latest('id')->whereRelation('Product','Brand',request('Brand'))->paginate(100);
            $Def=StoresDefaultData::orderBy('id','desc')->first();
            $show=DefaultDataShowHide::orderBy('id','desc')->first();
        $items->appends(request()->query());
        return view('admin.Stores.ItemsGuide',get_defined_vars());
        }

        public function NameGuideilter(){

        $ItemsGroups=ItemsGroups::all();
        $items=ProductUnits::latest('id')
        ->where('P_Ar_Name','like','%'.request('Name').'%')
        ->orWhere('P_En_Name','like','%'.request('Name').'%')
        ->paginate(100);

        $Brands=Brands::all();

      $Def=StoresDefaultData::orderBy('id','desc')->first();
            $show=DefaultDataShowHide::orderBy('id','desc')->first();
        $items->appends(request()->query());
        return view('admin.Stores.ItemsGuide',get_defined_vars());
        }

        public function CodeGuideFilter(){

        $ItemsGroups=ItemsGroups::all();


            $items =ProductUnits::
        where('Barcode', request('Code'))
            ->paginate(100);
            $Def=StoresDefaultData::orderBy('id','desc')->first();
            $show=DefaultDataShowHide::orderBy('id','desc')->first();

        $Brands=Brands::all();

        $items->appends(request()->query());
        return view('admin.Stores.ItemsGuide',get_defined_vars());
        }

        public function ChangeProductPrice(){

        $Group=request('Group');
        $Brand=request('Brand');
        $Price=request('Price');
        $Price_Two=request('Price_Two');
        $Price_Three=request('Price_Three');
        $Rounding=request('Rounding');


        $items=ProductUnits::latest('id')
        ->when(!empty(request('Group')), function ($query) {
        $query->where('Group', request('Group'));
        })


        ->when(!empty(request('Brand')), function ($query) {
        $query->where('Brand', request('Brand'));
        })


        ->get();


        if(!empty($items)){

        foreach($items as $item){

        if(!empty($Price)){

        $old1=$item->Price * ($Price / 100) ;
        $new1=$item->Price + $old1 ;


        if(request('Rounding') == 1){
        $new1New=number_format($new1, 1, '.', '');
        }elseif(request('Rounding') == 2){
        $new1New=number_format($new1, 2, '.', '');

        }elseif(request('Rounding') == 0){
        $new1New=round($new1);

        }


        ProductUnits::where('id',$item->id)->update(['Price'=>$new1New]);

        }


        if(!empty($Price_Two)){
        if(!empty($item->Price_Two)){

        $old2=$item->Price_Two * ($Price_Two / 100 );
        $new2=$item->Price_Two + $old2 ;

        if(request('Rounding') == 1){
        $new2New=number_format($new2, 1, '.', '');
        }elseif(request('Rounding') == 2){
        $new2New=number_format($new2, 2, '.', '');

        }elseif(request('Rounding') == 0){
        $new2New=round($new2);

        }


        ProductUnits::where('id',$item->id)->update(['Price_Two'=>$new2New]);

        }
        }


        if(!empty($Price_Three)){
        if(!empty($item->Price_Three)){

        $old3=$item->Price_Three * ($Price_Three / 100) ;
        $new3=$item->Price_Three + $old3 ;

        if(request('Rounding') == 1){
        $new3New=number_format($new3, 1, '.', '');
        }elseif(request('Rounding') == 2){
        $new3New=number_format($new3, 2, '.', '');

        }elseif(request('Rounding') == 0){
        $new3New=round($new3);

        }

        ProductUnits::where('id',$item->id)->update(['Price_Three'=>$new3New]);

        }
        }



        }
        }

        $items->appends(request()->query());
        session()->flash('success',trans('admin.Changed_Price_Successfully'));
        return back();
        }


        //NewChangePrice
        public function NewChangePrice(){
        $ItemsGroups=ItemsGroups::all();
            $items=ProductUnits::latest('id')->paginate(200);
        $Brands=Brands::all();
            $Def=StoresDefaultData::orderBy('id','desc')->first();
        return view('admin.Stores.NewChangePrice',get_defined_vars());
        }

        public function NewTypeGuideFilter(){

        $ItemsGroups=ItemsGroups::all();
        $items=ProductUnits::latest('id')->where('P_Type',request('P_Type'))->paginate(100);
        $Brands=Brands::all();
            $Def=StoresDefaultData::orderBy('id','desc')->first();
        $items->appends(request()->query());
        return view('admin.Stores.NewChangePrice',get_defined_vars());
        }

        public function NewNameGuideilter(){

        $ItemsGroups=ItemsGroups::all();
        $items=ProductUnits::latest('id')
        ->where('P_Ar_Name','like','%'.request('Name').'%')
        ->orWhere('P_En_Name','like','%'.request('Name').'%')
        ->paginate(100);
            $Def=StoresDefaultData::orderBy('id','desc')->first();
        $Brands=Brands::all();
        $items->appends(request()->query());
        return view('admin.Stores.NewChangePrice',get_defined_vars());
        }

        public function NewCodeGuideFilter(){

        $ItemsGroups=ItemsGroups::all();

            $items =ProductUnits::
            where('Barcode', request('Code'))
                ->paginate(100);

            $Def=StoresDefaultData::orderBy('id','desc')->first();
        $Brands=Brands::all();
        $items->appends(request()->query());
        return view('admin.Stores.NewChangePrice',get_defined_vars());
        }

        public function NewGroupGuideFilter(){

        $ItemsGroups=ItemsGroups::all();

            $items=ProductUnits::latest('id')

                ->when(!empty(request('Group')), function ($query) {

                    $AllGroups=ItemsGroups::where('Parent',request('Group'))->get('id');
                    $query->whereRelation('Product','Group', request('Group'))->orWhereIn('Group',$AllGroups);

                })

                ->when(!empty(request('Brand')), function ($query) {
                    $query->whereRelation('Product','Brand', request('Brand'));
                })


                ->paginate(100);

            $Def=StoresDefaultData::orderBy('id','desc')->first();
        $Brands=Brands::all();
        $items->appends(request()->query());
        return view('admin.Stores.NewChangePrice',get_defined_vars());
        }

        public function PostChangePrice(){

        try {
        DB::beginTransaction();



        $Products=request('Product');
        $Price=request('Price');
        $Price_Two=request('Price_Two');
        $Price_Three=request('Price_Three');
        $Rounding=request('Rounding');
        $Type=request('Type');


        if(!empty($Products)){

        for($i=0 ; $i < count($Products) ; $i++){ $item=ProductUnits::find($Products[$i]); if($Type==1){ if(!empty($Price)){ $old1=$item->Price * ($Price / 100) ;
            $new1=$item->Price + $old1 ;


            if(request('Rounding') == 1){
            $new1New=number_format($new1, 1, '.', '');
            }elseif(request('Rounding') == 2){
            $new1New=number_format($new1, 2, '.', '');

            }elseif(request('Rounding') == 0){
            $new1New=round($new1);

            }


            ProductUnits::where('id',$item->id)->update(['Price'=>$new1New]);

            }


            if(!empty($Price_Two)){
            if(!empty($item->Price_Two)){

            $old2=$item->Price_Two * ($Price_Two / 100 );
            $new2=$item->Price_Two + $old2 ;

            if(request('Rounding') == 1){
            $new2New=number_format($new2, 1, '.', '');
            }elseif(request('Rounding') == 2){
            $new2New=number_format($new2, 2, '.', '');

            }elseif(request('Rounding') == 0){
            $new2New=round($new2);

            }


            ProductUnits::where('id',$item->id)->update(['Price_Two'=>$new2New]);

            }
            }


            if(!empty($Price_Three)){
            if(!empty($item->Price_Three)){

            $old3=$item->Price_Three * ($Price_Three / 100) ;
            $new3=$item->Price_Three + $old3 ;

            if(request('Rounding') == 1){
            $new3New=number_format($new3, 1, '.', '');
            }elseif(request('Rounding') == 2){
            $new3New=number_format($new3, 2, '.', '');

            }elseif(request('Rounding') == 0){
            $new3New=round($new3);

            }

            ProductUnits::where('id',$item->id)->update(['Price_Three'=>$new3New]);

            }
            }


            }elseif($Type == 0){


            if(!empty($Price)){


            $new1=$Price ;


            if(request('Rounding') == 1){
            $new1New=number_format($new1, 1, '.', '');
            }elseif(request('Rounding') == 2){
            $new1New=number_format($new1, 2, '.', '');

            }elseif(request('Rounding') == 0){
            $new1New=round($new1);

            }


            ProductUnits::where('id',$item->id)->update(['Price'=>$new1New]);

            }


            if(!empty($Price_Two)){



            $new2=$Price_Two ;

            if(request('Rounding') == 1){
            $new2New=number_format($new2, 1, '.', '');
            }elseif(request('Rounding') == 2){
            $new2New=number_format($new2, 2, '.', '');

            }elseif(request('Rounding') == 0){
            $new2New=round($new2);

            }


            ProductUnits::where('id',$item->id)->update(['Price_Two'=>$new2New]);


            }


            if(!empty($Price_Three)){



            $new3=$Price_Three;

            if(request('Rounding') == 1){
            $new3New=number_format($new3, 1, '.', '');
            }elseif(request('Rounding') == 2){
            $new3New=number_format($new3, 2, '.', '');

            }elseif(request('Rounding') == 0){
            $new3New=round($new3);

            }

            ProductUnits::where('id',$item->id)->update(['Price_Three'=>$new3New]);


            }



            }elseif($Type == 2){

            if(!empty($Price)){


            $new1=$item->Price + $Price ;


            if(request('Rounding') == 1){
            $new1New=number_format($new1, 1, '.', '');
            }elseif(request('Rounding') == 2){
            $new1New=number_format($new1, 2, '.', '');

            }elseif(request('Rounding') == 0){
            $new1New=round($new1);

            }


            ProductUnits::where('id',$item->id)->update(['Price'=>$new1New]);

            }


            if(!empty($Price_Two)){
            if(!empty($item->Price_Two)){


            $new2=$item->Price_Two + $Price_Two ;

            if(request('Rounding') == 1){
            $new2New=number_format($new2, 1, '.', '');
            }elseif(request('Rounding') == 2){
            $new2New=number_format($new2, 2, '.', '');

            }elseif(request('Rounding') == 0){
            $new2New=round($new2);

            }


            ProductUnits::where('id',$item->id)->update(['Price_Two'=>$new2New]);

            }else{


            $new2= $Price_Two ;

            if(request('Rounding') == 1){
            $new2New=number_format($new2, 1, '.', '');
            }elseif(request('Rounding') == 2){
            $new2New=number_format($new2, 2, '.', '');

            }elseif(request('Rounding') == 0){
            $new2New=round($new2);

            }


            ProductUnits::where('id',$item->id)->update(['Price_Two'=>$new2New]);


            }
            }


            if(!empty($Price_Three)){
            if(!empty($item->Price_Three)){


            $new3=$item->Price_Three + $Price_Three ;

            if(request('Rounding') == 1){
            $new3New=number_format($new3, 1, '.', '');
            }elseif(request('Rounding') == 2){
            $new3New=number_format($new3, 2, '.', '');

            }elseif(request('Rounding') == 0){
            $new3New=round($new3);

            }

            ProductUnits::where('id',$item->id)->update(['Price_Three'=>$new3New]);

            }else{

            $new3= $Price_Three ;

            if(request('Rounding') == 1){
            $new3New=number_format($new3, 1, '.', '');
            }elseif(request('Rounding') == 2){
            $new3New=number_format($new3, 2, '.', '');

            }elseif(request('Rounding') == 0){
            $new3New=round($new3);

            }

            ProductUnits::where('id',$item->id)->update(['Price_Three'=>$new3New]);


            }
            }


            }


            }
            }

            DB::commit();

            session()->flash('success',trans('admin.Changed_Price_Successfully'));
            return back();

            }catch(\Exception $ex){

            $MODEL=Products::class;
            DB::rollBack();
            Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

            }catch(\Error $ex){


            $MODEL=Products::class;
            DB::rollBack();
            Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

            }



            }



   //===== Products ===========================================================

     public function Add_ItemsPage(){

     $Units=Measuerments::all();
     $Brands=Brands::all();
     $Taxes=Taxes::all();
     $ItemsGroups=ItemsGroups::all();
     $Virables=Virables::all();
     $SubscribeTypes=SubscribeTypes::all();
     $AdditionsProducts=Products::where('P_Type','Additions')->get();
     $Types=ProductTypeDefault::all();
     $Def=StoresDefaultData::orderBy('id','desc')->first();
     $DefSHOW=DefaultDataShowHide::orderBy('id','desc')->first();
     return view('admin.Stores.Products',get_defined_vars());
     }

     public function PostAddProduct(ProductRequest $request){


             try {
        DB::beginTransaction();

        $validated = $request->validated();



        if(!empty(request('P_En_Name'))){
         $english_name=request('P_En_Name');
         }else{
         $english_name=request('P_Ar_Name');
         }

     if(empty(request('Barcode'))){
     session()->flash('error',trans('admin.MustChoiceBarcode'));
     return back();
     }


                 //Product Event
          AddProductEvent::dispatch($request->all());


        $dataUser=[
        'screen_ar'=>'الاصناف',
        'screen_en'=>'Products',
        'explain_ar'=>request('P_Ar_Name'),
        'explain_en'=>$english_name,
        ];
        $this->UserCreateMoves($dataUser);


               DB::commit();

                 session()->flash('success',trans('admin.Added_Successfully'));
                 return back();

        }catch(\Exception $ex){

        $MODEL=Products::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=Products::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }





                 }

     public function FilterPSechdule(){

     $Brands=Brands::all();
     $ItemsGroups=ItemsGroups::all();
     $Stores=Stores::all();

     $AdditionsProducts=Products::where('P_Type','Additions')->get();
     $Types=ProductTypeDefault::all();

     $data =ProductUnits::
     where('Barcode', request('Code'))
     ->first();


           $items=Products::latest('id')

       ->with('GroupX','BrandX','subscribe_typeX','TaxX')

      ->when(!empty(request('Group')), function ($query) {

         $AllGroups=ItemsGroups::where('Parent',request('Group'))->get('id');
        $query->where('Group', request('Group'))->orWhereIn('Group',$AllGroups);
        })


        ->when(!empty(request('Brand')), function ($query) {
        $query->where('Brand', request('Brand'));
        })


        ->when(!empty(request('P_Type')), function ($query) {
        $query->where('P_Type', request('P_Type'));
        })


        ->when(!empty(request('Name')), function ($query) {
        $query->where('P_Ar_Name', 'ILIKE', '%' . request('Name') .'%')
              ->OrWhere('P_En_Name', 'ILIKE', '%' . request('Name') .'%');
        })


        ->when(!empty($data), function ($query) use($data) {
        $query->where('id',$data->Product);
        })

               ->paginate(20);
     $items->appends(request()->query());
     return view('admin.Stores.ProductsSechdule',get_defined_vars());
     }

     public function Products_SechdulePage(){

     $items=Products::latest('id')->with('GroupX','BrandX','subscribe_typeX','TaxX')->paginate(20);
     $Brands=Brands::all();
     $ItemsGroups=ItemsGroups::all();
     $Stores=Stores::all();

     $AdditionsProducts=Products::where('P_Type','Additions')->get();
        $Types=ProductTypeDefault::all();
     return view('admin.Stores.ProductsSechdule',get_defined_vars());
     }

     //=================

     public function UnActiveItem($id){


             try {
        DB::beginTransaction();
    Products::where('id',$id)->update(['Status'=>1]);
     $del=Products::find($id);


            $dataUser=[
        'screen_ar'=>'الاصناف',
        'screen_en'=>'Products',
        'type_ar'=>'عدم تفعيل',
        'type_en'=>'Un Active',
        'explain_ar'=>$del->P_Ar_Name,
        'explain_en'=>$del->P_En_Name,
        ];
        $this->UserCustomMoves($dataUser);


               DB::commit();

     session()->flash('error',trans('admin.UnActive'));
     return back();



        }catch(\Exception $ex){

        $MODEL=Products::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=Products::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }



     }

     public function ActiveItem($id){


          try {
        DB::beginTransaction();

          Products::where('id',$id)->update(['Status'=>0]);
          $del=Products::find($id);
            $dataUser=[
        'screen_ar'=>'الاصناف',
        'screen_en'=>'Products',
        'type_ar'=>'تفعيل',
        'type_en'=>'Active',
        'explain_ar'=>$del->P_Ar_Name,
        'explain_en'=>$del->P_En_Name,
        ];
        $this->UserCustomMoves($dataUser);


               DB::commit();

                session()->flash('success',trans('admin.Active'));
     return back();
        }catch(\Exception $ex){

        $MODEL=Products::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=Products::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }

     }

     //===============

     public function DeleteItem($id){


                    try {
        DB::beginTransaction();

     $del=Products::find($id);


        Products::where('id',$id)->update(['Status'=>1,'Delete'=>1]);

ProductUnits::where('Product',$id)->delete();

             ProductMoves::where('Product',$id)->update(['Delete'=>1]);


        $dataUser=[
        'screen_ar'=>'الاصناف',
        'screen_en'=>'Products',
        'explain_ar'=>$del->P_Ar_Name,
        'explain_en'=>$del->P_En_Name,
        ];
        $this->UserDeleteMoves($dataUser);


               DB::commit();

     session()->flash('error',trans('admin.Deleted'));
     return back();


        }catch(\Exception $ex){

        $MODEL=Products::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=Products::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }



     }

     public function DelSubImage($id){

                try {
        DB::beginTransaction();


     $del=SubImages::find($id);
     $del->delete();

          DB::commit();

     session()->flash('error',trans('admin.Deleted'));
     return back();

       }catch(\Exception $ex){

        $MODEL=Products::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=Products::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }

     }

     public function DeleteVAPrice($id){

                   try {
        DB::beginTransaction();
     $del=VAPrice::find($id);
     $del->delete();
           DB::commit();

     session()->flash('error',trans('admin.Deleted'));
     return back();

           }catch(\Exception $ex){

        $MODEL=Products::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=Products::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }

     }

     public function DeleteVAProQty($id){

                   try {
        DB::beginTransaction();
     $del=VAQty::find($id);
     $del->delete();
           DB::commit();
     session()->flash('error',trans('admin.Deleted'));
     return back();

           }catch(\Exception $ex){

        $MODEL=Products::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=Products::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }

     }

     public function DeleteVAPro($id){

                try {
        DB::beginTransaction();

     $del=VAProducts::find($id);
     VAQty::where('VAProductID',$id)->where('Product',$del->Product)->delete();
     $del->delete();
           DB::commit();
     session()->flash('error',trans('admin.Deleted'));
     return back();


           }catch(\Exception $ex){

        $MODEL=Products::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=Products::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }

     }

     public function DeleteSerialQty($id){

                   try {
        DB::beginTransaction();

     $del=ProductsQty::find($id);
     $del->delete();
           DB::commit();
     session()->flash('error',trans('admin.Deleted'));
     return back();

            }catch(\Exception $ex){

        $MODEL=Products::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=Products::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }

     }

     public function MultiDeleteVira(){

                   try {
        DB::beginTransaction();
     if(is_array(request('Vira')))
     {
     session()->flash('error',trans('admin.Deleted'));
     ProductsVira::destroy(request('Vira'));

     }elseif(!is_array(request('Vira'))){

     session()->flash('error',trans('admin.NotSelected'));

     }else{
     session()->flash('error',trans('admin.Deleted'));
     ProductsVira::find(request('Vira'))->delete();
     }
  DB::commit();
          session()->flash('error',trans('admin.Deleted'));
     return back();

            }catch(\Exception $ex){

        $MODEL=Products::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=Products::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }

     }

     //===================

    public function EditItems($id){

     $Units=Measuerments::all();
     $Brands=Brands::all();
     $Taxes=Taxes::all();
     $ItemsGroups=ItemsGroups::all();
     $item=Products::find($id);
     $ProsUnit=ProductUnits::where('Product',$item->id)->get();
     $subs=SubImages::where('Product',$item->id)->get();
     $ProductsVira=ProductsVira::where('Product',$item->id)->get();
     $Assembls=AssemblyProducts::where('p_id',$item->id)->get();
     $Additions=AdditionalProducts::where('Product',$item->id)->get();
     $SubscribeTypes=SubscribeTypes::all();
     $Virables=Virables::all();
     $AdditionsProducts=Products::where('P_Type','Additions')->get();
     $Types=ProductTypeDefault::all();
     $Def=StoresDefaultData::orderBy('id','desc')->first();
     $DefSHOW=DefaultDataShowHide::orderBy('id','desc')->first();
     return view('admin.Stores.EditItems',get_defined_vars());
     }

    public function PostEditProduct(Request $request,$id,ProductService $service){


             try {
        DB::beginTransaction();


                     $data= $this->validate(request(),[
             'P_Type'=>'required',
             'P_Ar_Name'=>'required',
             'Group'=>'required',
 'Image'=>'image|mimes:jpeg,png,jpg|max:2048',
               ],[
            'P_Type.required' => trans('admin.P_TypeRequired'),
            'P_Ar_Name.required' => trans('admin.P_Ar_NameRequired'),
            'Group.required' => trans('admin.GroupRequired'),

         ]);
            //use service
   $service->UpdateProduct($request->all(),$id);



         if(request()->hasFile('SubImage')){
         foreach ($request->SubImage as $photo) {
         $filename = $photo->store('ProductImagesCatlouge');
         SubImages::create([
         'Product' => $id,
         'Image' => $filename
         ]);
         }
         }


                  AssemblyProducts::where('p_id',$id)->delete();
                  ProductsVira::where('Product',$id)->delete();
                  AdditionalProducts::where('Product',$id)->delete();

               $service->ProductAdd($request->all(),$id);

        $service->UpdateOtherProduct($request->all(),$id);



        $dataUser=[
        'screen_ar'=>'الاصناف',
        'screen_en'=>'Products',
        'explain_ar'=>request('P_Ar_Name'),
        'explain_en'=>request('P_En_Name'),
        ];
        $this->UserUpdateMoves($dataUser);


               DB::commit();

                         session()->flash('success',trans('admin.Updated'));
                         return redirect('Products_Sechdule');




        }catch(\Exception $ex){

        $MODEL=Products::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=Products::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }





                         }

    public function PostEditAV(Request $request,ProductService $service){


       try {
        DB::beginTransaction();


          $image=request()->file('Image');
        $img=$this->UploadFile($image);
    if(!empty($img)){

    $img=$img;

    }else{
    $img=request('Images');
    }

    $id=request('ID');
    $data['P_Ar_Name'] = request('P_Ar_Name');
    $data['P_En_Name'] = request('P_En_Name');
    $data['Brand'] = request('Brand');
    $data['Group'] = request('Group');
    $data['Image'] = $img;
    $data['Ar_Desc'] = request('Ar_Desc');
    $data['En_Desc'] = request('En_Desc');
    $data['Ar_Spec'] = request('Ar_Spec');
    $data['En_Spec'] = request('En_Spec');
    $data['Store_Show'] = request('Store_Show');

    Products::where('id',$id)->update($data);


        $service->UpdateOtherProduct($request->all(),$id);

    $dataUser=[
        'screen_ar'=>'الاصناف',
        'screen_en'=>'Products',
        'explain_ar'=>request('P_Ar_Name'),
        'explain_en'=>request('P_En_Name'),
        ];
        $this->UserUpdateMoves($dataUser);


               DB::commit();

    session()->flash('success',trans('admin.Updated'));
    return redirect('Products_Sechdule');


        }catch(\Exception $ex){

        $MODEL=Products::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=Products::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }




    }

    public function PostEditQTYPriceAV(Request $request){


       try {
        DB::beginTransaction();

    $ID=request('ID');

    if(!empty(request('ProductVA'))){

    $P_Ar_NameVA=request('P_Ar_NameVA');
    $P_En_NameVA=request('P_En_NameVA');
    $P_CodeVA=request('P_CodeVA');
    $UnitVA=request('UnitVA');
    $ProductVA=request('ProductVA');

    for($i=0 ; $i < count($ProductVA) ; $i++){
        $AddProVA['Product_Code']=$P_CodeVA[$i];
        $AddProVA['P_Ar_Name']=$P_Ar_NameVA[$i];
        $AddProVA['P_En_Name']=$P_En_NameVA[$i];
        $AddProVA['Unit']=$UnitVA[$i];
        $AddProVA['Product']=$ID;
        $AddProVA['ProductID']=$ProductVA[$i];
        VAProducts::create($AddProVA);
    }
        $ViraVA=request('ViraVA');
        $SubViraVA=request('SubViraVA');
        $QtyVA=request('QtyVA');
        $ProductVAQty=request('ProductVAQty');

        for($x=0 ; $x < count($ProductVAQty) ; $x++){
            $ProductsVA=VAProducts::where('Product',$ID)->where('ProductID',$ProductVAQty[$x])->orderBy('id','desc')->first();

        $AddProVAQty['Qty']=$QtyVA[$x];
        $AddProVAQty['MainV']=$ViraVA[$x];
        $AddProVAQty['SubV']=$SubViraVA[$x];
        $AddProVAQty['ProductID']=$ProductVAQty[$x];
        $AddProVAQty['Product']=$ID;
        $AddProVAQty['VAProductID']=$ProductsVA->id;

        VAQty::create($AddProVAQty);
        }



        }

        if(!empty(request('PriceVA'))){

        $PriceVAMainV=request('PriceVAMainV');
        $PriceVASubV=request('PriceVASubV');
        $PriceVA=request('PriceVA');
        $OfferPriceVA=request('OfferPriceVA');
        for($i=0 ; $i < count($PriceVA) ; $i++){
            $AddProVAPrice['Product']=$ID;
            $AddProVAPrice['Price']=$PriceVA[$i];
            $AddProVAPrice['MainV']=$PriceVAMainV[$i];
            $AddProVAPrice['SubV']=$PriceVASubV[$i];
            $AddProVAPrice['Offer_Price']=$OfferPriceVA[$i];
            VAPrice::create($AddProVAPrice);
        }
        }

              $del=Products::find($ID);

                   $dataUser=[
        'screen_ar'=>'الاصناف',
        'screen_en'=>'Products',
    'explain_ar'=>$del->P_Ar_Name,
        'explain_en'=>$del->P_En_Name,
        ];


        $this->UserUpdateMoves($dataUser);


               DB::commit();


        session()->flash('success',trans('admin.Updated'));
            return back();

        }catch(\Exception $ex){

        $MODEL=Products::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=Products::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }


            }

    public function PostEditAddittionAV(Request $request){


       try {
        DB::beginTransaction();


           $id=request('ID');
        $del=Products::find($id);

                   $dataUser=[
        'screen_ar'=>'الاصناف',
        'screen_en'=>'Products',
    'explain_ar'=>$del->P_Ar_Name,
        'explain_en'=>$del->P_En_Name,
        ];
        $this->UserUpdateMoves($dataUser);

        if(!empty(request('Additional_Product'))){

        AdditionalProducts::where('Product',$id)->delete();
        $Additional_Product=request('Additional_Product');



        for($i=0 ; $i < count($Additional_Product) ; $i++){
            $AddPro['Product']=$id;
            $AddPro['Additional_Product']=$Additional_Product[$i];
            AdditionalProducts::create($AddPro);
        }
        }

              DB::commit();

        session()->flash('success',trans('admin.Updated'));
                return redirect('Products_Sechdule');


           }catch(\Exception $ex){

        $MODEL=Products::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=Products::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }



                }

    public function EditSerialQty(){

          try {
        DB::beginTransaction();

                $code = request('Code');
                $ID =request('ID');

                for($i=0 ; $i < count($code) ; $i++){
                    ProductsQty::where('id',$ID[$i])->update(['P_Code'=>$code[$i]]);

                    }

                 DB::commit();
                    session()->flash('success',trans('admin.Updated'));

                    return back();


           }catch(\Exception $ex){

        $MODEL=Products::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=Products::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }

                    }

    //=====================


    function AssemblyFilter(Request $request){

    if($request->ajax())
    {
    $output = '';
    $search = $request->get('search');

    if($search != '')
    {


       $data=$this->FilterProduct($search);



    }



    $total_row = $data->count();

    if($total_row > 0)
    {


    foreach($data as $row){

              if(is_numeric($search)){

     $ser_x=1;
     $ser_y=0;

    }else{


        $ser_x=1;
     $ser_y=1;


 }



 if($row->Def == $ser_x or $row->Def == $ser_y){

    $rr=ProductUnits::where('Product',$row->Product)->where('Def',1)->first();

    $units=ProductUnits::where('Product',$row->Product)->get();


    if(app()->getLocale() == 'ar' ){
    $PrrroName=$row->P_Ar_Name;
    $UniiName=$rr->Unit()->first()->Name;

    }else{
    $PrrroName=$row->P_En_Name;
    $UniiName=$rr->Unit()->first()->NameEn;

    }


    $output .= '

    <tr id="Row'.$row->Product.'">
        <td>
            '.$PrrroName.'
            <input type="hidden" id="P_Ar_Name'.$row->Product.'" value="'.$row->P_Ar_Name.'">
            <input type="hidden" id="P_En_Name'.$row->Product.'" value="'.$row->P_En_Name.'">

            <input type="hidden" id="Product'.$row->Product.'" value="'.$row->Product.'">

        </td>

        <td>
            <select class="select2 form-control w-100" id="UnitAssem'.$row->Product.'" onchange="UnitNameCode('.$row->Product.')">
                <option value=""> '.trans('admin.Choice_Unit').'</option>
                ';

                foreach($units as $uni){
                $nam=Measuerments::find($uni->Unit);
                if(app()->getLocale() == 'ar' ){
                $UnitNamme=$nam->Name;
                }else{

                $UnitNamme=$nam->NameEn;
                }

                $output .= '
                <option value="'.$uni->Unit.'" ';  if($uni->Def == 1){    $output .= ' selected ';  }   $output .= '> '.$UnitNamme.'</option>
                ';
                }

                $output .= '

            </select>
        </td>


        <td>
            <input type="number" step="any" id="Qty'.$row->Product.'" class="form-control" onkeyup="AssTotal('.$row->Product.')" onclick="AssTotal('.$row->Product.')">
            <input type="hidden" id="UnitNameAssem'.$row->Product.'" value="'.$UniiName.'">
            <input type="hidden" id="CodeAssem'.$row->Product.'" value="'.$rr->Barcode.'">

        </td>

        <td>

            <input type="number" step="any" id="Price'.$row->Product.'" step="any" class="form-control" onkeyup="AssTotal('.$row->Product.')" onclick="AssTotal('.$row->Product.')" value="'.$rr->Price.'" disabled>

        </td>

        <td>

            <input type="text" id="Total'.$row->Product.'" class="form-control" disabled>
        </td>


        <td>
            <button type="button" class="btn btn-default waves-effect waves-themed" style="display:none" id="AddBtnPur'.$row->Product.'" onclick="Fun('.$row->Product.')">
                <i class="fal fa-plus"></i>
            </button>
        </td>



    </tr>


    ';

    }

    }

    }
    else
    {
    $output = '
    <div class="col-md-3">'.trans('admin.No_Data_Find').'</div>
    ';
    }
    $data = array(
    'table_data' => $output,
    );
    echo json_encode($data);
    }
    }

    function VariableAggregateFilter(Request $request)
    {

    if($request->ajax())
    {
    $output = '';
    $search = $request->get('searchVariableAggregate');
    $r = $request->get('r');

    if($search != '')
    {

  $data=$this->FilterProduct($search);


    }

    $total_row = $data->count();

    if($total_row > 0)
    {


    foreach($data as $row){
       if(is_numeric($search)){

     $ser_x=1;
     $ser_y=0;

    }else{


        $ser_x=1;
     $ser_y=1;


 }



 if($row->Def == $ser_x or $row->Def == $ser_y){

    $rr=ProductUnits::where('Product',$row->Product)->where('Def',1)->first();

    $units=ProductUnits::where('Product',$row->Product)->get();

    if(app()->getLocale() == 'ar' ){
    $PrrroName=$row->P_Ar_Name;
    $UniiName=$rr->Unit()->first()->Name;

    }else{
    $PrrroName=$row->P_En_Name;
    $UniiName=$rr->Unit()->first()->NameEn;

    }


    $output .= '

    <tr id="RowVA'.$row->Product.'">
        <td>
            '.$PrrroName.'
            <input type="hidden" id="P_Ar_Name'.$row->Product.'" value="'.$row->P_Ar_Name.'">
            <input type="hidden" id="P_En_Name'.$row->Product.'" value="'.$row->P_En_Name.'">

            <input type="hidden" id="Product'.$row->Product.'" value="'.$row->Product.'">

        </td>

        <td>
            '.$rr->Barcode.'
            <input type="hidden" id="UnitNameAssem'.$row->Product.'" value="'.$UniiName.'">
            <input type="hidden" id="CodeAssem'.$row->Product.'" value="'.$rr->Barcode.'">
        </td>
        <td>
            <select class="select2 form-control w-100" id="UnitAssem'.$row->Product.'" onchange="UnitNameCode('.$row->Product.')">
                <option value=""> '.trans('admin.Choice_Unit').'</option>
                ';

                foreach($units as $uni){
                $nam=Measuerments::find($uni->Unit);
                if(app()->getLocale() == 'ar' ){
                $UnitNamme=$nam->Name;
                }else{

                $UnitNamme=$nam->NameEn;
                }

                $output .= '
                <option value="'.$uni->Unit.'" ';  if($uni->Def == 1){    $output .= ' selected ';  }   $output .= '> '.$UnitNamme.'</option>
                ';
                }

                $output .= '

            </select>
        </td>





        <td>
            <button type="button" class="btn btn-default waves-effect waves-themed" id="AddVA'.$row->Product.'" onclick="FunVA('.$row->Product.')">
                <i class="fal fa-plus"></i>
            </button>
        </td>



    </tr>


    ';


    }
    }

    }
    else
    {
    $output = '
    <div class="col-md-3">'.trans('admin.No_Data_Find').'</div>
    ';
    }
    $data = array(
    'table_data' => $output,
    );
    echo json_encode($data);
    }
    }


    public function TaxPriceFilter(Request $request){


    $TAX = $request->get('TAX');

    $tax=Taxes::find($TAX);

    if($tax->Rate != 0){
    $Result=($tax->Rate / 100) + 1;
    }else{
    $Result=0;

    }
    $states=['rate'=>$Result];
    return response()->json($states);

    }

    function SerialProductsQtyFilter(Request $request)
    {

    if($request->ajax())
    {
    $output = '';
    $store = $request->get('store');
    $product = $request->get('product');

    if($store != '')
    {


    $Prods=ProductsQty::
    where('Product',$product)
    ->where('Store',$store)
    ->get();


    }


    $total_row = $Prods->count();
    if($total_row > 0)
    {


    foreach($Prods as $rows){

    $output .= '

    <tr>
        <td>
            <input type="text" class="form-control" name="Code[]" value="'.$rows->P_Code.'">
            <input type="hidden" name="ID[]" value="'.$rows->id.'">
        </td>

        <td>

            <a class="btn btn-danger" href="'.url('DeleteSerialQty/'.$rows->id).'"><i class="fal fa-trash"></i></a>

        </td>
    </tr>

    ';


    }


    }
    else
    {
    $output = '
    <div class="col-md-3">'.trans('admin.No_Data_Find').'</div>
    ';
    }
    $data = array(
    'table_data' => $output,
    );
    echo json_encode($data);
    }
    }


    public function UnitNameFilter($id) {


    if(app()->getLocale() == 'ar' ){
    $states = Measuerments::where("id",$id)->pluck("Name","id");
    }else{
    $states = Measuerments::where("id",$id)->pluck("NameEn","id");

    }

    return response()->json($states);

    }

    public function AddCheckName(Request $request) {
    $search = $request->get('ARNAME');
    $states = [];

    $Prods=Products::
    where('P_Ar_Name',$search)
    ->orWhere('P_En_Name',$search)
    ->first();

    if(!empty($Prods)){

    if($Prods->P_Ar_Name == $search){
    $x=1;
    }elseif($Prods->P_En_Name == $search){
    $x=1;
    }else{
    $x=0;

    }

    }else{
    $x=0;
    }

    $states +=['Name' => $x];
    return response()->json($states);

    }

    public function VASelectFilterr() {

    if(app()->getLocale() == 'ar' ){
    $states = DB::table("virables")->pluck("Name","id");
    }else{
    $states = DB::table("virables")->pluck("NameEn","id");
    }

    return response()->json($states);

    }


    public function VASubSelectFilterr() {

    if(app()->getLocale() == 'ar' ){
    $states = DB::table("sub_virables")->where('V_ID',request('VA'))->pluck("Name","id");
    }else{
    $states = DB::table("sub_virables")->where('V_ID',request('VA'))->pluck("NameEn","id");
    }

    return response()->json($states);




    }

    function VOneFilter(Request $request)
    {

    if($request->ajax())
    {
    $output = '';
    $search = $request->get('search');

    if($search != '')
    {

    $data =SubVirables::
    where('V_ID', $search)
    ->get();


    }


    $total_row = $data->count();
    if($total_row > 0)
    {

    foreach($data as $row){

    if(app()->getLocale() == 'ar' ){
    $xName=$row->Name;

    }else{
    $xName=$row->NameEn;

    }

    $output .= '

    <tr>
        <td>
            '.$xName.'
            <input type="hidden" name="VOneName[]" value="'.$row->id.'">
        </td>
        <td> <input type="number" step="any" name="VOneCost[]" class="form-control" value="0"> </td>
    </tr>



    ';


    }

    }
    else
    {
    $output = '
    <div class="col-md-3"> '.trans('admin.No_Data_Find').' </div>
    ';
    }
    $data = array(
    'table_data' => $output,
    );
    echo json_encode($data);
    }
    }

    function VTwoFilter(Request $request)
    {

    if($request->ajax())
    {
    $output = '';
    $search = $request->get('search');
    $searchT = $request->get('searchT');

    if($search != '' and $searchT != '')
    {

    $dataHeader =SubVirables::
    where('V_ID', $searchT)
    ->get();

    $data =SubVirables::
    where('V_ID', $search)
    ->get();


    }


    $total_row = $data->count();
    if($total_row > 0)
    {




    $output .= '

    <thead class="bg-highlight">
        <tr>
            <th class="text-center">'.trans('admin.Virable').'</th>
            ';

            foreach($dataHeader as $rowH){

            if(app()->getLocale() == 'ar' ){
            $xName=$rowH->Name;

            }else{
            $xName=$rowH->NameEn;

            }

            $output .= '


            <th class="text-center"> '.$xName.'
                <input type="hidden" name="VTwooName[]" value="'.$rowH->id.'">

            </th>



            ';
            }
            $output .= '
        </tr>
    </thead>
    <tbody>
        ';

        foreach($data as $row){

        if(app()->getLocale() == 'ar' ){
        $xxName=$row->Name;

        }else{
        $xxName=$row->NameEn;

        }
        $output .= '
        <tr>
            <td class="text-center">
                '.$xxName.'
                <input type="hidden" name="VTwoName[]" value="'.$row->id.'">
            </td>
            ';
            foreach($dataHeader as $rowH){
            $output .= '
            <td class="text-center"> <input type="number" step="any" name="VTwoCost[]" class="form-control" placeholder="'.trans('admin.Cost').'" value="0"> </td>


            ';
            }

            $output .= '
        </tr>
        ';
        }
        $output .= '

    </tbody>



    ';


    }
    else
    {
    $output = '
    <div class="col-md-3">'.trans('admin.No_Data_Find').'</div>
    ';
    }
    $data = array(
    'table_data' => $output,
    );
    echo json_encode($data);
    }
    }

    public function UnitNameCodeFilter($id,$Pro) {

    $average = new Average ;

    $x = ProductUnits::where("Unit",$id)->where('Product',$Pro)->first();
    $y = Measuerments::find($id);

     $rr = ProductUnits::where("Unit",$id)->where('Product',$Pro)->first();
      $Store=request('Store');

     $COSTpr=$average->AverageCostGetUnit($Pro, $rr->Barcode,$Store,$id);

    $states=[];
    if(app()->getLocale() == 'ar' ){
    $states += ['code'=>$x->Barcode ,'name'=>$y->Name,'price'=>$COSTpr];
    }else{
    $states += ['code'=>$x->Barcode ,'name'=>$y->NameEn,'price'=>$COSTpr];
    }
    return response()->json($states);

    }

    public function UnitNameCodeFilterr($id,$Pro) {
    $x = ProductUnits::where("Unit",$id)->where('Product',$Pro)->first();
    $y = Measuerments::find($id);

    $states=[];

    if(app()->getLocale() == 'ar' ){
    $states += ["name" => $y->Name ,'code' => $x->Barcode ,'price' => $x->Price];
    }else{
    $states += ["name" => $y->NameEn ,'code' => $x->Barcode ,'price' => $x->Price];
    }
    return response()->json($states);

    }

    //==============================


    //New One
    public function AddNewProduct(){


    $Name=request('Name');
    $EnName=request('EnName');
    $P_Type=request('P_Type');
    $Brand=request('Brand');
    $Group=request('Group');
    $unit=request('unit');
    $Rate=request('Rate');
    $Barcode=request('Barcode');
    $Price=request('Price');
    $Price_Two=request('Price_Two');
    $Price_Three=request('Price_Three');


    if(!empty($EnName)){

    $EnName=$EnName;
    }else{

    $EnName=$Name;

    }



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

    array(

    'P_Type' => $P_Type,
    'P_Ar_Name' => $Name,
    'P_En_Name' => $EnName,
    'Brand' => $Brand,
    'Group' => $Group,
    'Minimum' => 0,
    'Tax' => 1,
    'Status' => 0,

    )
    );


    $uu['Rate']=$Rate;
    $uu['Barcode']=$Barcode;
    $uu['Price']=$Price;
    $uu['Price_Two']=$Price_Two;
    $uu['Price_Three']=$Price_Three;
    $uu['Def']=1;
    $uu['P_Ar_Name']=$Name;
    $uu['P_En_Name']=$EnName;
    $uu['P_Type']=$P_Type;
    $uu['Unit']=$unit;
    $uu['Product']=$ID;
    $uu['Brand']=$Brand;
    $uu['Group']=$Group;
    ProductUnits::create($uu);




    $move['Date']=date('Y-m-d');
    $move['Type']='رصيد سابق';
    $move['TypeEn']='Previous Balance';
    $move['Bill_Num']=0;
    $move['Incom']=0;
    $move['Outcom']=0;
    $move['Current']=0;
    $move['CostIn']=0;
    $move['CostOut']=0;
    $move['CostCurrent']=0;
    $move['P_Ar_Name']=$Name;
    $move['P_En_Name']=$EnName;
    $move['P_Code']=null;
    $move['Unit']=null;
    $move['Group']=$Group;
    $move['Store']=null;
    $move['Product']=$ID;
    $move['V1']=null;
    $move['V2']=null;
    $move['Brand']=$Brand;
    $move['Safe']=null;
    $move['Branch']=null;
    $move['SalePrice']=null;
    $move['ProductPrice']=null;
    $move['User']=auth()->guard('admin')->user()->id;

    ProductMoves::create($move);



    $dataUser['User']=auth()->guard('admin')->user()->id;
    $dataUser['Date']=date('Y-m-d');
    $dataUser['Time']=date("h:i:s a", time());
    $dataUser['Screen']='الاصناف';
    $dataUser['ScreenEn']='Products';
    $dataUser['Type']='اضافه جديده';
    $dataUser['TypeEn']='New Add';
    $dataUser['Explain']=$Name;
    $dataUser['ExplainEn']=$EnName;
    UsersMoves::create($dataUser);


    $states=['SUCEESS'=>'SUCEESS'];
    return response()->json($states);

    }


       //===== End Products ===========================================================



    // =============== Start Period ===============================================

    public function StartPeriodProductsPage(){

    $Stores=Stores::type()->get();
    $Code=$this->ReturnCode(StartPeriods::class);
    $Coins=Coins::all();
    $Brands=Brands::all();
    $ItemsGroups=ItemsGroups::all();
    $Def=StoresDefaultData::orderBy('id','desc')->first();
    $show=DefaultDataShowHide::orderBy('id','desc')->first();
    return view('admin.Stores.StartPeriod',get_defined_vars());
    }

    public function StartPeriodSechdulePage(){

    $items=StartPeriods::orderBy('id','desc')->paginate(100);

    return view('admin.Stores.StartPeriodsSechdule',get_defined_vars());
    }

    public function EditStartPeriod($id){

    $Stores=Stores::type()->get();
    $Code=$this->ReturnCode(StartPeriods::class);
    $Coins=Coins::all();
    $Brands=Brands::all();
    $ItemsGroups=ItemsGroups::all();
    $item=StartPeriods::find($id);
    $Pros=ProductsStartPeriods::where('SP_ID',$item->id)->get();
    $Def=StoresDefaultData::orderBy('id','desc')->first();
    $show=DefaultDataShowHide::orderBy('id','desc')->first();
    return view('admin.Stores.EditStartPeriod',get_defined_vars());
    }

    public function StartPeriodPrint($id){

    $item=StartPeriods::find($id);
    $Prods=ProductsStartPeriods::where('SP_ID',$id)->get();

    return view('admin.Stores.StartPeriodPrint',get_defined_vars());
    }

    public function AddStartPeriod(Request $request,StoresService $service){

    try {
    DB::beginTransaction();

    $data= $this->validate(request(),[
    'Store'=>'required',
    'Coin'=>'required',
    ],[
    'Store.required' => trans('admin.StoreRequired'),
    'Coin.required' => trans('admin.CoinRequired'),
    ]);



    $ID=$service->CreateNewStart($request->all());

    StartPeriodEvent::dispatch($request->all(),$ID);


    $dataUser=[
    'screen_ar'=>'اصناف بداية فترة',
    'screen_en'=>'Start Period Products',
    'explain_ar'=>request('Code'),
    'explain_en'=>request('Code'),
    ];
    $this->UserCreateMoves($dataUser);


    DB::commit();

    session()->flash('success',trans('admin.Added_Successfully'));
    return back();


    }catch(\Exception $ex){

    $MODEL=StartPeriods::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=StartPeriods::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }



    }

    public function DeleteStartPeriod($id,StoresService $service){

    try {
    DB::beginTransaction();

    $del=StartPeriods::findOrFail($id);

    StartPeriods::where('id',$id)->update(['Delete'=>1]);

    GeneralDaily::where('Code_Type',$del->Code)->where('Type','اصناف بداية فترة')->delete();
    Journalizing::where('Code_Type',$del->Code)->where('Type','اصناف بداية فترة')->update(['Delete'=>1]);
    StoresMoves::where('ID',$del->id)->where('Type','بدايه فتره')->update(['Delete'=>1]);



    //Service Remove Qties

    $service->RemoveQties($id,1,0);


    $dataUser=[
    'screen_ar'=>'اصناف بداية فترة',
    'screen_en'=>'Start Period Products',
    'explain_ar'=>$del->Code,
    'explain_en'=>$del->Code,
    ];
    $this->UserDeleteMoves($dataUser);



    DB::commit();

    session()->flash('error',trans('admin.Deleted'));
    return back();

    }catch(\Exception $ex){

    $MODEL=StartPeriods::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=StartPeriods::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }


    }

    public function PostEditStartPeriod($id,Request $request,StoresService $service){


    try {
    DB::beginTransaction();

    $data= $this->validate(request(),[
    'Store'=>'required',
    'Coin'=>'required',
    ],[
    'Store.required' => trans('admin.StoreRequired'),
    'Coin.required' => trans('admin.CoinRequired'),
    ]);


    $del=StartPeriods::findOrFail($id);

    StartPeriods::where('id',$id)->update(['Edit'=>1,'Edit_New_Code'=>request('Code')]);

    GeneralDaily::where('Code_Type',$del->Code)->where('Type','المشتريات')->delete();
    Journalizing::where('Code_Type',$del->Code)->where('Type','اصناف بداية فترة')->update(['Edit'=>1,'Edit_New_Code'=>request('Code')]);
    StoresMoves::where('ID',$del->id)->where('Type','بدايه فتره')->update(['Edit'=>1,'Edit_New_Code'=>request('Code')]);


    //Service Remove Qties

    $service->RemoveQties($id,0,request('Code'));


    $ID=$service->CreateNewStart($request->all());

    StartPeriodEvent::dispatch($request->all(),$ID);



    $dataUser=[
    'screen_ar'=>'اصناف بداية فترة',
    'screen_en'=>'Start Period Products',
    'explain_ar'=>request('Old_Code'),
    'explain_en'=>request('Old_Code'),
    ];
    $this->UserUpdateMoves($dataUser);



    DB::commit();


    session()->flash('success',trans('admin.Updated'));
    return redirect('StartPeriodSechdule');


    }catch(\Exception $ex){

    $MODEL=StartPeriods::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=StartPeriods::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }



    }


    //Filters

    function StartProductsFilter(Request $request,$store,StoresService $service)
    {

    if($request->ajax())
    {
    $output = '';
    $search = $request->get('search');
    $Brand = $request->get('Brand');
    $Group = $request->get('Group');

    if($search != '')
    {

    $data =$this->FilterPurchProduct($search,$Brand,$Group);

    }

    $total_row = $data->count();
    if($total_row > 0)
    {


    $st=Stores::find($store);
    $def=StoresDefaultData::latest('id')->first();


    foreach($data as $row){

    if($row->Def == 1){
    $rr=ProductUnits::where('Product',$row->Product)->where('Def',1)->first();
    $pro=ProductsStores::where('Product',$row->Product)->where('Store',$store)->first();


    if(!empty($row->Product()->first()->Brand)){

    $branddX=$row->Product()->first()->Brand;
    if(app()->getLocale() == 'ar' ){
    $brandd=$row->Product()->first()->Brand()->first()->Name;

    }else{
    $brandd=$row->Product()->first()->Brand()->first()->NameEn;
    }

    }else{

    $brandd="";
    $branddX="";

    }



    if($row->P_Type == 'Completed' or $row->P_Type == 'Raw' or $row->P_Type == 'Service' or $row->P_Type == 'Industrial' or $row->P_Type == 'Additions'){
    $type=1;
    }elseif($row->P_Type == 'Serial'){
    $type=2;
    }elseif($row->P_Type == 'Single_Variable'){
    $type=3;
    }elseif($row->P_Type == 'Duble_Variable'){
    $type=4;

    }

    if(app()->getLocale() == 'ar' ){
    $PrrroName=$row->P_Ar_Name;
    $UniiName=$row->Unit()->first()->Name;
    $StoreNemo=$st->Name;

    }else{
    $PrrroName=$row->P_En_Name;
    $UniiName=$row->Unit()->first()->NameEn;
    $StoreNemo=$st->NameEn;

    }


    if($def->StartPeriod_Show_Product == 1){


    if(!empty($Group) and !empty($Brand)){

    if($row->Product()->first()->Group == $Group and $branddX == $Brand){

    $Filter=[

    'store'=>$store,
    'product'=>$row->Product,
    'name_ar'=>$row->P_Ar_Name,
    'name_en'=>$row->P_En_Name,
    'type'=>$type,
    'PrrroName'=>$PrrroName,
    'UniiName'=>$UniiName,
    'StoreNemo'=>$StoreNemo,
        'search'=>$search,

    ];

    $output .=$service->ItemsFilter($Filter);

    }

    }elseif(!empty($Group) and empty($Brand)){


    if($row->Product()->first()->Group == $Group){

    $Filter=[


    'store'=>$store,
    'product'=>$row->Product,
    'name_ar'=>$row->P_Ar_Name,
    'name_en'=>$row->P_En_Name,
    'type'=>$type,
    'PrrroName'=>$PrrroName,
    'UniiName'=>$UniiName,
    'StoreNemo'=>$StoreNemo,
        'search'=>$search,

    ];

    $output .=$service->ItemsFilter($Filter);

    }


    }elseif(empty($Group) and !empty($Brand)){

    if($branddX == $Brand){

    $Filter=[

    'store'=>$store,
    'product'=>$row->Product,
    'name_ar'=>$row->P_Ar_Name,
    'name_en'=>$row->P_En_Name,
    'type'=>$type,
    'PrrroName'=>$PrrroName,
    'UniiName'=>$UniiName,
    'StoreNemo'=>$StoreNemo,
        'search'=>$search,

    ];

    $output .=$service->ItemsFilter($Filter);

    }


    }elseif(empty($Group) and empty($Brand)){

    $Filter=[

    'store'=>$store,
    'product'=>$row->Product,
    'name_ar'=>$row->P_Ar_Name,
    'name_en'=>$row->P_En_Name,
    'type'=>$type,
    'PrrroName'=>$PrrroName,
    'UniiName'=>$UniiName,
    'StoreNemo'=>$StoreNemo,
        'search'=>$search,

    ];

    $output .=$service->ItemsFilter($Filter);

    }


    }else{

    if(empty($pro)){

    if(!empty($Group) and !empty($Brand)){

    if($row->Product()->first()->Group == $Group and $branddX == $Brand){

    $Filter=[

    'store'=>$store,
    'product'=>$row->Product,
    'name_ar'=>$row->P_Ar_Name,
    'name_en'=>$row->P_En_Name,
    'type'=>$type,
    'PrrroName'=>$PrrroName,
    'UniiName'=>$UniiName,
    'StoreNemo'=>$StoreNemo,
        'search'=>$search,

    ];

    $output .=$service->ItemsFilter($Filter);

    }

    }elseif(!empty($Group) and empty($Brand)){


    if($row->Product()->first()->Group == $Group){

    $Filter=[


    'store'=>$store,
    'product'=>$row->Product,
    'name_ar'=>$row->P_Ar_Name,
    'name_en'=>$row->P_En_Name,
    'type'=>$type,
    'PrrroName'=>$PrrroName,
    'UniiName'=>$UniiName,
    'StoreNemo'=>$StoreNemo,
        'search'=>$search,

    ];

    $output .=$service->ItemsFilter($Filter);

    }


    }elseif(empty($Group) and !empty($Brand)){

    if($branddX == $Brand){

    $Filter=[

    'store'=>$store,
    'product'=>$row->Product,
    'name_ar'=>$row->P_Ar_Name,
    'name_en'=>$row->P_En_Name,
    'type'=>$type,
    'PrrroName'=>$PrrroName,
    'UniiName'=>$UniiName,
    'StoreNemo'=>$StoreNemo,
        'search'=>$search,

    ];

    $output .=$service->ItemsFilter($Filter);

    }


    }elseif(empty($Group) and empty($Brand)){

    $Filter=[

    'store'=>$store,
    'product'=>$row->Product,
    'name_ar'=>$row->P_Ar_Name,
    'name_en'=>$row->P_En_Name,
    'type'=>$type,
    'PrrroName'=>$PrrroName,
    'UniiName'=>$UniiName,
    'StoreNemo'=>$StoreNemo,
        'search'=>$search,

    ];

    $output .=$service->ItemsFilter($Filter);

    }


    }

    }


    }

    }


    }else
    {
    $output = '
    <div class="col-md-3">'.trans('admin.No_Data_Find').'</div>
    ';
    }
    $data = array(
    'table_data' => $output,
    );
    echo json_encode($data);
    }
    }

    public function ViraFilter($id) {
    $x = ProductsVira::where('Product',$id)->get();

    $states=[];

    foreach($x as $d){

    if(app()->getLocale() == 'ar' ){
    $states += ["$d->V1" => $d->V1()->first()->Name];
    }else{
    $states += ["$d->V1" => $d->V1()->first()->NameEn];
    }

    }


    return response()->json($states);

    }

    public function ViraTwoFilter($id) {
    $x = ProductsVira::where('Product',$id)->get();

    $states=[];

    foreach($x as $d){
    $states += ["V2" => $d->V2];
    $states += ["V1" => $d->V1];

    }


    return response()->json($states);

    }

    public function ViraName($id) {

    $x = ProductsVira::where('Product',$id)->get();

    $states=[];

    foreach($x as $d){
    if(app()->getLocale() == 'ar' ){
    $f=$d->V1()->first()->Name;
    $states += [ $d->V1.$d->V2 => $d->V1()->first()->Name. " - " . $d->V2()->first()->Name];
    }else{

    $f=$d->V1()->first()->NameEn;
    $states += [ $d->V1.$d->V2 => $d->V1()->first()->NameEn. " - " . $d->V2()->first()->NameEn];

    }

    }




    return response()->json($states);

    }

    function MoreProDetailsStart(Request $request)
    {

    if($request->ajax())
    {
    $output = '';
    $r = $request->get('r');


    if($r != '')
    {

    $Pros=ProductsStartPeriods::where('SP_ID',$r)->get();



    }


    $total_row = $Pros->count();
    if($total_row > 0)
    {
    foreach($Pros as $pro){

    if(app()->getLocale() == 'ar'){

    $name=$pro->Product()->first()->P_Ar_Name;

    if(!empty($pro->V1)){
    $V=$pro->V1()->first()->Name;
    }else{
    $V='';
    }


    if(!empty($pro->V2)){
    $VV=$pro->V2()->first()->Name;
    }else{
    $VV='';
    }

    $unit=$pro->Unit()->first()->Name;

    $store=$pro->Store()->first()->Name;


    }else{
    $name=$pro->Product()->first()->P_En_Name;

    if(!empty($pro->V1)){
    $V=$pro->V1()->first()->NameEn;
    }else{
    $V='';
    }


    if(!empty($pro->V2)){
    $VV=$pro->V2()->first()->NameEn;
    }else{
    $VV='';
    }

    $unit=$pro->Unit()->first()->NameEn;
    $store=$pro->Store()->first()->NameEn;

    }




    $output .= '<tr>


        <td>

            '.$name.' ('.$V.') ('.$VV.')
        </td>


        <td> '.$pro->P_Code.' </td>

        <td> '.$pro->Patch_Number.'</td>

        <td> '.$pro->Exp_Date.'</td>
        <td>
            '.$unit.'
        </td>
        <td>
            '.$pro->Qty.'
        </td>

        <td>
            '.$pro->Price.'
        </td>
        <td>
            '.$pro->Total.'
        </td>

        <td>

            '.$store.'


        </td>



    </tr>';



    }


    }else
    {
    $output = '
    <div class="col-md-3">'.trans('admin.No_Data_Find').'</div>
    ';
    }
    $data = array(
    'table_data' => $output,
    );
    echo json_encode($data);
    }
    }

     //===== End  Start Period ===========================================================


    // =============== Inventory ===============================================
    public function InventoryPage(){

    $Stores=Stores::type()->get();
    $Code=$this->ReturnCode(Inventory::class);
    $Coins=Coins::all();
    $Brands=Brands::all();
    $ItemsGroups=ItemsGroups::all();
    $Def=StoresDefaultData::orderBy('id','desc')->first();
    $show=DefaultDataShowHide::orderBy('id','desc')->first();
    return view('admin.Stores.Inventory',get_defined_vars());
    }

    public function EditInvntory($id){

    $item=Inventory::find($id);
    $Pros=ProductInventory::where('Inv_ID',$item->id)->get();

    $Stores=Stores::type()->get();
    $Code=$this->ReturnCode(Inventory::class);
    $Coins=Coins::all();
    $Brands=Brands::all();
    $ItemsGroups=ItemsGroups::all();
    $Def=StoresDefaultData::orderBy('id','desc')->first();
    $show=DefaultDataShowHide::orderBy('id','desc')->first();



    if($item->Settle != 0){
    session()->flash('error',trans('admin.Already_Done'));
    return redirect('Inventory_Sechdule');

    }


    return view('admin.Stores.EditInventory',get_defined_vars());
    }

    public function InventoryPrint($id){

    $item=Inventory::find($id);
    $Pros=ProductInventory::where('Inv_ID',$item->id)->get();
    return view('admin.Stores.InventoryPrint',get_defined_vars());
    }

    public function Inventory_SechdulePage(){

    $items=Inventory::orderBy('id','desc')->paginate(100);

    return view('admin.Stores.InventorySechdule',get_defined_vars());
    }


    public function AddInventory(InventoryRequest $request){

    try {
    DB::beginTransaction();

    $validated = $request->validated();

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

    array(


    'Date' => request('Date'),
    'Draw' => request('Draw'),
    'Note' => request('Note'),
    'Total_Dificit' => request('Total_Dificit'),
    'Total_Excess' => request('Total_Excess'),
    'Total_Dificit_Price' => request('Total_Dificit_Price'),
    'Total_Excess_Price' => request('Total_Excess_Price'),
    'Account_Excess' => request('Account_Excess'),
    'Account_Dificit' => request('Account_Dificit'),
    'Store' => request('Store'),
    'Coin' => request('Coin'),
    'Settle' => 0,
    'User' => auth()->guard('admin')->user()->id,


    )
    );


    if(!empty(request('Unit'))){

    $Unit=request('Unit');
    $P_Code=request('P_Code');
    $P_Price=request('Price');
    $P_Qty=request('Qty');
    $P_Inventory=request('Inventory');
    $P_Dificit=request('Dificit');
    $P_Excess=request('Excess');
    $P_Product=request('Product');
    $P_VOne=request('VOne');
    $P_VTwo=request('VTwo');
    $TotalDificitP=request('TotalDificitP');
    $TotalExcessP=request('TotalExcessP');
    $Exp_Date=request('Exp_Date');

    for($i=0 ; $i < count($Unit) ; $i++){ $uu['Inv_ID']=$ID; $uu['P_Code']=$P_Code[$i]; $uu['Av_Qty']=$P_Qty[$i]; $uu['Inventory']=$P_Inventory[$i]; $uu['Deficit']=$P_Dificit[$i]; $uu['Excess']=$P_Excess[$i]; $uu['Product']=$P_Product[$i]; $uu['V1']=$P_VOne[$i]; $uu['V2']=$P_VTwo[$i]; $uu['Unit']=$Unit[$i]; $uu['Price']=$P_Price[$i]; $uu['TotalDificitP']=$TotalDificitP[$i]; $uu['TotalExcessP']=$TotalExcessP[$i]; $uu['Exp_Date']=$Exp_Date[$i]; ProductInventory::create($uu); } } $dataUser=[ 'screen_ar'=>'الجرد',
        'screen_en'=>'Inventory',
        'explain_ar'=>request('Code'),
        'explain_en'=>request('Code'),
        ];
        $this->UserCreateMoves($dataUser);

        DB::commit();

        session()->flash('success',trans('admin.Added_Successfully'));
        return back();


        }catch(\Exception $ex){

        $MODEL=Inventory::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=Inventory::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }


        }

        public function DeleteInventory($id){


        try {
        DB::beginTransaction();

        $del=Inventory::find($id);

        Inventory::where('id',$id)->update(['Delete'=>1]);

        $dataUser=[
        'screen_ar'=>'الجرد',
        'screen_en'=>'Inventory',
        'explain_ar'=>$del->Code,
        'explain_en'=>$del->Code,
        ];
        $this->UserDeleteMoves($dataUser);

        DB::commit();

        session()->flash('error',trans('admin.Deleted'));
        return back();


        }catch(\Exception $ex){

        $MODEL=Inventory::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }catch(\Error $ex){


        $MODEL=Inventory::class;
        DB::rollBack();
        Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
        return back();

        }


        }

        public function PostEditInventory($id,InventoryRequest $request){

        try {
        DB::beginTransaction();

        $del=Inventory::find($id);

        Inventory::where('id',$id)->update(['Edit'=>1,'Edit_New_Code'=>request('Code')]);




        $validated = $request->validated();

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

        array(


        'Date' => request('Date'),
        'Draw' => request('Draw'),
        'Note' => request('Note'),
        'Total_Dificit' => request('Total_Dificit'),
        'Total_Excess' => request('Total_Excess'),
        'Total_Dificit_Price' => request('Total_Dificit_Price'),
        'Total_Excess_Price' => request('Total_Excess_Price'),
        'Account_Excess' => request('Account_Excess'),
        'Account_Dificit' => request('Account_Dificit'),
        'Store' => request('Store'),
        'Coin' => request('Coin'),
        'Settle' => 0,
        'User' => auth()->guard('admin')->user()->id,


        )
        );


        if(!empty(request('Unit'))){

        $Unit=request('Unit');
        $P_Code=request('P_Code');
        $P_Price=request('Price');
        $P_Qty=request('Qty');
        $P_Inventory=request('Inventory');
        $P_Dificit=request('Dificit');
        $P_Excess=request('Excess');
        $P_Product=request('Product');
        $P_VOne=request('VOne');
        $P_VTwo=request('VTwo');
        $TotalDificitP=request('TotalDificitP');
        $TotalExcessP=request('TotalExcessP');
        $Exp_Date=request('Exp_Date');

        for($i=0 ; $i < count($Unit) ; $i++){ $uu['Inv_ID']=$ID; $uu['P_Code']=$P_Code[$i]; $uu['Av_Qty']=$P_Qty[$i]; $uu['Inventory']=$P_Inventory[$i]; $uu['Deficit']=$P_Dificit[$i]; $uu['Excess']=$P_Excess[$i]; $uu['Product']=$P_Product[$i]; $uu['V1']=$P_VOne[$i]; $uu['V2']=$P_VTwo[$i]; $uu['Unit']=$Unit[$i]; $uu['Price']=$P_Price[$i]; $uu['TotalDificitP']=$TotalDificitP[$i]; $uu['TotalExcessP']=$TotalExcessP[$i]; $uu['Exp_Date']=$Exp_Date[$i]; ProductInventory::create($uu); } } $dataUser=[ 'screen_ar'=>'الجرد',
            'screen_en'=>'Inventory',
            'explain_ar'=>request('Old_Code'),
            'explain_en'=>request('Old_Code'),
            ];
            $this->UserUpdateMoves($dataUser);

            DB::commit();

            session()->flash('success',trans('admin.Updated'));
            return redirect('Inventory_Sechdule');


            }catch(\Exception $ex){

            $MODEL=Inventory::class;
            DB::rollBack();
            Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

            }catch(\Error $ex){


            $MODEL=Inventory::class;
            DB::rollBack();
            Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

            }


            }


            //Filters
            function InventoryFilter(Request $request,Average $average,StoresService $service)
            {

            if($request->ajax())
            {
            $output = '';
            $search = $request->get('search');
            $store = $request->get('store');
            $Brand = $request->get('Brandd');
            $Group = $request->get('Groupp');
            $PriceType = $request->get('pricee');

            if($search != '' or $store != '' or $Brand != '' or $Group != '')
            {

            if($search != ''){
            $Prods=$this->FilterSalesProductQty($search,$store,$Brand,$Group);
            }elseif($Brand != '' or $Group != '' or $store != ''){
            $Prods=ProductsQty::take(500)->get();
            }


            }
            $total_row = $Prods->count();
            if($total_row > 0)
            {



            $Def=SalesDefaultData::orderBy('id','desc')->first();
            $showw=DefaultDataShowHide::orderBy('id','desc')->first();
            $st = Stores::find($store);

            foreach($Prods as $rows){

                if(is_numeric($search)){

                    $rr = ProductUnits::where('Product', $rows->Product)->where('Barcode', $search)->first();
                }else {
                    $rr = ProductUnits::where('Product', $rows->Product)->where('Def', 1)->first();
                }

                $plow=ProductUnits::where('Product',$rows->Product)->where('Rate',1)->first();


            if(!empty($rows->Product()->first()->Brand)){

            $branddX=$rows->Product()->first()->Brand;
            if(app()->getLocale() == 'ar' ){
            $brandd=$rows->Product()->first()->Brand()->first()->Name;

            }else{
            $brandd=$rows->Product()->first()->Brand()->first()->NameEn;
            }

            }else{

            $brandd="";
            $branddX="";

            }


            if($showw->Group_Brand == 1){

            if(app()->getLocale() == 'ar' ){
            $ShowGrBr= '('.$brandd.') ('.$rows->Product()->first()->Group()->first()->Name.') ';
            }else{

            $ShowGrBr= '('.$brandd.') ('.$rows->Product()->first()->Group()->first()->NameEn.') ';
            }
            }else{
            $ShowGrBr='';
            }


            if(app()->getLocale() == 'ar' ){
            $PrrroName=$rows->P_Ar_Name;
            $UniiName=$rr->Unit()->first()->Name;
            $StoreNemo=$st->Name;

            }else{
            $PrrroName=$rows->P_En_Name;
            $UniiName=$rr->Unit()->first()->NameEn;
            $StoreNemo=$st->NameEn;

            }



            if($rows->Product()->first()->P_Type == 'Completed' or $rows->Product()->first()->P_Type == 'Industrial' or $rows->Product()->first()->P_Type == 'Additions'){
            $type=1;
            $v_name='';
            $vv_name='';
            $serial=0;
            $p_code=$rr->Barcode;
            }elseif($rows->Product()->first()->P_Type == 'Serial'){
            $type=2;
            $v_name='';
            $vv_name='';
            $serial=1;
            $p_code= $rows->P_Code;
            }elseif($rows->Product()->first()->P_Type == 'Single_Variable'){

            if(app()->getLocale() == 'ar' ){
            $PrrroVName=$rows->V1()->first()->Name;

            }else{
            $PrrroVName=$rows->V1()->first()->NameEn;

            }

            $type=3;
            $v_name=$PrrroVName;
            $vv_name='';
            $serial=0;
            $p_code= $rows->P_Code;
            }elseif($rows->Product()->first()->P_Type == 'Duble_Variable'){


            if(app()->getLocale() == 'ar' ){
            $PrrroVName=$rows->V1()->first()->Name;
            $PrrroVVName=$rows->V2()->first()->Name;
            }else{
            $PrrroVName=$rows->V1()->first()->NameEn;
            $PrrroVVName=$rows->V2()->first()->NameEn;
            }

            $type=4;
            $v_name=$PrrroVName;
            $vv_name=$PrrroVVName;
            $serial=0;
            $p_code= $rows->P_Code;
            }


            if($PriceType == 'Cost'){
            $Price=$average->AverageCostGetUnit($rows->Product,$rr->Barcode,$store,$rr->Unit);
            }else{
            $Price=$rr->Price;
            }

            if(!empty($Group) and !empty($Brand)){

            if($rows->Product()->first()->Group == $Group and $branddX == $Brand){


            $Filter=[


            'store'=>$store,
            'product'=>$rows->Product,
            'id'=>$rows->id,
            'name_ar'=>$rows->P_Ar_Name,
            'name_en'=>$rows->P_En_Name,
            'v1'=>$rows->V1,
            'v2'=>$rows->V2,
            'type'=>$type,
            'PrrroName'=>$PrrroName,
            'UniiName'=>$UniiName,
            'StoreNemo'=>$StoreNemo,
            'P_Code'=>$p_code,
            'qty'=>$rows->Qty,
            'Original'=>$rows->Original,
            'Patch_Number'=>$rows->Patch_Number,
            'brandd'=>$brandd,
            'ShowGrBr'=>$ShowGrBr,
            'v_name'=>$v_name,
            'vv_name'=>$vv_name,
            'serial'=>$serial,
            'Exp_Date'=>$rows->Exp_Date,
            'pro_store'=>$rows->Store,
            'Price'=>$Price,
                'search'=>$search,

            ];

            $output .=$service->ItemsFilterInventory($Filter);


            }

            }elseif(empty($Group) and !empty($Brand)){


            if( $branddX == $Brand){


            $Filter=[


            'store'=>$store,
            'product'=>$rows->Product,
            'id'=>$rows->id,
            'name_ar'=>$rows->P_Ar_Name,
            'name_en'=>$rows->P_En_Name,
            'v1'=>$rows->V1,
            'v2'=>$rows->V2,
            'type'=>$type,
            'PrrroName'=>$PrrroName,
            'UniiName'=>$UniiName,
            'StoreNemo'=>$StoreNemo,
            'P_Code'=>$p_code,
            'qty'=>$rows->Qty,
            'Original'=>$rows->Original,
            'Patch_Number'=>$rows->Patch_Number,
            'brandd'=>$brandd,
            'ShowGrBr'=>$ShowGrBr,
            'v_name'=>$v_name,
            'vv_name'=>$vv_name,
            'serial'=>$serial,
            'Exp_Date'=>$rows->Exp_Date,
            'pro_store'=>$rows->Store,
            'Price'=>$Price,
                'search'=>$search,
            ];

            $output .=$service->ItemsFilterInventory($Filter);


            }

            }elseif(!empty($Group) and empty($Brand)){


            if($rows->Product()->first()->Group == $Group){




            $Filter=[


            'store'=>$store,
            'product'=>$rows->Product,
            'id'=>$rows->id,
            'name_ar'=>$rows->P_Ar_Name,
            'name_en'=>$rows->P_En_Name,
            'v1'=>$rows->V1,
            'v2'=>$rows->V2,
            'type'=>$type,
            'PrrroName'=>$PrrroName,
            'UniiName'=>$UniiName,
            'StoreNemo'=>$StoreNemo,
            'P_Code'=>$p_code,
            'qty'=>$rows->Qty,
            'Original'=>$rows->Original,
            'Patch_Number'=>$rows->Patch_Number,
            'brandd'=>$brandd,
            'ShowGrBr'=>$ShowGrBr,
            'v_name'=>$v_name,
            'vv_name'=>$vv_name,
            'serial'=>$serial,
            'Exp_Date'=>$rows->Exp_Date,
            'pro_store'=>$rows->Store,
            'Price'=>$Price,
                'search'=>$search,
            ];

            $output .=$service->ItemsFilterInventory($Filter);



            }

            }elseif(empty($Group) and empty($Brand)){



            $Filter=[


            'store'=>$store,
            'id'=>$rows->id,
            'product'=>$rows->Product,
            'name_ar'=>$rows->P_Ar_Name,
            'name_en'=>$rows->P_En_Name,
            'v1'=>$rows->V1,
            'v2'=>$rows->V2,
            'type'=>$type,
            'PrrroName'=>$PrrroName,
            'UniiName'=>$UniiName,
            'StoreNemo'=>$StoreNemo,
            'P_Code'=>$p_code,
            'qty'=>$rows->Qty,
            'Original'=>$rows->Original,
            'Patch_Number'=>$rows->Patch_Number,
            'brandd'=>$brandd,
            'ShowGrBr'=>$ShowGrBr,
            'v_name'=>$v_name,
            'vv_name'=>$vv_name,
            'serial'=>$serial,
            'Exp_Date'=>$rows->Exp_Date,
            'pro_store'=>$rows->Store,
            'Price'=>$Price,
                'search'=>$search,
            ];

            $output .=$service->ItemsFilterInventory($Filter);




            }



            }





            }else
            {
            $output = '
            <div class="col-md-3">'.trans('admin.No_Data_Find').'</div>
            ';
            }
            $data = array(
            'table_data' => $output,
            );
            echo json_encode($data);
            }
            }



    public function UnitNameCodeInventoryFilter(SalesService $service) {

        $states=[];
        $average = new Average ;


        $id=request('id');
        $Pro=request('Pro');
        $code=request('code');
        $Store=request('store');
        $PRORATE=request('PRORATE');
        $pricee=request('pricee');

        $rr = ProductUnits::where("Unit",$id)->where('Product',$Pro)->first();

        $x = $this->ProAvQties($Store,$Pro,$code);

        $price=$average->AverageCostGetUnit($Pro,$code,$Store,$id);

        $PROSS = ProductUnits::where('Product',$Pro)->get();

        $EXPPPP=ExpireDateQty::orderBy('id','desc')->where('Product',$Pro)->where('Store',$Store)->where('P_Code',$code)->first();
        $EXPO='';
        if(!empty($EXPPPP)){
            $EXPO=$this->ExpireAvQtiesCheck($Store,$Pro,$code,$EXPPPP->Exp_Date);
        }


        $COSTpr=$average->AverageCostGetUnit($Pro, $rr->Barcode,$Store,$id);

        if(!empty($x)){
            $Quntity= $x->Qty / $rr->Rate ;
            if(!empty($EXPO)){

                $Quntity=$EXPO->Qty;
            }


            if(app()->getLocale() == 'ar' ){
                $UnitName=$rr->Unit()->first()->Name;
            }else{
                $UnitName=$rr->Unit()->first()->NameEn;
            }

            if($Quntity < 0){

                $Quntity=0;
            }

            if($COSTpr < 0){

                $COSTpr=0;
            }



            $states += [
                "name" => $UnitName ,
                'code' => $rr->Barcode ,
                'price' => $price ,
                'qty' => $Quntity,
                'priceI'=>$rr->Price,
                'priceII'=>$rr->Price_Two,
                'priceIII'=>$rr->Price_Three
            ];





        }else{

            foreach($PROSS as $proo){


                $x = $this->ProAvQtiesUnit($Store,$proo->Product,$proo->Barcode,$id);


                $EXPPPP=ExpireDateQty::orderBy('id','desc')->where('Product',$proo->Product)->where('Store',$Store)->where('P_Code',$proo->Barcode)->first();
                $EXPO='';
                if(!empty($EXPPPP)){

                    $EXPO=$this->ExpireAvQtiesCheck($Store,$proo->Product,$proo->Barcode,$EXPPPP->Exp_Date);

                }

                $COSTpr=$average->AverageCostGet($proo->Product, $proo->Barcode,$Store);


                if(!empty($EXPO)){

                    $Quantity=$EXPO->Qty;
                }

                if(!empty($x)){
                    $Quantity= $x->Qty / $rr->Rate ;
                    if(!empty($EXPO)){

                        $Quantity=$EXPO->Qty;
                    }

                    if(app()->getLocale() == 'ar' ){
                        $UnitName=$proo->Unit()->first()->Name;
                    }else{
                        $UnitName=$proo->Unit()->first()->NameEn;
                    }

                    if($Quantity < 0){

                        $Quantity=0;
                    }

                    if($COSTpr < 0){

                        $COSTpr=0;
                    }




                    $states += [
                        "name" => $UnitName ,
                        'code' => $proo->Barcode ,
                        'price' => $price ,
                        'qty' => $Quantity,
                        'priceI'=>$proo->Price,
                        'priceII'=>$proo->Price_Two,
                        'priceIII'=>$proo->Price_Three
                    ];



                }

            }


        }
        return response()->json($states);

    }


    public function UnitNameCodeInventoryFilterTWO(SalesService $service) {

        $states=[];
        $average = new Average ;



        $id=request('id');
        $Pro=request('Pro');
        $code=request('code');
        $Store=request('store');


        $rr = ProductUnits::where("Unit",$id)->where('Product',$Pro)->first();

        $x = $this->ProAvQties($Store,$Pro,$code);

        $price=$average->AverageCostGetUnit($Pro,$code,$Store,$id);

        $PROSS = ProductUnits::where('Product',$Pro)->get();

        $EXPPPP=ExpireDateQty::orderBy('id','desc')->where('Product',$Pro)->where('Store',$Store)->where('P_Code',$code)->first();
        $EXPO='';
        if(!empty($EXPPPP)){
            $EXPO=$this->ExpireAvQtiesCheck($Store,$Pro,$code,$EXPPPP->Exp_Date);
        }


        $COSTpr=$average->AverageCostGetUnit($Pro, $rr->Barcode,$Store,$id);

        if(!empty($x)){
            $Quntity= $x->Qty / $rr->Rate ;
            if(!empty($EXPO)){

                $Quntity=$EXPO->Qty;
            }


            if(app()->getLocale() == 'ar' ){
                $UnitName=$rr->Unit()->first()->Name;
            }else{
                $UnitName=$rr->Unit()->first()->NameEn;
            }

            if($Quntity < 0){

                $Quntity=0;
            }

            if($COSTpr < 0){

                $COSTpr=0;
            }



            $states += [
                "name" => $UnitName ,
                'code' => $rr->Barcode ,
                'price' => $price ,
                'qty' => $Quntity,
                'priceI'=>$rr->Price,
                'priceII'=>$rr->Price_Two,
                'priceIII'=>$rr->Price_Three
            ];





        }else{

            foreach($PROSS as $proo){


                $x = $this->ProAvQtiesUnit($Store,$proo->Product,$proo->Barcode,$id);


                $EXPPPP=ExpireDateQty::orderBy('id','desc')->where('Product',$proo->Product)->where('Store',$Store)->where('P_Code',$proo->Barcode)->first();
                $EXPO='';
                if(!empty($EXPPPP)){

                    $EXPO=$this->ExpireAvQtiesCheck($Store,$proo->Product,$proo->Barcode,$EXPPPP->Exp_Date);

                }

                $COSTpr=$average->AverageCostGet($proo->Product, $proo->Barcode,$Store);


                if(!empty($EXPO)){

                    $Quantity=$EXPO->Qty;
                }

                if(!empty($x)){
                    $Quantity= $x->Qty / $rr->Rate ;
                    if(!empty($EXPO)){

                        $Quantity=$EXPO->Qty;
                    }

                    if(app()->getLocale() == 'ar' ){
                        $UnitName=$proo->Unit()->first()->Name;
                    }else{
                        $UnitName=$proo->Unit()->first()->NameEn;
                    }

                    if($Quantity < 0){

                        $Quantity=0;
                    }

                    if($COSTpr < 0){

                        $COSTpr=0;
                    }




                    $states += [
                        "name" => $UnitName ,
                        'code' => $proo->Barcode ,
                        'price' => $price ,
                        'qty' => $Quantity,
                        'priceI'=>$proo->Price,
                        'priceII'=>$proo->Price_Two,
                        'priceIII'=>$proo->Price_Three
                    ];



                }

            }


        }
        return response()->json($states);

    }



    public function UnitNameCodeInventoryFilterSalePrice() {


            $id=request('id');
            $Pro=request('Pro');
            $code=request('code');
            $store=request('store');
            $PRORATE=request('PRORATE');

            $Def=StoresDefaultData::orderBy('id','desc')->first();
            $rr = ProductUnits::where("Unit",$id)->where('Product',$Pro)->first();
            $x=$this->ProAvQtiesUnit($store,$Pro,$code,$id);
            $average = new Average ;
            $states=[];
            $price=$rr->Price;


            if(app()->getLocale() == 'ar' ){
            $name=$rr->Unit()->first()->Name;
            }else{
            $name=$rr->Unit()->first()->NameEn;
            }

            if(!empty($x)){

            $Quntity= $x->Qty / $rr->Rate ;
            }else{

            $Quntity=0;

            }



            $states += ["name" => $name ,'code' => $rr->Barcode ,'price' => $price , 'qty' => $Quntity];

            return response()->json($states);

            }




            //Settlement
            public function SettlementInvntory($id){

            $item=Inventory::find($id);
            $Pros=ProductInventory::where('Inv_ID',$item->id)->get();
            $Stores=Stores::type()->get();
            $Coins=Coins::all();
            $Code=$this->ReturnCode(Settlement::class);
            $Def=StoresDefaultData::orderBy('id','desc')->first();
            $show=DefaultDataShowHide::orderBy('id','desc')->first();
            if($item->Settle != 0){
            session()->flash('error',trans('admin.Already_Done'));
            return redirect('Inventory_Sechdule');

            }

            return view('admin.Stores.Settlement',get_defined_vars());
            }

            public function Settlement_SechdulePage(){

            $items=Settlement::orderBy('id','asc')->paginate(100);

            return view('admin.Stores.SettlementSechdule',get_defined_vars());
            }


            public function PostSettlement($id,InventoryRequest $request){

            try {
            DB::beginTransaction();

            $validated = $request->validated();

            Inventory::where('id',$id)->update(['Settle'=>1]);
            $s=Stores::find(request('Store'));

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

            array(

            'Code' => request('Code'),
            'Date' => request('Date'),
            'Draw' => request('Draw'),
            'Note' => request('Note'),
            'Total_Dificit' => request('Total_Dificit'),
            'Total_Excess' => request('Total_Excess'),
            'Total_Dificit_Price' => request('Total_Dificit_Price'),
            'Total_Excess_Price' => request('Total_Excess_Price'),
            'Account_Excess' => request('Account_Excess'),
            'Account_Dificit' => request('Account_Dificit'),
            'Store' => request('Store'),
            'Coin' => request('Coin'),
            'Inv_ID' => $id,
            'Time' =>date("h:i:s a", time()),
            'Branch' => $s->Branch,
            'User' => auth()->guard('admin')->user()->id,


            )
            );



            //Event
            SettlementEvent::dispatch($request->all(),$ID);



            $dataUser=[
            'screen_ar'=>'تسويه',
            'screen_en'=>'Settlement',
            'explain_ar'=>request('Code'),
            'explain_en'=>request('Code'),
            ];
            $this->UserCreateMoves($dataUser);

            DB::commit();

            session()->flash('success',trans('admin.Added_Successfully'));
            return redirect('Settlement_Sechdule');


            }catch(\Exception $ex){

            $MODEL=Settlement::class;
            DB::rollBack();
            Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

            }catch(\Error $ex){


            $MODEL=Settlement::class;
            DB::rollBack();
            Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

            }




            }


    //===== End  Inventory ===========================================================



    // === Consists ========
    public function ConsistsPage(){

    $Stores=Stores::type()->get();
    $Code=$this->ReturnCode(Consists::class);
    $Coins=Coins::all();
    $Brands=Brands::all();
    $ItemsGroups=ItemsGroups::all();
    $Def=StoresDefaultData::orderBy('id','desc')->first();
    $show=DefaultDataShowHide::orderBy('id','desc')->first();


    return view('admin.Stores.Consists',get_defined_vars());
    }

    public function ConsistsSechdule(){

    $items=Consists::paginate(100);

    return view('admin.Stores.ConsistsSechdule',get_defined_vars());
    }

    function ConsistFilter(Request $request,Average $average,StoresService $service)
    {

    if($request->ajax())
    {
    $output = '';
    $search = $request->get('search');
    $store = $request->get('store');
    $PriceType = $request->get('pricee');
    $Brand='';
    $Group='';
    if($search != '' and $store != '')
    {


    $Prods=$this->FilterSalesProductQty($search,$store,$Brand,$Group);

    }
    $total_row = $Prods->count();
    if($total_row > 0)
    {


    $Def=SalesDefaultData::orderBy('id','desc')->first();
    $showw=DefaultDataShowHide::orderBy('id','desc')->first();
    $st = Stores::find($store);

    foreach($Prods as $rows){

        if(is_numeric($search)){

            $rr = ProductUnits::where('Product', $rows->Product)->where('Barcode', $search)->first();
        }else {
            $rr = ProductUnits::where('Product', $rows->Product)->where('Def', 1)->first();
        }


        $plow=ProductUnits::where('Product',$rows->Product)->where('Rate',1)->first();


    if(!empty($rows->Product()->first()->Brand)){

    $branddX=$rows->Product()->first()->Brand;
    if(app()->getLocale() == 'ar' ){
    $brandd=$rows->Product()->first()->Brand()->first()->Name;

    }else{
    $brandd=$rows->Product()->first()->Brand()->first()->NameEn;
    }

    }else{

    $brandd="";
    $branddX="";

    }


    if($showw->Group_Brand == 1){

    if(app()->getLocale() == 'ar' ){
    $ShowGrBr= '('.$brandd.') ('.$rows->Product()->first()->Group()->first()->Name.') ';
    }else{

    $ShowGrBr= '('.$brandd.') ('.$rows->Product()->first()->Group()->first()->NameEn.') ';
    }
    }else{
    $ShowGrBr='';
    }


    if(app()->getLocale() == 'ar' ){
    $PrrroName=$rows->P_Ar_Name;
    $UniiName=$rr->Unit()->first()->Name;
    $StoreNemo=$st->Name;

    }else{
    $PrrroName=$rows->P_En_Name;
    $UniiName=$rr->Unit()->first()->NameEn;
    $StoreNemo=$st->NameEn;

    }



    if($rows->Product()->first()->P_Type == 'Completed' or $rows->Product()->first()->P_Type == 'Industrial' or $rows->Product()->first()->P_Type == 'Additions'){
    $type=1;
    $v_name='';
    $vv_name='';
    $serial=0;
    $p_code=$rr->Barcode;
    }elseif($rows->Product()->first()->P_Type == 'Serial'){
    $type=2;
    $v_name='';
    $vv_name='';
    $serial=1;
    $p_code= $rows->P_Code;
    }elseif($rows->Product()->first()->P_Type == 'Single_Variable'){

    if(app()->getLocale() == 'ar' ){
    $PrrroVName=$rows->V1()->first()->Name;

    }else{
    $PrrroVName=$rows->V1()->first()->NameEn;

    }

    $type=3;
    $v_name=$PrrroVName;
    $vv_name='';
    $serial=0;
    $p_code= $rows->P_Code;
    }elseif($rows->Product()->first()->P_Type == 'Duble_Variable'){


    if(app()->getLocale() == 'ar' ){
    $PrrroVName=$rows->V1()->first()->Name;
    $PrrroVVName=$rows->V2()->first()->Name;
    }else{
    $PrrroVName=$rows->V1()->first()->NameEn;
    $PrrroVVName=$rows->V2()->first()->NameEn;
    }

    $type=4;
    $v_name=$PrrroVName;
    $vv_name=$PrrroVVName;
    $serial=0;
    $p_code= $rows->P_Code;
    }


    if($PriceType == 'Cost'){
    $Price=$average->AverageCostGetUnit($rows->Product,$rr->Barcode,$store,$rr->Unit);
    }else{
    $Price=$rr->Price;
    }



    $Filter=[


    'store'=>$store,
    'product'=>$rows->Product,
    'id'=>$rows->id,
    'name_ar'=>$rows->P_Ar_Name,
    'name_en'=>$rows->P_En_Name,
    'v1'=>$rows->V1,
    'v2'=>$rows->V2,
    'type'=>$type,
    'PrrroName'=>$PrrroName,
    'UniiName'=>$UniiName,
    'StoreNemo'=>$StoreNemo,
    'P_Code'=>$p_code,
    'qty'=>$rows->Qty,
    'Original'=>$rows->Original,
    'Patch_Number'=>$rows->Patch_Number,
    'brandd'=>$brandd,
    'ShowGrBr'=>$ShowGrBr,
    'v_name'=>$v_name,
    'vv_name'=>$vv_name,
    'serial'=>$serial,
    'Exp_Date'=>$rows->Exp_Date,
    'pro_store'=>$rows->Store,
    'Price'=>$Price,
        'search'=>$search,
    ];

    $output .=$service->ItemsFilterConsist($Filter);






    }




    }else
    {
    $output = '
    <div class="col-md-3">'.trans('admin.No_Data_Find').'</div>
    ';
    }
    $data = array(
    'table_data' => $output,
    );
    echo json_encode($data);
    }
    }


    public function AddConsists(Request $request){

    try {
    DB::beginTransaction();


    $data= $this->validate(request(),[
    'Date'=>'required',
    'Store'=>'required',
    'Coin'=>'required',
    'Account'=>'required',
    ],[

    ]);

    $s=Stores::find(request('Store'));

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

    array(

    'Code' => request('Code'),
    'Date' => request('Date'),
    'Darw' => request('Draw'),
    'Products_Number' => request('Products_Number'),
    'Total_Qty' => request('Total_Qty'),
    'Total_Price' => request('Total_Price'),
    'Account' => request('Account'),
    'Store' => request('Store'),
    'Coin' => request('Coin'),
    'User' => auth()->guard('admin')->user()->id,
    'Time' =>date("h:i:s a", time()),
    'Branch' => $s->Branch,

    )
    );



    //Event
    ConsistEvent::dispatch($request->all(),$ID);






    $dataUser=[
    'screen_ar'=>'تالف',
    'screen_en'=>'Consists',
    'explain_ar'=>request('Code'),
    'explain_en'=>request('Code'),
    ];
    $this->UserCreateMoves($dataUser);



    DB::commit();

    session()->flash('success',trans('admin.Added_Successfully'));
    return back();


    }catch(\Exception $ex){

    $MODEL=Consists::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=Consists::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }

    }



    public function DeleteConsist($id,StoresService $service){


    try {
    DB::beginTransaction();

    $del=Consists::find($id);
    Consists::where('id',$id)->update(['Delete'=>1]);



    GeneralDaily::where('Code_Type',$del->Code)->where('Type','تالف')->delete();
    Journalizing::where('Code_Type',$del->Code)->where('Type','تالف')->update(['Delete'=>1]);
    StoresMoves::where('ID',$del->id)->where('Type','تالف')->update(['Delete'=>1]);



    //Service

    $service->RemoveQtiesConsisit($id);


    $dataUser=[
    'screen_ar'=>'تالف',
    'screen_en'=>'Consist',
    'explain_ar'=>$del->Code,
    'explain_en'=>$del->Code,
    ];
    $this->UserDeleteMoves($dataUser);


    DB::commit();
    session()->flash('error',trans('admin.Deleted'));
    return back();



    }catch(\Exception $ex){

    $MODEL=Consists::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=Consists::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }




    }



    // === Samples ========
    public function Samples(){

    $Stores=Stores::type()->get();
    $Code=$this->ReturnCode(Consists::class);
    $Coins=Coins::all();
    $Brands=Brands::all();
    $ItemsGroups=ItemsGroups::all();
    $Def=StoresDefaultData::orderBy('id','desc')->first();
    $show=DefaultDataShowHide::orderBy('id','desc')->first();


    return view('admin.Stores.Sample',get_defined_vars());
    }

    public function SamplesSechdule(){

    $items=Consists::paginate(100);

    return view('admin.Stores.SampleSechdule',get_defined_vars());
    }

    function SamplesFilter(Request $request,Average $average,StoresService $service)
    {

    if($request->ajax())
    {
    $output = '';
    $search = $request->get('search');
    $store = $request->get('store');
    $PriceType = $request->get('pricee');
    $Brand='';
    $Group='';
    if($search != '' and $store != '')
    {


    $Prods=$this->FilterSalesProductQty($search,$store,$Brand,$Group);

    }
    $total_row = $Prods->count();
    if($total_row > 0)
    {


    $Def=SalesDefaultData::orderBy('id','desc')->first();
    $showw=DefaultDataShowHide::orderBy('id','desc')->first();
    $st = Stores::find($store);

    foreach($Prods as $rows){

        if(is_numeric($search)){

            $rr = ProductUnits::where('Product', $rows->Product)->where('Barcode', $search)->first();
        }else {
            $rr = ProductUnits::where('Product', $rows->Product)->where('Def', 1)->first();
        }
    $plow=ProductUnits::where('Product',$rows->Product)->where('Rate',1)->first();


    if(!empty($rows->Product()->first()->Brand)){

    $branddX=$rows->Product()->first()->Brand;
    if(app()->getLocale() == 'ar' ){
    $brandd=$rows->Product()->first()->Brand()->first()->Name;

    }else{
    $brandd=$rows->Product()->first()->Brand()->first()->NameEn;
    }

    }else{

    $brandd="";
    $branddX="";

    }


    if($showw->Group_Brand == 1){

    if(app()->getLocale() == 'ar' ){
    $ShowGrBr= '('.$brandd.') ('.$rows->Product()->first()->Group()->first()->Name.') ';
    }else{

    $ShowGrBr= '('.$brandd.') ('.$rows->Product()->first()->Group()->first()->NameEn.') ';
    }
    }else{
    $ShowGrBr='';
    }


    if(app()->getLocale() == 'ar' ){
    $PrrroName=$rows->P_Ar_Name;
    $UniiName=$rr->Unit()->first()->Name;
    $StoreNemo=$st->Name;

    }else{
    $PrrroName=$rows->P_En_Name;
    $UniiName=$rr->Unit()->first()->NameEn;
    $StoreNemo=$st->NameEn;

    }



    if($rows->Product()->first()->P_Type == 'Completed' or $rows->Product()->first()->P_Type == 'Industrial' or $rows->Product()->first()->P_Type == 'Additions'){
    $type=1;
    $v_name='';
    $vv_name='';
    $serial=0;
    $p_code=$rr->Barcode;
    }elseif($rows->Product()->first()->P_Type == 'Serial'){
    $type=2;
    $v_name='';
    $vv_name='';
    $serial=1;
    $p_code= $rows->P_Code;
    }elseif($rows->Product()->first()->P_Type == 'Single_Variable'){

    if(app()->getLocale() == 'ar' ){
    $PrrroVName=$rows->V1()->first()->Name;

    }else{
    $PrrroVName=$rows->V1()->first()->NameEn;

    }

    $type=3;
    $v_name=$PrrroVName;
    $vv_name='';
    $serial=0;
    $p_code= $rows->P_Code;
    }elseif($rows->Product()->first()->P_Type == 'Duble_Variable'){


    if(app()->getLocale() == 'ar' ){
    $PrrroVName=$rows->V1()->first()->Name;
    $PrrroVVName=$rows->V2()->first()->Name;
    }else{
    $PrrroVName=$rows->V1()->first()->NameEn;
    $PrrroVVName=$rows->V2()->first()->NameEn;
    }

    $type=4;
    $v_name=$PrrroVName;
    $vv_name=$PrrroVVName;
    $serial=0;
    $p_code= $rows->P_Code;
    }


    if($PriceType == 'Cost'){
    $Price=$average->AverageCostGetUnit($rows->Product,$rr->Barcode,$store,$rr->Unit);
    }else{
    $Price=$rr->Price;
    }



    $Filter=[


    'store'=>$store,
    'product'=>$rows->Product,
    'id'=>$rows->id,
    'name_ar'=>$rows->P_Ar_Name,
    'name_en'=>$rows->P_En_Name,
    'v1'=>$rows->V1,
    'v2'=>$rows->V2,
    'type'=>$type,
    'PrrroName'=>$PrrroName,
    'UniiName'=>$UniiName,
    'StoreNemo'=>$StoreNemo,
    'P_Code'=>$p_code,
    'qty'=>$rows->Qty,
    'Original'=>$rows->Original,
    'Patch_Number'=>$rows->Patch_Number,
    'brandd'=>$brandd,
    'ShowGrBr'=>$ShowGrBr,
    'v_name'=>$v_name,
    'vv_name'=>$vv_name,
    'serial'=>$serial,
    'Exp_Date'=>$rows->Exp_Date,
    'pro_store'=>$rows->Store,
    'Price'=>$Price,
        'search'=>$search,
    ];

    $output .=$service->ItemsFilterConsist($Filter);






    }




    }else
    {
    $output = '
    <div class="col-md-3">'.trans('admin.No_Data_Find').'</div>
    ';
    }
    $data = array(
    'table_data' => $output,
    );
    echo json_encode($data);
    }
    }


    public function AddSamples(Request $request){

    try {
    DB::beginTransaction();


    $data= $this->validate(request(),[
    'Date'=>'required',
    'Store'=>'required',
    'Coin'=>'required',
    'Account'=>'required',
    ],[

    ]);

    $s=Stores::find(request('Store'));

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

    array(

    'Code' => request('Code'),
    'Date' => request('Date'),
    'Darw' => request('Draw'),
    'Products_Number' => request('Products_Number'),
    'Total_Qty' => request('Total_Qty'),
    'Total_Price' => request('Total_Price'),
    'Account' => request('Account'),
    'Store' => request('Store'),
    'Coin' => request('Coin'),
    'User' => auth()->guard('admin')->user()->id,
    'Time' =>date("h:i:s a", time()),
    'Branch' => $s->Branch,

    )
    );



    ConsistEvent::dispatch($request->all(),$ID);


    $dataUser=[
    'screen_ar'=>'العينات',
    'screen_en'=>'Samples',
    'explain_ar'=>request('Code'),
    'explain_en'=>request('Code'),
    ];
    $this->UserCreateMoves($dataUser);



    DB::commit();

    session()->flash('success',trans('admin.Added_Successfully'));
    return back();


    }catch(\Exception $ex){

    $MODEL=Consists::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=Consists::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }

    }




//========================================================

    //==== Stores Transfers ===
    public function StoresTransfersPage(){

         $StoresFrom=Stores::type()->get();
         $Code=$this->ReturnCode(StorsTransfers::class);
         $Coins=Coins::all();
         $Brands=Brands::all();
         $ItemsGroups=ItemsGroups::all();
         $Def=StoresDefaultData::orderBy('id','desc')->first();
         $show=DefaultDataShowHide::orderBy('id','desc')->first();
         $Stores=Stores::all();
         $Shippings=ShippingCompany::all();
         $Emps = Employess::type()->lazy();
         $Branches=Branches::all();
         return view('admin.Stores.StoresTransfers',get_defined_vars());
    }

      public function TransferSure($id){


              $item=StorsTransfers::find($id);
              $Pros=ProductsStoresTransfers::where('ST_ID',$item->id)->get();

              $Stores=Stores::all();
              $Coins=Coins::all();

              $Shippings=ShippingCompany::all();
              $Emps = Employess::type()->lazy();
              $Branches=Branches::all();

              if($item->Status != 0){
              session()->flash('error',trans('admin.Already_Done'));
              return redirect('StoresTransfersSechdule');

              }
         return view('admin.Stores.SureStoresTransfers',get_defined_vars());
    }

      public function ShippingTransferRecived($id){

         $Stores=Stores::all();
         $Coins=Coins::all();
        $item=StorsTransfers::find($id);
           $Pros=ProductsStoresTransfers::where('ST_ID',$item->id)->get();
           $Shippings=ShippingCompany::all();
         $Safes = AcccountingManual::where('Type',1)->safetype()->lazy();

         return view('admin.Stores.ShippingTransferRecived',get_defined_vars());
    }

      public function StoresTransfersSechdulePage(){

         $items=StorsTransfers::latest('id')->type()->paginate(100);

         return view('admin.Stores.StoresTransfersSechdule',get_defined_vars());
    }

     public function StoresTransferPrint($id){

         $item=StorsTransfers::find($id);
         $Pros=ProductsStoresTransfers::where('ST_ID',$id)->get();

         return view('admin.Stores.StoresTransfersPrint',get_defined_vars());
    }

        public function EditStoreTransfer($id){

             $item=StorsTransfers::find($id);
             $Pros=ProductsStoresTransfers::where('ST_ID',$item->id)->get();
             $Stores=Stores::all();
             $Coins=Coins::all();
             $Shippings=ShippingCompany::all();
             $Emps = Employess::type()->lazy();
             $Branches=Branches::all();
               $Def=StoresDefaultData::orderBy('id','desc')->first();
         $show=DefaultDataShowHide::orderBy('id','desc')->first();
              $Code=$this->ReturnCode(StorsTransfers::class);
             if($item->Status != 0){
             session()->flash('error',trans('admin.Already_Done'));
             return redirect('StoresTransfersSechdule');

             }
         return view('admin.Stores.EditStoresTransfers',get_defined_vars());
    }


     public function RefusedStoreTransfer($id){

          try {
    DB::beginTransaction();

        StorsTransfers::where('id',$id)->update(['Status'=>2]);
  DB::commit();
        session()->flash('error',trans('admin.Refused'));
        return back();

             }catch(\Exception $ex){

     $MODEL=StorsTransfers::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

           session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }catch(\Error $ex){


             $MODEL=StorsTransfers::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }


           }


    //Filters
     function TarnsferStoresFilter(Request $request,StoresService $service)
             {

     if($request->ajax())
     {
      $output = '';
      $search = $request->get('search');
      $store = $request->get('store');
      $Brand = $request->get('Brand');
      $Group = $request->get('Group');
      $TypeTransfer = $request->get('TypeTransfer');
      $OtherType = $request->get('Cost_Store');
      $Tostore = $request->get('TOSTORE');

    if($search != '' or $store != '' or $Brand != '' or $Group != '' )
    {

         if($search != ''){


                           $DefSHOW=DefaultDataShowHide::orderBy('id','desc')->first();
        if($DefSHOW->Search_Typical ==  1){

                      $Prods=ProductsQty::
            where('P_Ar_Name','ILIKE', "%{$search}%")
            ->orWhere('P_En_Name','ILIKE', "%{$search}%")
            ->orWhere('V_Name','ILIKE', "%{$search}%")
            ->orWhere('VV_Name','ILIKE', "%{$search}%")
            ->orWhere('P_Code',$search)
            ->orWhere('PP_Code',$search)
            ->orWhere('PPP_Code',$search)
            ->orWhere('PPPP_Code',$search)
          ->take(100)
          ->get();

  }else{

              $Prods=ProductsQty::
            where('P_Ar_Name','ILIKE', "%{$search}%")
            ->orWhere('P_En_Name','ILIKE', "%{$search}%")
            ->orWhere('V_Name','ILIKE', "%{$search}%")
            ->orWhere('VV_Name','ILIKE', "%{$search}%")
            ->orWhere('P_Code','ILIKE', "%{$search}%")
            ->orWhere('PP_Code','ILIKE', "%{$search}%")
            ->orWhere('PPP_Code','ILIKE', "%{$search}%")
            ->orWhere('PPPP_Code','ILIKE', "%{$search}%")
          ->take(100)
          ->get();

  }




         }else{

                        $Prods=ProductsQty::where('Qty','!=',0)->paginate(20);


         }



     }
         $total_row = $Prods->count();
      if($total_row > 0)
      {



         $Def=SalesDefaultData::orderBy('id','desc')->first();
            $showw=DefaultDataShowHide::orderBy('id','desc')->first();
            $st = Stores::find($store);

            foreach($Prods as $rows){

                if(is_numeric($search)){

                    $rr = ProductUnits::where('Product', $rows->Product)->where('Barcode', $search)->first();
                }else {
                    $rr = ProductUnits::where('Product', $rows->Product)->where('Def', 1)->first();
                }

                $plow=ProductUnits::where('Product',$rows->Product)->where('Rate',1)->first();


            if(!empty($rows->Product()->first()->Brand)){

            $branddX=$rows->Product()->first()->Brand;
            if(app()->getLocale() == 'ar' ){
            $brandd=$rows->Product()->first()->Brand()->first()->Name;

            }else{
            $brandd=$rows->Product()->first()->Brand()->first()->NameEn;
            }

            }else{

            $brandd="";
            $branddX="";

            }


            if($showw->Group_Brand == 1){

            if(app()->getLocale() == 'ar' ){
            $ShowGrBr= '('.$brandd.') ('.$rows->Product()->first()->Group()->first()->Name.') ';
            }else{

            $ShowGrBr= '('.$brandd.') ('.$rows->Product()->first()->Group()->first()->NameEn.') ';
            }
            }else{
            $ShowGrBr='';
            }


            if(app()->getLocale() == 'ar' ){
            $PrrroName=$rows->P_Ar_Name;
            $UniiName=$rr->Unit()->first()->Name;
            $StoreNemo=$st->Name;

            }else{
            $PrrroName=$rows->P_En_Name;
            $UniiName=$rr->Unit()->first()->NameEn;
            $StoreNemo=$st->NameEn;

            }



            if($rows->Product()->first()->P_Type == 'Completed' or $rows->Product()->first()->P_Type == 'Industrial' or $rows->Product()->first()->P_Type == 'Additions'){
            $type=1;
            $v_name='';
            $vv_name='';
            $serial=0;
            $p_code=$rr->Barcode;
            }elseif($rows->Product()->first()->P_Type == 'Serial'){
            $type=2;
            $v_name='';
            $vv_name='';
            $serial=1;
            $p_code= $rows->P_Code;
            }elseif($rows->Product()->first()->P_Type == 'Single_Variable'){

            if(app()->getLocale() == 'ar' ){
            $PrrroVName=$rows->V1()->first()->Name;

            }else{
            $PrrroVName=$rows->V1()->first()->NameEn;

            }

            $type=3;
            $v_name=$PrrroVName;
            $vv_name='';
            $serial=0;
            $p_code= $rows->P_Code;
            }elseif($rows->Product()->first()->P_Type == 'Duble_Variable'){


            if(app()->getLocale() == 'ar' ){
            $PrrroVName=$rows->V1()->first()->Name;
            $PrrroVVName=$rows->V2()->first()->Name;
            }else{
            $PrrroVName=$rows->V1()->first()->NameEn;
            $PrrroVVName=$rows->V2()->first()->NameEn;
            }

            $type=4;
            $v_name=$PrrroVName;
            $vv_name=$PrrroVVName;
            $serial=0;
            $p_code= $rows->P_Code;
            }



            if(!empty($Group) and !empty($Brand)){

            if($rows->Product()->first()->Group == $Group and $branddX == $Brand){


            $Filter=[


            'store'=>$store,
            'product'=>$rows->Product,
            'id'=>$rows->id,
            'name_ar'=>$rows->P_Ar_Name,
            'name_en'=>$rows->P_En_Name,
            'v1'=>$rows->V1,
            'v2'=>$rows->V2,
            'type'=>$type,
            'PrrroName'=>$PrrroName,
            'UniiName'=>$UniiName,
            'StoreNemo'=>$StoreNemo,
            'P_Code'=>$p_code,
            'qty'=>$rows->Qty,
            'Original'=>$rows->Original,
            'Patch_Number'=>$rows->Patch_Number,
            'brandd'=>$brandd,
            'ShowGrBr'=>$ShowGrBr,
            'v_name'=>$v_name,
            'vv_name'=>$vv_name,
            'serial'=>$serial,
            'Exp_Date'=>$rows->Exp_Date,
            'pro_store'=>$rows->Store,
            'TypeTransfer'=>$TypeTransfer,
            'OtherType'=>$OtherType,
            'Tostore'=>$Tostore,
                'search'=>$search,

            ];

            $output .=$service->ItemsFilterStoresTransfer($Filter);


            }

            }elseif(empty($Group) and !empty($Brand)){


            if( $branddX == $Brand){


            $Filter=[


            'store'=>$store,
            'product'=>$rows->Product,
            'id'=>$rows->id,
            'name_ar'=>$rows->P_Ar_Name,
            'name_en'=>$rows->P_En_Name,
            'v1'=>$rows->V1,
            'v2'=>$rows->V2,
            'type'=>$type,
            'PrrroName'=>$PrrroName,
            'UniiName'=>$UniiName,
            'StoreNemo'=>$StoreNemo,
            'P_Code'=>$p_code,
            'qty'=>$rows->Qty,
            'Original'=>$rows->Original,
            'Patch_Number'=>$rows->Patch_Number,
            'brandd'=>$brandd,
            'ShowGrBr'=>$ShowGrBr,
            'v_name'=>$v_name,
            'vv_name'=>$vv_name,
            'serial'=>$serial,
            'Exp_Date'=>$rows->Exp_Date,
            'pro_store'=>$rows->Store,
               'TypeTransfer'=>$TypeTransfer,
            'OtherType'=>$OtherType,
            'Tostore'=>$Tostore,
                'search'=>$search,
            ];

            $output .=$service->ItemsFilterStoresTransfer($Filter);


            }

            }elseif(!empty($Group) and empty($Brand)){


            if($rows->Product()->first()->Group == $Group){




            $Filter=[


            'store'=>$store,
            'product'=>$rows->Product,
            'id'=>$rows->id,
            'name_ar'=>$rows->P_Ar_Name,
            'name_en'=>$rows->P_En_Name,
            'v1'=>$rows->V1,
            'v2'=>$rows->V2,
            'type'=>$type,
            'PrrroName'=>$PrrroName,
            'UniiName'=>$UniiName,
            'StoreNemo'=>$StoreNemo,
            'P_Code'=>$p_code,
            'qty'=>$rows->Qty,
            'Original'=>$rows->Original,
            'Patch_Number'=>$rows->Patch_Number,
            'brandd'=>$brandd,
            'ShowGrBr'=>$ShowGrBr,
            'v_name'=>$v_name,
            'vv_name'=>$vv_name,
            'serial'=>$serial,
            'Exp_Date'=>$rows->Exp_Date,
            'pro_store'=>$rows->Store,
               'TypeTransfer'=>$TypeTransfer,
            'OtherType'=>$OtherType,
            'Tostore'=>$Tostore,
                'search'=>$search,
            ];

            $output .=$service->ItemsFilterStoresTransfer($Filter);



            }

            }elseif(empty($Group) and empty($Brand)){



            $Filter=[


            'store'=>$store,
            'id'=>$rows->id,
            'product'=>$rows->Product,
            'name_ar'=>$rows->P_Ar_Name,
            'name_en'=>$rows->P_En_Name,
            'v1'=>$rows->V1,
            'v2'=>$rows->V2,
            'type'=>$type,
            'PrrroName'=>$PrrroName,
            'UniiName'=>$UniiName,
            'StoreNemo'=>$StoreNemo,
            'P_Code'=>$p_code,
            'qty'=>$rows->Qty,
            'Original'=>$rows->Original,
            'Patch_Number'=>$rows->Patch_Number,
            'brandd'=>$brandd,
            'ShowGrBr'=>$ShowGrBr,
            'v_name'=>$v_name,
            'vv_name'=>$vv_name,
            'serial'=>$serial,
            'Exp_Date'=>$rows->Exp_Date,
            'pro_store'=>$rows->Store,
               'TypeTransfer'=>$TypeTransfer,
            'OtherType'=>$OtherType,
            'Tostore'=>$Tostore,
                'search'=>$search,
            ];

            $output .=$service->ItemsFilterStoresTransfer($Filter);




            }



            }


      }else
      {
       $output = '
        <div class="col-md-3">'.trans('admin.No_Data_Find').'</div>
       ';
      }
      $data = array(
       'table_data'  => $output,
      );
      echo json_encode($data);
     }
    }

            public function UnitNameCodeStoresTransferFilter() {

            $id=request('id');
            $Pro=request('Pro');
            $code=request('code');
            $store=request('store');
            $PRORATE=request('PRORATE');
            $pricee=request('pricee');

            $Def=StoresDefaultData::orderBy('id','desc')->first();
            $rr = ProductUnits::where("Unit",$id)->where('Product',$Pro)->first();
            $x=$this->ProAvQties($store,$Pro,$code);


            $average = new Average ;
            $states=[];

  $Def=StoresDefaultData::orderBy('id','desc')->first();
           if($Def->StoresTarnsferPrice == 0){

            //سعر التكلفه
            $price=$average->AverageCostGetUnit($Pro,$code,$store,$id);

         }elseif($Def->StoresTarnsferPrice == 1){
            //سعر البيع
            $price=$rr->Price;

            }

            if(app()->getLocale() == 'ar' ){
            $name=$rr->Unit()->first()->Name;
            }else{
            $name=$rr->Unit()->first()->NameEn;
            }



           $EXPPPP=ExpireDateQty::orderBy('id','desc')->where('Product',$Pro)->where('Store',$store)->where('P_Code',$code)->first();
             $EXPO='';
             if(!empty($EXPPPP)){
             $EXPO=$this->ExpireAvQtiesCheck($store,$Pro,$code,$EXPPPP->Exp_Date);
             }



             if(!empty($x)){
             $Quntity= $x->Qty / $rr->Rate ;
             }
             if(!empty($EXPO)){

             $Quntity=$EXPO->Qty;
             }

            if(empty($Quntity)){
                $Quntity=0;
            }
                $cost_price=$average->AverageCostGetUnit($Pro,$code,$store,$id);
            $states += [
            "name" => $name ,
            'code' => $rr->Barcode ,
            'price' => $price ,
            'qty' => $Quntity,
            'priceI'=>$rr->Price,
            'priceII'=>$rr->Price_Two,
            'priceIII'=>$rr->Price_Three,
            'cost'=>$cost_price
            ];



            return response()->json($states);

            }

            public function UnitNameCodeStoresTransferFilterTWO() {

            $id=request('id');
            $Pro=request('Pro');
            $code=request('code');
            $store=request('store');
            $small=request('small');

            $Def=StoresDefaultData::orderBy('id','desc')->first();
            $plow=ProductUnits::where('Product',$Pro)->where('Rate',1)->first();
            $rr = ProductUnits::where("Unit",$id)->where('Product',$Pro)->first();
            $x=$this->ProAvQtiesUnit($store,$Pro,$plow->Barcode,$id);
            $average = new Average ;
            $states=[];



            $price=$average->AverageCostGetUnit($Pro,$plow->Barcode,$store,$id);
            $PROSS = ProductUnits::where('Product',$Pro)->get();

            if(app()->getLocale() == 'ar' ){
            $name=$rr->Unit()->first()->Name;
            }else{
            $name=$rr->Unit()->first()->NameEn;
            }


            if(!empty($x)){


            $Quntity= $x->Qty / $rr->Rate ;
            $price= $price * $rr->Rate ;


            $states += ["name" => $name,'code' => $rr->Barcode ,'price' => $price , 'qty' => $Quntity];


            }else{

            foreach($PROSS as $proo){


            $x=$this->ProAvQtiesUnit($store,$proo->Product,$proo->Barcode,$id);

            if(app()->getLocale() == 'ar' ){
            $name=$proo->Unit()->first()->Name;
            }else{
            $name=$proo->Unit()->first()->NameEn;
            }

            if(!empty($x)){
            $Quntity= $x->Qty / $proo->Rate ;
            $price= $small * $proo->Rate ;


            $states += ["name" => $name ,'code' => $proo->Barcode ,'price' => $price , 'qty' => $Quntity];


            }

            }


            }



            return response()->json($states);

            }

     public function StoreClientAccount(Request $request){

              $from = $request->get('FS');
              $to = $request->get('TS');
              $i=0;
              $ii=0;

              $x=Stores::find($from);
              $y=Stores::find($to);

              if(!empty($x)){

              if(!empty($x->Account_Client)){
              $i=1;

              }


              }

              if(!empty($y)){

              if(!empty($y->Account_Client)){
              $ii=1;

              }


              }


              $z=$i + $ii ;

              $states=['Account'=>$z];
              return response()->json($states);

    }


    //===============


      public function AddStoresTransfers(StoresTransferRequest $request){

      try {
    DB::beginTransaction();


           $validated = $request->validated();


           $image=request()->file('File');
           $zFile=$this->UploadFile($image);
           if(!empty($zFile)){

                 $zFile=$zFile;

             }else{
                 $zFile=null;
             }



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

        array(


            'Date' => request('Date'),
            'Draw' => request('Draw'),
            'Total' => request('Total'),
            'TotalQty' => request('TotalQty'),
            'Total_Cost' => request('Total_Cost'),
            'Note' => request('Note'),
            'From_Store' => request('From_Store'),
            'To_Store' => request('To_Store'),
            'Coin' => request('Coin'),
            'Ship' => request('Ship'),
            'CostShip' => request('CostShip'),
            'Delegate' => request('Delegate'),
            'Branch' => request('Branch'),
            'TypeTransfer' => request('TypeTransfer'),
            'Cost_Store' => request('Cost_Store'),
            'Time' => date("h:i:s a", time()),
            'Status' => 0,
            'Edit' => 0,
            'RecivedShip' => 0,
            'Cost_Center' => null,
            'File' => $zFile,
            'User' => auth()->guard('admin')->user()->id,

        )
    );





         $notii['Date']=date('Y-m-d');
         $notii['Status']=0;
         $notii['Noti_Ar_Name']=' تحويل مخازن يحتاج للتأكيد';
         $notii['Noti_En_Name']='Stores Transfer Need Confirmation';
         $notii['Type']='تحويلات المخازن';
         $notii['TypeEn']='Stores Transfer';
         $notii['Type_Code']=request('Code');
         $notii['Emp']=request('Delegate');
         $notii['Client']=null;
         $notii['Product']=null;
         $notii['Store']=request('To_Store');
         $notii['Safe']=null;
         Notifications::create($notii);

         notify()->warning(trans('admin.StoresTRansfer_Need_Confirmation'));


          if(!empty(request('Unit'))){

              $P_Ar_Name=request('P_Ar_Name');
              $P_En_Name=request('P_En_Name');
              $Unit=request('Unit');
              $P_Code=request('P_Code');
              $Price=request('Price');
              $Qty=request('Qty');
              $Trans_Qty=request('Trans_Qty');
              $TotalP=request('TotalP');
              $Product=request('Product');
              $VOne=request('VOne');
              $VTwo=request('VTwo');
              $V_Name=request('V_Name');
              $VV_Name=request('VV_Name');
              $OldPrice=request('OldPrice');
              $CostPrice=request('CostPrice');
              $Exp_Date=request('Exp_Date');

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

                $uu['ST_ID']=$ID;
                $uu['P_Ar_Name']=$P_Ar_Name[$i];
                $uu['P_En_Name']=$P_En_Name[$i];
                $uu['V_Name']=$V_Name[$i];
                $uu['VV_Name']=$VV_Name[$i];
                $uu['P_Code']=$P_Code[$i];
                $uu['Price']=$Price[$i];
                $uu['Av_Qty']=$Qty[$i];
                $uu['Trans_Qty']=$Trans_Qty[$i];
                $uu['Original_Trans_Qty']=$Trans_Qty[$i];
                $uu['Total']=$TotalP[$i];
                $uu['Product']=$Product[$i];
                $uu['V1']=$VOne[$i];
                $uu['V2']=$VTwo[$i];
                $uu['Unit']=$Unit[$i];
                $uu['OldPrice']=$OldPrice[$i];
                $uu['CostPrice']=$CostPrice[$i];
                $uu['Exp_Date']=$Exp_Date[$i];
                $uu['To_Store']=request('To_Store');

               ProductsStoresTransfers::create($uu);

            }


          }



   $dataUser=[
    'screen_ar'=>'تحويلات المخازن',
    'screen_en'=>'Stores Transfers',
    'explain_ar'=>request('Code'),
    'explain_en'=>request('Code'),
    ];
    $this->UserCreateMoves($dataUser);
            DB::commit();

             session()->flash('success',trans('admin.Added_Successfully'));
       if(request('SP') == 0){  return back(); }elseif(request('SP') == 1){  return redirect('StoresTransferPrint/'.$ID); }

                     }catch(\Exception $ex){

     $MODEL=StorsTransfers::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

           session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }catch(\Error $ex){


             $MODEL=StorsTransfers::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }


    }

     public function DeleteStoresTransfer($id){


     try {
    DB::beginTransaction();

        $del=StorsTransfers::find($id);

         StorsTransfers::where('id',$id)->update(['Delete'=>1]);
         Notifications::where('Type_Code',$del->Code)->where('Type','تحويلات المخازن')->delete();



        $dataUser=[
    'screen_ar'=>'تحويلات المخازن',
    'screen_en'=>'Stores Transfers',
    'explain_ar'=>$del->Code,
    'explain_en'=>$del->Code,
    ];
    $this->UserDeleteMoves($dataUser);
            DB::commit();
        session()->flash('error',trans('admin.Deleted'));
        return back();

            }catch(\Exception $ex){

     $MODEL=StorsTransfers::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

           session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }catch(\Error $ex){


             $MODEL=StorsTransfers::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }


           }

         public function PostEditStoresTransfers($id,StoresTransferRequest $request){


               try {
    DB::beginTransaction();

      $validated = $request->validated();




                $item=StorsTransfers::find($id);
            if($item->Status != 0){
   session()->flash('error',trans('admin.Already_Done'));
               return redirect('StoresTransfersSechdule');

                    }
          StorsTransfers::where('id',$id)->update(['Edit_t'=>1,'Edit_New_Code'=>request('Code')]);


           $image=request()->file('File');
           $zFile=$this->UploadFile($image);
           if(!empty($zFile)){

                 $zFile=$zFile;

             }else{
                 $zFile=null;
             }



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

        array(


            'Date' => request('Date'),
            'Draw' => request('Draw'),
            'Total' => request('Total'),
            'TotalQty' => request('TotalQty'),
            'Total_Cost' => request('Total_Cost'),
            'Note' => request('Note'),
            'From_Store' => request('From_Store'),
            'To_Store' => request('To_Store'),
            'Coin' => request('Coin'),
            'Ship' => request('Ship'),
            'CostShip' => request('CostShip'),
            'Delegate' => request('Delegate'),
            'Branch' => request('Branch'),
            'TypeTransfer' => request('TypeTransfer'),
            'Cost_Store' => request('Cost_Store'),
            'Time' => date("h:i:s a", time()),
            'Status' => 0,
            'Edit' => 0,
            'RecivedShip' => 0,
            'Cost_Center' => null,
            'File' => $zFile,
            'User' => auth()->guard('admin')->user()->id,

        )
    );





         $notii['Date']=date('Y-m-d');
         $notii['Status']=0;
         $notii['Noti_Ar_Name']=' تحويل مخازن يحتاج للتأكيد';
         $notii['Noti_En_Name']='Stores Transfer Need Confirmation';
         $notii['Type']='تحويلات المخازن';
         $notii['TypeEn']='Stores Transfer';
         $notii['Type_Code']=request('Code');
         $notii['Emp']=request('Delegate');
         $notii['Client']=null;
         $notii['Product']=null;
         $notii['Store']=request('To_Store');
         $notii['Safe']=null;
         Notifications::create($notii);

         notify()->warning(trans('admin.StoresTRansfer_Need_Confirmation'));


          if(!empty(request('Unit'))){

              $P_Ar_Name=request('P_Ar_Name');
              $P_En_Name=request('P_En_Name');
              $Unit=request('Unit');
              $P_Code=request('P_Code');
              $Price=request('Price');
              $Qty=request('Qty');
              $Trans_Qty=request('Trans_Qty');
              $TotalP=request('TotalP');
              $Product=request('Product');
              $VOne=request('VOne');
              $VTwo=request('VTwo');
              $V_Name=request('V_Name');
              $VV_Name=request('VV_Name');
              $OldPrice=request('OldPrice');
              $CostPrice=request('CostPrice');
    $Exp_Date=request('Exp_Date');
            for($i=0 ; $i < count($Unit) ; $i++){

                $uu['ST_ID']=$ID;
                $uu['P_Ar_Name']=$P_Ar_Name[$i];
                $uu['P_En_Name']=$P_En_Name[$i];
                $uu['V_Name']=$V_Name[$i];
                $uu['VV_Name']=$VV_Name[$i];
                $uu['P_Code']=$P_Code[$i];
                $uu['Price']=$Price[$i];
                $uu['Av_Qty']=$Qty[$i];
                $uu['Trans_Qty']=$Trans_Qty[$i];
                $uu['Original_Trans_Qty']=$Trans_Qty[$i];
                $uu['Total']=$TotalP[$i];
                $uu['Product']=$Product[$i];
                $uu['V1']=$VOne[$i];
                $uu['V2']=$VTwo[$i];
                $uu['Unit']=$Unit[$i];
                $uu['OldPrice']=$OldPrice[$i];
                $uu['CostPrice']=$CostPrice[$i];
                $uu['To_Store']=request('To_Store');
    $uu['Exp_Date']=$Exp_Date[$i];
               ProductsStoresTransfers::create($uu);

            }


          }



   $dataUser=[
    'screen_ar'=>'تحويلات المخازن',
    'screen_en'=>'Stores Transfers',
    'explain_ar'=>request('Old_Code'),
    'explain_en'=>request('Old_Code'),
    ];
    $this->UserUpdateMoves($dataUser);
            DB::commit();



             session()->flash('success',trans('admin.Updated'));
           return redirect('StoresTransfersSechdule');



                     }catch(\Exception $ex){

     $MODEL=StorsTransfers::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

           session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }catch(\Error $ex){


             $MODEL=StorsTransfers::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }



    }

       public function SureStoresTransfers($id,StoresTransferRequest $request){

      try {
    DB::beginTransaction();


           $validated = $request->validated();

             $item=StorsTransfers::find($id);
       Notifications::where('Type_Code',$item->Code)->where('Type','تحويلات المخازن')->delete();
                     if($item->Status != 0){
   session()->flash('error',trans('admin.Already_Done'));
               return redirect('StoresTransfersSechdule');

                    }

 StorsTransfers::where('id',$id)->update(['Status'=>1]);
          //Create Event
          $result=StoresTransferEvent::dispatch($request->all(),$id,1);



    if($result[0] == 5){
        DB::rollBack();
        session()->flash('error',trans('admin.Not_Enough_Qty'));
        return back();
    }




   $dataUser=[
    'screen_ar'=>'تحويلات المخازن',
    'screen_en'=>'Stores Transfers',
     'type_ar'=>'تأكيد',
     'type_en'=>'Sure',
    'explain_ar'=>request('Code'),
    'explain_en'=>request('Code'),
    ];
    $this->UserCustomMoves($dataUser);
            DB::commit();


             session()->flash('success',trans('admin.Added_Successfully'));
           return redirect('StoresTransfersSechdule');

                   }catch(\Exception $ex){

     $MODEL=StorsTransfers::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

           session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }catch(\Error $ex){


             $MODEL=StorsTransfers::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }


    }

    public function SureRecivedShipStoresTransfers($id,StoresTransferRequest $request){

          try {
    DB::beginTransaction();


           $validated = $request->validated();

           $item=StorsTransfers::find($id);
       Notifications::where('Type_Code',$item->Code)->where('Type','تحويلات المخازن')->delete();
                     if($item->Status != 0){
   session()->flash('error',trans('admin.Already_Done'));
               return redirect('StoresTransfersSechdule');

                    }
 StorsTransfers::where('id',$id)->update(['Status'=>1]);

          //Create Event

              $result=StoresTransferEvent::dispatch($request->all(),$id,1);



              if($result[0] == 5){
                  DB::rollBack();
                  session()->flash('error',trans('admin.Not_Enough_Qty'));
                  return back();
              }


   $dataUser=[
    'screen_ar'=>'تحويلات المخازن',
    'screen_en'=>'Stores Transfers',
     'type_ar'=>'تأكيد',
     'type_en'=>'Sure',
    'explain_ar'=>request('Code'),
    'explain_en'=>request('Code'),
    ];
    $this->UserCustomMoves($dataUser);
            DB::commit();

             session()->flash('success',trans('admin.Added_Successfully'));
           return redirect('StoresTransfersSechdule');


                   }catch(\Exception $ex){

     $MODEL=StorsTransfers::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

           session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }catch(\Error $ex){


             $MODEL=StorsTransfers::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }


    }



    //Return Stores Transfer
      public function Stores_Sales_Transfers_Sechdule(){


        if(auth()->guard('admin')->user()->emp == 0){

        $items=StorsTransfers::orderBy('id','desc')->where('TypeTransfer',1)->whereIn('Status',[1,2])->paginate(100);
        }else{

        if(!empty(auth()->guard('admin')->user()->store)){
        $items=StorsTransfers::orderBy('id','desc')
        ->where('To_Store',auth()->guard('admin')->user()->store)
        ->where('TypeTransfer',1)->whereIn('Status',[1,2])->paginate(100);
        }else{

        $items=StorsTransfers::orderBy('id','desc')->where('TypeTransfer',1)->whereIn('Status',[1,2])->paginate(100);
        }

        }

         return view('admin.Stores.Stores_Sales_Transfers_Sechdule',get_defined_vars());
    }

     public function ReturnStoresTransfer($id){

         $Stores=Stores::all();
         $Coins=Coins::all();
        $item=StorsTransfers::find($id);
           $Pros=ProductsStoresTransfers::where('ST_ID',$item->id)->get();
           $Shippings=ShippingCompany::all();
           $Emps = Employess::type()->lazy();
            $Branches=Branches::all();
         return view('admin.Stores.ReturnStoresTransfers',get_defined_vars());
    }

      public function ReturnStoresTransfersSechdule(){


         $items=ReturnStorsTransfer::orderBy('id','desc')->paginate(100);


         return view('admin.Stores.ReturnStoresTransfersSechdule',get_defined_vars());
    }

    public function ApproveReturnStoresTransfer($id){

         $Stores=Stores::all();
         $Coins=Coins::all();
        $R=ReturnStorsTransfer::find($id);
        $item=StorsTransfers::find($R->OriginalID);
           $Pros=ProductsStoresTransfers::where('ST_ID',$item->id)->get();
           $Shippings=ShippingCompany::all();
       $Emps = Employess::type()->lazy();
            $Branches=Branches::all();
         return view('admin.Stores.ApproveReturnStoresTransfers',get_defined_vars());
    }

      public function ReturnSaleStoresTransfers(StoresTransferRequest $request,Average $avearge){

          try {
              DB::beginTransaction();

              $data= $this->validate(request(),[
             'From_Store'=>'required',
             'To_Store'=>'required',
             'Coin'=>'required',

               ],[

            'From_Store.required' => trans('admin.StoreRequired'),
            'To_Store.required' => trans('admin.StoreRequired'),
            'Coin.required' => trans('admin.CoinRequired'),


         ]);


          $def=StoresDefaultData::orderBy('id','desc')->first();



          if($def->ReturnStoresTransfer == 1){
              $stat=0;

          }else{

              $stat=1;

          }
           $store=Stores::find(request('To_Store'));
            $data['Code'] = request('Code');
            $data['Date'] = request('Date');
            $data['Draw'] = request('Draw');
            $data['Total'] = request('Total');
            $data['TotalQty'] = request('TotalQty');
            $data['Total_Cost'] = request('Total_Cost');
            $data['Note'] = request('Note');
            $data['From_Store'] = request('To_Store');
            $data['To_Store'] = request('From_Store');
            $data['Coin'] = request('Coin');
            $data['Ship'] = request('Ship');
            $data['CostShip'] = request('CostShip');
            $data['Cost_Center'] = null;
            $data['Status'] = $stat;
              $data['Delegate']=request('Delegate');
              $data['TypeTransfer']=request('TypeTransfer');
              $data['Cost_Store']=request('Cost_Store');
            $data['User'] = auth()->guard('admin')->user()->id;
            $data['Branch']=$store->Branch;
            $data['OriginalID']=request('OriginalID');
           ReturnStorsTransfer::create($data);

          $cc=ReturnStorsTransfer::orderBy('id','desc')->first();
          $id=$cc->id;
          if(!empty(request('Unit'))){

              $P_Ar_Name=request('P_Ar_Name');
              $P_En_Name=request('P_En_Name');
              $Unit=request('Unit');
              $P_Code=request('P_Code');
              $Price=request('Price');
              $OldPrice=request('OldPrice');
              $Qty=request('Qty');
              $Trans_Qty=request('Trans_Qty');
              $ReturnQty=request('ReturnQty');
              $OrgTrans_Qty=request('Original_Trans_Qty');
              $TotalP=request('TotalP');
              $Product=request('Product');
              $VOne=request('VOne');
              $VTwo=request('VTwo');
              $V_Name=request('V_Name');
              $VV_Name=request('VV_Name');
                $CostPrice=request('CostPrice');

            for($i=0 ; $i < count($Unit) ; $i++){
                 $pp=ProductUnits::where('Unit',$Unit[$i])->where('Product',$Product[$i])->first();
                 $plow=ProductUnits::where('Product',$Product[$i])->where('Rate',1)->first();
                $uu['ST_ID']=$id;
                $uu['P_Ar_Name']=$P_Ar_Name[$i];
                $uu['P_En_Name']=$P_En_Name[$i];
                $uu['V_Name']=$V_Name[$i];
                $uu['VV_Name']=$VV_Name[$i];
                $uu['P_Code']=$P_Code[$i];
                 $uu['SmallCode']=$plow->Barcode;
                $uu['Price']=$Price[$i];
                $uu['Av_Qty']=$Qty[$i];
                $uu['Trans_Qty']=$Trans_Qty[$i];
                $uu['ReturnQty']=$ReturnQty[$i];
                $uu['Original_Trans_Qty']=$OrgTrans_Qty[$i];
                $uu['SmallTrans_Qty']=$Trans_Qty[$i] * $pp->Rate;
                $uu['Total']=$TotalP[$i];
                $uu['Product']=$Product[$i];
                $uu['V1']=$VOne[$i];
                $uu['V2']=$VTwo[$i];
                $uu['Unit']=$Unit[$i];
                $uu['OldPrice']=$OldPrice[$i];
                $uu['To_Store']=request('From_Store');
                  $uu['CostPrice']=$CostPrice[$i];
               ReturnProductsStoresTransfers::create($uu);


          if($def->ReturnStoresTransfer == 0){

 if(empty(request('Ship'))){
                   $Quantity =ProductsQty::
                where('Store',request('To_Store'))
                ->where('Product',$Product[$i])
                ->where('P_Code',$P_Code[$i])
                ->first();

if(empty($Quantity)){

  $Quantity =ProductsQty::
                where('Store',request('To_Store'))
                ->where('Product',$Product[$i])
                ->where('PP_Code',$P_Code[$i])
                ->first();

if(empty($Quantity)){

  $Quantity =ProductsQty::
                where('Store',request('To_Store'))
                ->where('Product',$Product[$i])
                ->where('PPP_Code',$P_Code[$i])
                ->first();


if(empty($Quantity)){

  $Quantity =ProductsQty::
                where('Store',request('To_Store'))
                ->where('Product',$Product[$i])
                ->where('PPPP_Code',$P_Code[$i])
                ->first();

}



}






}



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


                $QuantityTo =ProductsQty::
                where('Store',request('From_Store'))
                ->where('Product',$Product[$i])
                ->where('P_Code',$P_Code[$i])
                ->first();

if(empty($QuantityTo)){

  $QuantityTo =ProductsQty::
                where('Store',request('From_Store'))
                ->where('Product',$Product[$i])
                ->where('PP_Code',$P_Code[$i])
                ->first();

if(empty($QuantityTo)){

  $QuantityTo =ProductsQty::
                where('Store',request('From_Store'))
                ->where('Product',$Product[$i])
                ->where('PPP_Code',$P_Code[$i])
                ->first();


if(empty($QuantityTo)){

  $QuantityTo =ProductsQty::
                where('Store',request('From_Store'))
                ->where('Product',$Product[$i])
                ->where('PPPP_Code',$P_Code[$i])
                ->first();

}



}






}





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

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

       $purchs=ProductsPurchases::where('Product',$Product[$i])->where('SmallCode',$plow->Barcode)->where('Store',request('To_Store'))->get()->sum('Total_Bf_Tax');

                   $ty= $avearge->AverageCostGetUnit($Product[$i],$plow->Barcode,request('To_Store'),$plow->Unit);


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

                 if($ty != 0){
                   $in=0;
         $out=$qq * $ty ;
         $current=$newqty * $ty ;
                }else{

             $in=0;
         $out=$qq * 1;
         $current=$newqty * 1;

                }




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


                $CostTotalSale=$ty * $newQQty;

     $ty= $avearge->AverageCostGetUnit($Product[$i],$plow->Barcode,request('To_Store'),$plow->Unit);

           $lastOperation=ProductMoves::orderBy('id','desc')->where('P_Code',$P_Code[$i])->where('Product',$Product[$i])->where('Store',request('To_Store'))->first();



         $in=0;
         $out=$CostTotalSale;


      if(!empty($lastOperation)){
      if($lastOperation->Current != 0){
         $current=($lastOperation->Current - $newQQty) *  $ty;
      }else{
          $current=($newQQty) *  $ty;

      }

      }else{
            $current=($newQQty) *  $ty;
      }









                  if(!empty($Quantity)){
                   $old=$Quantity->Qty - $qq ;
                    $cur=$old * $ty ;
                      ProductsQty::where('id',$Quantity->id)->update(['Qty'=>$old,'Price'=>$ty, 'TotalCost'=>$cur]);

                }



          $move['Date']=request('Date');
          $move['Type']='مرتجع تحويل مخازن';
          $move['TypeEn']='Return Stores Transfer';
          $move['Bill_Num']=request('Code');
          $move['Incom']=0;
          $move['Outcom']=$qq;
          $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']=$P_Code[$i];
          $move['Unit']=$Unit[$i];
          $move['QTY']=$ReturnQty[$i];
          $move['Group']=$prooooo->Group;
          $move['Store']=request('To_Store');
          $move['Product']=$Product[$i];
          $move['V1']=$VOne[$i];
          $move['V2']=$VTwo[$i];
          $move['User']=auth()->guard('admin')->user()->id;
      $Sro=Stores::find(request('To_Store'));

                   $move['Brand']=$prooooo->Brand;
          $move['Safe']=null;
          $move['Branch']=$Sro->Branch;
          $move['SalePrice']=null;
          $move['ProductPrice']=null;
       $move['Delegate']=request('Delegate');
          $move['Payment_Method']=null;
              ProductMoves::create($move);



        if(!empty($QuantityTo)){
              $prooooo=Products::find($Product[$i]);
            $New=$QuantityTo->Qty + $qq ;


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


            $ty= $avearge->AverageCostGetUnit($Product[$i],$plow->Barcode,request('From_Store'),$plow->Unit);

          $newqty=$QuantityTo->Qty +  $qq ;
            if($ty != 0){
                   $in=$qq * $ty;
         $out=0;
         $current=$newqty * $ty;
                }else{

             $in=$qq * 1;
         $out=0;
         $current=$newqty * 1;

                }




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

            $ty= $avearge->AverageCostGetUnit($Product[$i],$plow->Barcode,request('From_Store'),$plow->Unit);

                $CostTotalSale=$ty * $newQQty;



           $lastOperation=ProductMoves::orderBy('id','desc')->where('P_Code',$P_Code[$i])->where('Product',$Product[$i])->where('Store',request('From_Store'))->first();



         $in=$CostTotalSale;
         $out=0;



      if(!empty($lastOperation)){
      if($lastOperation->Current != 0){
       $current=($lastOperation->Current + $newQQty) *  $ty;
      }else{
       $current=($newQQty) *  $ty;

      }

      }else{
          $current=($newQQty) *  $ty;
      }









           $cur=$New * $ty ;
  ProductsQty::where('id',$QuantityTo->id)->update(['Qty'=>$New,'Price'=>$ty, 'TotalCost'=>$cur]);



          $move['Date']=request('Date');
          $move['Type']='مرتجع تحويل مخازن';
                 $move['TypeEn']='Return Stores Transfer';
          $move['Bill_Num']=request('Code');
          $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']=$P_Code[$i];
          $move['Unit']=$Unit[$i];
          $move['QTY']=$ReturnQty[$i];
          $move['Group']=$prooooo->Group;;
          $move['Store']=request('From_Store');
          $move['Product']=$Product[$i];
          $move['V1']=$VOne[$i];
          $move['V2']=$VTwo[$i];
          $move['User']=auth()->guard('admin')->user()->id;
             $Sro=Stores::find(request('From_Store'));

                   $move['Brand']=$prooooo->Brand;
          $move['Safe']=null;
          $move['Branch']=$Sro->Branch;
          $move['SalePrice']=null;
          $move['ProductPrice']=null;
              $move['Delegate']=request('Delegate');
          $move['Payment_Method']=null;
              ProductMoves::create($move);


        }

            }





$PS=ProductsStoresTransfers::where('ST_ID',request('OriginalID'))->where('P_Code',$P_Code[$i])->where('Product',$Product[$i])->orderBy('id','desc')->first();

              $VXS['Trans_Qty']=$PS->Trans_Qty -  $ReturnQty[$i] ;


             ProductsStoresTransfers::where('id',$PS->id)->update($VXS);


          }


            }







          }



            if($def->ReturnStoresTransfer == 0){

        $Def=StoresDefaultData::orderBy('id','desc')->first();

         $F=StorsTransfers::find($id);




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

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

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

           }

              $CodeT=$id;
               $Fstore=Stores::find(request('From_Store'));

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

        array(

            'Code' => $Code,
            'Type' => 'تحويلات المخازن',
            'TypeEn' => 'Stores Transfers',
            'Code_Type' => $CodeT,
            'Date' => request('Date'),
            'Draw' => request('Draw'),
            'Coin' => request('Coin'),
            'Cost_Center' => null,
            'Total_Debaitor' => request('Total'),
            'Total_Creditor' => request('Total'),
            'Note' => request('Note'),

        )
    );

$Fstore=Stores::find(request('From_Store'));
    $Tstore=Stores::find(request('To_Store'));       //elly shary

        $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=0;
        $PRODUCTSS['Creditor']=request('Total_Cost');
        $PRODUCTSS['Account']=52;
        $PRODUCTSS['Statement']=null;


         JournalizingDetails::create($PRODUCTSS);

        $Gen['Code']=$Code;
        $Gen['Code_Type']=$CodeT;
        $Gen['Date']=request('Date');
        $Gen['Type']= 'تحويلات المخازن';
        $Gen['TypeEn']='Stores Transfers';
        $Gen['Debitor']=0;
        $Gen['Creditor']=request('Total_Cost');
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * 0;
        $Gen['Creditor_Coin']=request('Draw') * request('Total_Cost');
        $Gen['Account']=52;
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);


        $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=request('Total_Cost');
        $PRODUCTSS['Creditor']=0;
        $PRODUCTSS['Account']=$Fstore->Account;
        $PRODUCTSS['Statement']=null;


         JournalizingDetails::create($PRODUCTSS);

        $Gen['Code']=$Code;
        $Gen['Code_Type']=$CodeT;
        $Gen['Date']=request('Date');
        $Gen['Type']= 'تحويلات المخازن';
        $Gen['TypeEn']='Stores Transfers';
        $Gen['Debitor']=request('Total_Cost');
        $Gen['Creditor']=0;
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * request('Total_Cost');
        $Gen['Creditor_Coin']=request('Draw') * 0;
        $Gen['Account']=$Fstore->Account;
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']= null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);


          $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=0;
        $PRODUCTSS['Creditor']=request('Total');
        $PRODUCTSS['Account']=$Tstore->Account_Client;
        $PRODUCTSS['Statement']=null;


         JournalizingDetails::create($PRODUCTSS);

        $Gen['Code']=$Code;
        $Gen['Code_Type']=$CodeT;
        $Gen['Date']=request('Date');
        $Gen['Type']= 'تحويلات المخازن';
        $Gen['TypeEn']='Stores Transfers';
        $Gen['Debitor']=0;
        $Gen['Creditor']=request('Total');
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * 0;
        $Gen['Creditor_Coin']=request('Draw') * request('Total');
        $Gen['Account']=$Tstore->Account_Client;
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);


          $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=request('Total');
        $PRODUCTSS['Creditor']=0;
        $PRODUCTSS['Account']=49;
        $PRODUCTSS['Statement']=null;


         JournalizingDetails::create($PRODUCTSS);

        $Gen['Code']=$Code;
        $Gen['Code_Type']=$CodeT;
        $Gen['Date']=request('Date');
        $Gen['Type']= 'تحويلات المخازن';
        $Gen['TypeEn']='Stores Transfers';
        $Gen['Debitor']=request('Total');
        $Gen['Creditor']=0;
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * request('Total');
        $Gen['Creditor_Coin']=request('Draw') * 0;
        $Gen['Account']=49;
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']= null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);

        $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=request('Total');
        $PRODUCTSS['Creditor']=0;
        $PRODUCTSS['Account']=$Tstore->Account_Client;
        $PRODUCTSS['Statement']=null;


         JournalizingDetails::create($PRODUCTSS);

        $Gen['Code']=$Code;
        $Gen['Code_Type']=$CodeT;
        $Gen['Date']=request('Date');
        $Gen['Type']= 'تحويلات المخازن';
        $Gen['TypeEn']='Stores Transfers';
        $Gen['Debitor']=request('Total');
        $Gen['Creditor']=0;
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * request('Total');
        $Gen['Creditor_Coin']=request('Draw') * 0;
        $Gen['Account']=$Tstore->Account_Client;
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);




       $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=0;
        $PRODUCTSS['Creditor']=request('Total');
        $PRODUCTSS['Account']=$Tstore->Account;
        $PRODUCTSS['Statement']=null;


         JournalizingDetails::create($PRODUCTSS);

        $Gen['Code']=$Code;
        $Gen['Code_Type']=$CodeT;
        $Gen['Date']=request('Date');
        $Gen['Type']= 'تحويلات المخازن';
        $Gen['TypeEn']='Stores Transfers';
        $Gen['Debitor']=0;
        $Gen['Creditor']=request('Total');
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * 0;
        $Gen['Creditor_Coin']=request('Draw') * request('Total');
        $Gen['Account']=$Tstore->Account;
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);





                $store=Stores::find(request('To_Store'));

        $dataStMove['Date']=date('Y-m-d');
           $dataStMove['Code']=request('Code');
           $dataStMove['Time']=date("h:i:s a", time());
           $dataStMove['Branch']=$store->Branch;
           $dataStMove['Store']=request('From_Store');
           $dataStMove['Safe']=null;
           $dataStMove['Type']='تحويلات مخازن من';
           $dataStMove['TypeEn']='Stores Transfer From';
           $dataStMove['Cost_Center']=null;
           $dataStMove['User']=auth()->guard('admin')->user()->id;
           $dataStMove['Coin']=request('Coin');
           $dataStMove['Note']=request('Note');
           $dataStMove['Total_Qty']=request('TotalQty');
           $dataStMove['Total_Price']=request('Total');
           $dataStMove['Account']=null;
           $dataStMove['Ship']=request('Ship');
           $dataStMove['ID']=$id;
           StoresMoves::create($dataStMove);

             $store=Stores::find(request('From_Store'));

            $dataStMove['Date']=date('Y-m-d');
           $dataStMove['Code']=request('Code');
           $dataStMove['Time']=date("h:i:s a", time());
           $dataStMove['Branch']=$store->Branch;
           $dataStMove['Store']=request('To_Store');
           $dataStMove['Safe']=null;
           $dataStMove['Type']='تحويلات مخازن الي';
           $dataStMove['TypeEn']='Stores Transfer To';
           $dataStMove['Cost_Center']=null;
           $dataStMove['User']=auth()->guard('admin')->user()->id;
           $dataStMove['Coin']=request('Coin');
           $dataStMove['Note']=request('Note');
           $dataStMove['Total_Qty']=request('TotalQty');
           $dataStMove['Total_Price']=request('Total');
           $dataStMove['Account']=null;
           $dataStMove['Ship']=request('Ship');
           $dataStMove['ID']=$id;
           StoresMoves::create($dataStMove);


           $dataUser['User']=auth()->guard('admin')->user()->id;
           $dataUser['Date']=date('Y-m-d');
           $dataUser['Time']=date("h:i:s a", time());
          $dataUser['Screen']='تحويلات المخازن';
           $dataUser['ScreenEn']='Stores Transfers';
           $dataUser['Type']='مرتجع';
           $dataUser['TypeEn']='Return';
           $dataUser['Explain']=request('Code');
           $dataUser['ExplainEn']=request('Code');
           UsersMoves::create($dataUser);
            }



             session()->flash('success',trans('admin.Added_Successfully'));
           return redirect('ReturnStoresTransfersSechdule');


          }catch(\Exception $ex){

              $MODEL=ReturnStorsTransfer::class;
              DB::rollBack();
              Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

              session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
              return back();

          }catch(\Error $ex){


              $MODEL=ReturnStorsTransfer::class;
              DB::rollBack();
              Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

              session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
              return back();

          }


      }

          public function PostApproveReturnSaleStoresTransfers(Average $avearge){

              try {
                  DB::beginTransaction();
        $data= $this->validate(request(),[
             'From_Store'=>'required',
             'To_Store'=>'required',
             'Coin'=>'required',

               ],[

            'From_Store.required' => trans('admin.StoreRequired'),
            'To_Store.required' => trans('admin.StoreRequired'),
            'Coin.required' => trans('admin.CoinRequired'),


         ]);


          $def=StoresDefaultData::orderBy('id','desc')->first();




           $store=Stores::find(request('To_Store'));
            $data['Code'] = request('Code');
            $data['Date'] = request('Date');
            $data['Draw'] = request('Draw');
            $data['Total'] = request('Total');
            $data['TotalQty'] = request('TotalQty');
            $data['Total_Cost'] = request('Total_Cost');
            $data['Note'] = request('Note');
            $data['From_Store'] = request('To_Store');
            $data['To_Store'] = request('From_Store');
            $data['Coin'] = request('Coin');
            $data['Ship'] = request('Ship');
            $data['CostShip'] = request('CostShip');
            $data['Cost_Center'] = null;
            $data['Status'] = 1;
              $data['Delegate']=request('Delegate');
              $data['TypeTransfer']=request('TypeTransfer');
              $data['Cost_Store']=request('Cost_Store');
            $data['User'] = auth()->guard('admin')->user()->id;
            $data['Branch']=$store->Branch;
            $data['OriginalID']=request('OriginalID');
           ReturnStorsTransfer::where('id',request('ID'))->update($data);

          $cc=ReturnStorsTransfer::orderBy('id','desc')->first();
          $id=$cc->id;
          if(!empty(request('Unit'))){

              $P_Ar_Name=request('P_Ar_Name');
              $P_En_Name=request('P_En_Name');
              $Unit=request('Unit');
              $P_Code=request('P_Code');
              $Price=request('Price');
              $OldPrice=request('OldPrice');
              $Qty=request('Qty');
              $Trans_Qty=request('Trans_Qty');
              $ReturnQty=request('ReturnQty');
              $OrgTrans_Qty=request('Original_Trans_Qty');
              $TotalP=request('TotalP');
              $Product=request('Product');
              $VOne=request('VOne');
              $VTwo=request('VTwo');
              $V_Name=request('V_Name');
              $VV_Name=request('VV_Name');
                $CostPrice=request('CostPrice');

            for($i=0 ; $i < count($Unit) ; $i++){
                 $pp=ProductUnits::where('Unit',$Unit[$i])->where('Product',$Product[$i])->first();
                 $plow=ProductUnits::where('Product',$Product[$i])->where('Rate',1)->first();
                $uu['ST_ID']=$id;
                $uu['P_Ar_Name']=$P_Ar_Name[$i];
                $uu['P_En_Name']=$P_En_Name[$i];
                $uu['V_Name']=$V_Name[$i];
                $uu['VV_Name']=$VV_Name[$i];
                $uu['P_Code']=$P_Code[$i];
                 $uu['SmallCode']=$plow->Barcode;
                $uu['Price']=$Price[$i];
                $uu['Av_Qty']=$Qty[$i];
                $uu['Trans_Qty']=$Trans_Qty[$i];
                $uu['ReturnQty']=$ReturnQty[$i];
                $uu['Original_Trans_Qty']=$OrgTrans_Qty[$i];
                $uu['SmallTrans_Qty']=$Trans_Qty[$i] * $pp->Rate;
                $uu['Total']=$TotalP[$i];
                $uu['Product']=$Product[$i];
                $uu['V1']=$VOne[$i];
                $uu['V2']=$VTwo[$i];
                $uu['Unit']=$Unit[$i];
                $uu['OldPrice']=$OldPrice[$i];
                $uu['To_Store']=request('From_Store');
                  $uu['CostPrice']=$CostPrice[$i];
               ReturnProductsStoresTransfers::create($uu);




 if(empty(request('Ship'))){
                   $Quantity =ProductsQty::
                where('Store',request('To_Store'))
                ->where('Product',$Product[$i])
                ->where('P_Code',$P_Code[$i])
                ->first();

if(empty($Quantity)){

  $Quantity =ProductsQty::
                where('Store',request('To_Store'))
                ->where('Product',$Product[$i])
                ->where('PP_Code',$P_Code[$i])
                ->first();

if(empty($Quantity)){

  $Quantity =ProductsQty::
                where('Store',request('To_Store'))
                ->where('Product',$Product[$i])
                ->where('PPP_Code',$P_Code[$i])
                ->first();


if(empty($Quantity)){

  $Quantity =ProductsQty::
                where('Store',request('To_Store'))
                ->where('Product',$Product[$i])
                ->where('PPPP_Code',$P_Code[$i])
                ->first();

}



}






}



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


                $QuantityTo =ProductsQty::
                where('Store',request('From_Store'))
                ->where('Product',$Product[$i])
                ->where('P_Code',$P_Code[$i])
                ->first();

if(empty($QuantityTo)){

  $QuantityTo =ProductsQty::
                where('Store',request('From_Store'))
                ->where('Product',$Product[$i])
                ->where('PP_Code',$P_Code[$i])
                ->first();

if(empty($QuantityTo)){

  $QuantityTo =ProductsQty::
                where('Store',request('From_Store'))
                ->where('Product',$Product[$i])
                ->where('PPP_Code',$P_Code[$i])
                ->first();


if(empty($QuantityTo)){

  $QuantityTo =ProductsQty::
                where('Store',request('From_Store'))
                ->where('Product',$Product[$i])
                ->where('PPPP_Code',$P_Code[$i])
                ->first();

}



}






}





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

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



     $ty= $avearge->AverageCostGetUnit($Product[$i],$plow->Barcode,request('To_Store'),$plow->Unit);

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

                 if($ty != 0){
                   $in=0;
         $out=$qq * $ty ;
         $current=$newqty * $ty ;
                }else{

             $in=0;
         $out=$qq * 1;
         $current=$newqty * 1;

                }




                        $newQQty= $unit->Rate * $ReturnQty[$i] ;
     $ty= $avearge->AverageCostGetUnit($Product[$i],$plow->Barcode,request('To_Store'),$plow->Unit);

                $CostTotalSale=$ty * $newQQty;



           $lastOperation=ProductMoves::orderBy('id','desc')->where('P_Code',$P_Code[$i])->where('Product',$Product[$i])->where('Store',request('To_Store'))->first();



         $in=0;
         $out=$CostTotalSale;



      if(!empty($lastOperation)){
      if($lastOperation->Current != 0){
          $current=($lastOperation->Current - $newQQty) *  $ty;
      }else{
             $current=($newQQty) *  $ty;

      }

      }else{
            $current=($newQQty) *  $ty;
      }









                  if(!empty($Quantity)){
                   $old=$Quantity->Qty - $qq ;
                    $cur=$old * $ty ;
                      ProductsQty::where('id',$Quantity->id)->update(['Qty'=>$old,'Price'=>$ty, 'TotalCost'=>$cur]);

                }



          $move['Date']=request('Date');
          $move['Type']='مرتجع تحويل مخازن';
          $move['TypeEn']='Return Stores Transfer';
          $move['Bill_Num']=request('Code');
          $move['Incom']=0;
          $move['Outcom']=$qq;
          $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']=$P_Code[$i];
          $move['Unit']=$Unit[$i];
          $move['QTY']=$ReturnQty[$i];
          $move['Group']=$prooooo->Group;
          $move['Store']=request('To_Store');
          $move['Product']=$Product[$i];
          $move['V1']=$VOne[$i];
          $move['V2']=$VTwo[$i];
          $move['User']=auth()->guard('admin')->user()->id;
      $Sro=Stores::find(request('To_Store'));

                   $move['Brand']=$prooooo->Brand;
          $move['Safe']=null;
          $move['Branch']=$Sro->Branch;
          $move['SalePrice']=null;
          $move['ProductPrice']=null;
       $move['Delegate']=request('Delegate');
          $move['Payment_Method']=null;
              ProductMoves::create($move);



        if(!empty($QuantityTo)){
              $prooooo=Products::find($Product[$i]);
            $New=$QuantityTo->Qty + $qq ;


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


            $ty= $avearge->AverageCostGetUnit($Product[$i],$plow->Barcode,request('From_Store'),$plow->Unit);

          $newqty=$QuantityTo->Qty +  $qq ;
            if($ty != 0){
                   $in=$qq * $ty;
         $out=0;
         $current=$newqty * $ty;
                }else{

             $in=$qq * 1;
         $out=0;
         $current=$newqty * 1;

                }




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

            $ty= $avearge->AverageCostGetUnit($Product[$i],$plow->Barcode,request('From_Store'),$plow->Unit);


            $CostTotalSale=$ty * $newQQty;



           $lastOperation=ProductMoves::orderBy('id','desc')->where('P_Code',$P_Code[$i])->where('Product',$Product[$i])->where('Store',request('From_Store'))->first();



         $in=$CostTotalSale;
         $out=0;


      if(!empty($lastOperation)){
      if($lastOperation->Current != 0){
      $current=($lastOperation->Current + $newQQty) *  $ty;
      }else{
         $current=($newQQty) *  $ty;

      }

      }else{
           $current=($newQQty) *  $ty;
      }


           $cur=$New * $ty ;
  ProductsQty::where('id',$QuantityTo->id)->update(['Qty'=>$New,'Price'=>$ty, 'TotalCost'=>$cur]);



          $move['Date']=request('Date');
          $move['Type']='مرتجع تحويل مخازن';
                 $move['TypeEn']='Return Stores Transfer';
          $move['Bill_Num']=request('Code');
          $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']=$P_Code[$i];
          $move['Unit']=$Unit[$i];
          $move['QTY']=$ReturnQty[$i];
          $move['Group']=$prooooo->Group;;
          $move['Store']=request('From_Store');
          $move['Product']=$Product[$i];
          $move['V1']=$VOne[$i];
          $move['V2']=$VTwo[$i];
          $move['User']=auth()->guard('admin')->user()->id;
             $Sro=Stores::find(request('From_Store'));

                   $move['Brand']=$prooooo->Brand;
          $move['Safe']=null;
          $move['Branch']=$Sro->Branch;
          $move['SalePrice']=null;
          $move['ProductPrice']=null;
              $move['Delegate']=request('Delegate');
          $move['Payment_Method']=null;
              ProductMoves::create($move);


        }

            }





$PS=ProductsStoresTransfers::where('ST_ID',request('OriginalID'))->where('P_Code',$P_Code[$i])->where('Product',$Product[$i])->orderBy('id','desc')->first();

              $VXS['Trans_Qty']=$PS->Trans_Qty -  $ReturnQty[$i] ;


             ProductsStoresTransfers::where('id',$PS->id)->update($VXS);





            }







          }





        $Def=StoresDefaultData::orderBy('id','desc')->first();

         $F=StorsTransfers::find($id);




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

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

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

           }

              $CodeT=$id;
               $Fstore=Stores::find(request('From_Store'));

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

        array(

            'Code' => $Code,
            'Type' => 'تحويلات المخازن',
            'TypeEn' => 'Stores Transfers',
            'Code_Type' => $CodeT,
            'Date' => request('Date'),
            'Draw' => request('Draw'),
            'Coin' => request('Coin'),
            'Cost_Center' => null,
            'Total_Debaitor' => request('Total'),
            'Total_Creditor' => request('Total'),
            'Note' => request('Note'),

        )
    );

$Fstore=Stores::find(request('From_Store'));
    $Tstore=Stores::find(request('To_Store'));       //elly shary

        $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=0;
        $PRODUCTSS['Creditor']=request('Total_Cost');
        $PRODUCTSS['Account']=52;
        $PRODUCTSS['Statement']=null;


         JournalizingDetails::create($PRODUCTSS);

        $Gen['Code']=$Code;
        $Gen['Code_Type']=$CodeT;
        $Gen['Date']=request('Date');
        $Gen['Type']= 'تحويلات المخازن';
        $Gen['TypeEn']='Stores Transfers';
        $Gen['Debitor']=0;
        $Gen['Creditor']=request('Total_Cost');
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * 0;
        $Gen['Creditor_Coin']=request('Draw') * request('Total_Cost');
        $Gen['Account']=52;
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);


        $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=request('Total_Cost');
        $PRODUCTSS['Creditor']=0;
        $PRODUCTSS['Account']=$Fstore->Account;
        $PRODUCTSS['Statement']=null;


         JournalizingDetails::create($PRODUCTSS);

        $Gen['Code']=$Code;
        $Gen['Code_Type']=$CodeT;
        $Gen['Date']=request('Date');
        $Gen['Type']= 'تحويلات المخازن';
        $Gen['TypeEn']='Stores Transfers';
        $Gen['Debitor']=request('Total_Cost');
        $Gen['Creditor']=0;
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * request('Total_Cost');
        $Gen['Creditor_Coin']=request('Draw') * 0;
        $Gen['Account']=$Fstore->Account;
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']= null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);


          $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=0;
        $PRODUCTSS['Creditor']=request('Total');
        $PRODUCTSS['Account']=$Tstore->Account_Client;
        $PRODUCTSS['Statement']=null;


         JournalizingDetails::create($PRODUCTSS);

        $Gen['Code']=$Code;
        $Gen['Code_Type']=$CodeT;
        $Gen['Date']=request('Date');
        $Gen['Type']= 'تحويلات المخازن';
        $Gen['TypeEn']='Stores Transfers';
        $Gen['Debitor']=0;
        $Gen['Creditor']=request('Total');
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * 0;
        $Gen['Creditor_Coin']=request('Draw') * request('Total');
        $Gen['Account']=$Tstore->Account_Client;
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);


          $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=request('Total');
        $PRODUCTSS['Creditor']=0;
        $PRODUCTSS['Account']=49;
        $PRODUCTSS['Statement']=null;


         JournalizingDetails::create($PRODUCTSS);

        $Gen['Code']=$Code;
        $Gen['Code_Type']=$CodeT;
        $Gen['Date']=request('Date');
        $Gen['Type']= 'تحويلات المخازن';
        $Gen['TypeEn']='Stores Transfers';
        $Gen['Debitor']=request('Total');
        $Gen['Creditor']=0;
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * request('Total');
        $Gen['Creditor_Coin']=request('Draw') * 0;
        $Gen['Account']=49;
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']= null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);

        $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=request('Total');
        $PRODUCTSS['Creditor']=0;
        $PRODUCTSS['Account']=$Tstore->Account_Client;
        $PRODUCTSS['Statement']=null;


         JournalizingDetails::create($PRODUCTSS);

        $Gen['Code']=$Code;
        $Gen['Code_Type']=$CodeT;
        $Gen['Date']=request('Date');
        $Gen['Type']= 'تحويلات المخازن';
        $Gen['TypeEn']='Stores Transfers';
        $Gen['Debitor']=request('Total');
        $Gen['Creditor']=0;
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * request('Total');
        $Gen['Creditor_Coin']=request('Draw') * 0;
        $Gen['Account']=$Tstore->Account_Client;
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);




       $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=0;
        $PRODUCTSS['Creditor']=request('Total');
        $PRODUCTSS['Account']=$Tstore->Account;
        $PRODUCTSS['Statement']=null;


         JournalizingDetails::create($PRODUCTSS);

        $Gen['Code']=$Code;
        $Gen['Code_Type']=$CodeT;
        $Gen['Date']=request('Date');
        $Gen['Type']= 'تحويلات المخازن';
        $Gen['TypeEn']='Stores Transfers';
        $Gen['Debitor']=0;
        $Gen['Creditor']=request('Total');
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * 0;
        $Gen['Creditor_Coin']=request('Draw') * request('Total');
        $Gen['Account']=$Tstore->Account;
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);





                $store=Stores::find(request('To_Store'));

        $dataStMove['Date']=date('Y-m-d');
           $dataStMove['Code']=request('Code');
           $dataStMove['Time']=date("h:i:s a", time());
           $dataStMove['Branch']=$store->Branch;
           $dataStMove['Store']=request('From_Store');
           $dataStMove['Safe']=null;
           $dataStMove['Type']='تحويلات مخازن من';
           $dataStMove['TypeEn']='Stores Transfer From';
           $dataStMove['Cost_Center']=null;
           $dataStMove['User']=auth()->guard('admin')->user()->id;
           $dataStMove['Coin']=request('Coin');
           $dataStMove['Note']=request('Note');
           $dataStMove['Total_Qty']=request('TotalQty');
           $dataStMove['Total_Price']=request('Total');
           $dataStMove['Account']=null;
           $dataStMove['Ship']=request('Ship');
           $dataStMove['ID']=$id;
           StoresMoves::create($dataStMove);

             $store=Stores::find(request('From_Store'));

            $dataStMove['Date']=date('Y-m-d');
           $dataStMove['Code']=request('Code');
           $dataStMove['Time']=date("h:i:s a", time());
           $dataStMove['Branch']=$store->Branch;
           $dataStMove['Store']=request('To_Store');
           $dataStMove['Safe']=null;
           $dataStMove['Type']='تحويلات مخازن الي';
           $dataStMove['TypeEn']='Stores Transfer To';
           $dataStMove['Cost_Center']=null;
           $dataStMove['User']=auth()->guard('admin')->user()->id;
           $dataStMove['Coin']=request('Coin');
           $dataStMove['Note']=request('Note');
           $dataStMove['Total_Qty']=request('TotalQty');
           $dataStMove['Total_Price']=request('Total');
           $dataStMove['Account']=null;
           $dataStMove['Ship']=request('Ship');
           $dataStMove['ID']=$id;
           StoresMoves::create($dataStMove);


           $dataUser['User']=auth()->guard('admin')->user()->id;
           $dataUser['Date']=date('Y-m-d');
           $dataUser['Time']=date("h:i:s a", time());
          $dataUser['Screen']='تحويلات المخازن';
           $dataUser['ScreenEn']='Stores Transfers';
           $dataUser['Type']='مرتجع';
           $dataUser['TypeEn']='Return';
           $dataUser['Explain']=request('Code');
           $dataUser['ExplainEn']=request('Code');
           UsersMoves::create($dataUser);




             session()->flash('success',trans('admin.Updated'));
           return redirect('ReturnStoresTransfersSechdule');



              }catch(\Exception $ex){

                  $MODEL=ReturnStorsTransfer::class;
                  DB::rollBack();
                  Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

                  session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
                  return back();

              }catch(\Error $ex){


                  $MODEL=ReturnStorsTransfer::class;
                  DB::rollBack();
                  Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

                  session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
                  return back();

              }


          }




    //==== End Stores Transfers ====


     //===  Permission_to_exchange_goods  === //zy mbe3aat
      public function Permission_to_exchange_goods(){
         $Code=$this->ReturnCode(PermissionToExchangeGoods::class);
         $CostCenters=CostCenter::all();
         $Coins=Coins::all();
         $Stores=Stores::all();
         $Accounts = AcccountingManual::where('Type',1)->where('Parent',24)->get();
         return view('admin.Stores.PermissionToExchangeGoods',get_defined_vars());
    }

      public function ExchangePrintPage($id){

           $item=PermissionToExchangeGoods::find($id);

         return view('admin.Stores.ExchangePrint',get_defined_vars());
    }

      public function ExchangeGoodsSechdulePage(){

        $items=PermissionToExchangeGoods::paginate(100);
         return view('admin.Stores.ExchangeGoodsSechdule',get_defined_vars());
    }

   public function EditPremissionExchange($id){

            $item=PermissionToExchangeGoods::find($id);
  $details=ProductsPermissionToExchangeGoods::where('Exchange',$item->id)->get();
          $Code=$this->ReturnCode(PermissionToExchangeGoods::class);
         $CostCenters=CostCenter::all();
         $Coins=Coins::all();
         $Stores=Stores::all();
         $Accounts = AcccountingManual::where('Type',1)->where('Parent',24)->get();


                   if($item->Status != 0){
   session()->flash('error',trans('admin.Already_Done'));
               return redirect('ExchangeGoodsSechdule');

                    }
         return view('admin.Stores.EditPermissionToExchangeGoods',get_defined_vars());
    }


         public function TransferToSalesExchange($id){

             $item=PermissionToExchangeGoods::find($id);
           $details=ProductsPermissionToExchangeGoods::where('Exchange',$item->id)->get();
            $CostCenters=CostCenter::all();
            $Coins=Coins::all();
            $Stores=Stores::type()->get();
            $Brands=Brands::all();
            $ItemsGroups=ItemsGroups::all();
            $Safes = AcccountingManual::where('Type',1)->safetype()->lazy();
            $Employess = Employess::where('Emp_Type','Saller')->type()->lazy();
            $Deliveries = Employess::where('Emp_Type','Delivery')->type()->lazy();
            $Shippings = AcccountingManual::where('Type',1)->where('Parent',97)->get();
            $ChecksTypes=ChecksTypes::all();
            $Taxes=Taxes::all();
            $InstallmentCompanies=InstallmentCompanies::all();
            $Clients = AcccountingManual::where('Type',1)->accountsalestype()->lazy();
            $Code=$this->ReturnCode(Sales::class);
            $CodeUser=$this->ReturnCode(Customers::class);
            $Def=SalesDefaultData::orderBy('id','desc')->first();
            $crm=CrmDefaultData::orderBy('id','desc')->first();
            $FCOST=StoresDefaultData::orderBy('id','desc')->first();
            $show=DefaultDataShowHide::orderBy('id','desc')->first();
            $Style='none';
            $credStyle="none";
            $title=trans('admin.Transfer_to_Sales');
            $urll=url('PostTransSalesExchange/'.$item->id);
            $Place='RecivedSales';


                             if($item->Status != 0){
   session()->flash('error',trans('admin.Already_Done'));
               return redirect('ExchangeGoodsSechdule');

                    }



         return view('admin.Stores.TransferToSalesExchange',get_defined_vars());
    }


      function ExchangeProductsFilter(Request $request,StoresService $service)
             {

     if($request->ajax())
     {
      $output = '';
      $search = $request->get('search');
      $store = $request->get('store');

    if($search != '' and $store != '')
    {

        $Prods=$this->FilterSalesProductQty($search,$store,null,null);
        $data=$this->FilterSalesProduct($search,null,null);
        $Saleservice=new SalesService();

     }


         $total_row = $Prods->count();
         $total_row2 = $data->count();
         $total_row3 = $total_row + $total_row2;
      if($total_row3 > 0)
      {

         foreach($Prods as $rows){


             if(is_numeric($search)){

                 $rr = ProductUnits::where('Product', $rows->Product)->where('Barcode', $search)->first();
             }else {
                 $rr = ProductUnits::where('Product', $rows->Product)->where('Def', 1)->first();
             }


             $st=Stores::find($store);
             if(app()->getLocale() == 'ar' ){
                 $PrrroName=$rows->P_Ar_Name;
                 $UniiName=$rr->Unit()->first()->Name;
                 $StoreNemo=$st->Name;

             }else{
                 $PrrroName=$rows->P_En_Name;
                 $UniiName=$rr->Unit()->first()->NameEn;
                 $StoreNemo=$st->NameEn;

             }



             if($rows->Product()->first()->P_Type == 'Completed' or $rows->Product()->first()->P_Type == 'Industrial' or $rows->Product()->first()->P_Type == 'Additions'){
                 $type=1;
                 $v_name='';
                 $vv_name='';
                 $serial=0;
                 $p_code=$rr->Barcode;
             }elseif($rows->Product()->first()->P_Type == 'Serial'){
                 $type=2;
                 $v_name='';
                 $vv_name='';
                 $serial=1;
                 $p_code= $rows->P_Code;
             }elseif($rows->Product()->first()->P_Type == 'Single_Variable'){

                 if(app()->getLocale() == 'ar' ){
                     $PrrroVName=$rows->V1()->first()->Name;

                 }else{
                     $PrrroVName=$rows->V1()->first()->NameEn;

                 }

                 $type=3;
                 $v_name=$PrrroVName;
                 $vv_name='';
                 $serial=0;
                 $p_code= $rows->P_Code;
             }elseif($rows->Product()->first()->P_Type == 'Duble_Variable'){


                 if(app()->getLocale() == 'ar' ){
                     $PrrroVName=$rows->V1()->first()->Name;
                     $PrrroVVName=$rows->V2()->first()->Name;
                 }else{
                     $PrrroVName=$rows->V1()->first()->NameEn;
                     $PrrroVVName=$rows->V2()->first()->NameEn;
                 }

                 $type=4;
                 $v_name=$PrrroVName;
                 $vv_name=$PrrroVVName;
                 $serial=0;
                 $p_code= $rows->P_Code;
             }



        if($rows->Store == $store){


            $Filter=[

                'store'=>$store,
                'product'=>$rows->Product,
                'id'=>$rows->id,
                'name_ar'=>$rows->P_Ar_Name,
                'name_en'=>$rows->P_En_Name,
                'v1'=>$rows->V1,
                'v2'=>$rows->V2,
                'type'=>$type,
                'PrrroName'=>$PrrroName,
                'UniiName'=>$UniiName,
                'StoreNemo'=>$StoreNemo,
                'P_Code'=>$p_code,
                'qty'=>$rows->Qty / $rr->Rate,
                'Original'=>$rows->Original,
                'Patch_Number'=>$rows->Patch_Number,
                'v_name'=>$v_name,
                'vv_name'=>$vv_name,
                'serial'=>$serial,
                'Exp_Date'=>$rows->Exp_Date,
                'pro_store'=>$rows->Store,
                'search'=>$search,

            ];

            $output .=$service->ItemsFilterExchange($Filter);



        }


         }

          foreach($data as $rows){

              if(is_numeric($search)){

                  $ser_x=1;
                  $ser_y=0;

              }else{


                  $ser_x=1;
                  $ser_y=1;


              }



              if($rows->Def == $ser_x or $rows->Def == $ser_y){

                  if(is_numeric($search)){

                      $rr = ProductUnits::where('Product', $rows->Product)->where('Barcode', $search)->first();
                  }else {
                      $rr = ProductUnits::where('Product', $rows->Product)->where('Def', 1)->first();
                  }

                  $st=Stores::find($store);
                  if(app()->getLocale() == 'ar' ){
                      $PrrroName=$rows->P_Ar_Name;
                      $UniiName=$rr->Unit()->first()->Name;
                      $StoreNemo=$st->Name;

                  }else{
                      $PrrroName=$rows->P_En_Name;
                      $UniiName=$rr->Unit()->first()->NameEn;
                      $StoreNemo=$st->NameEn;

                  }



                  if($rows->Product()->first()->P_Type == 'Assembly'){

                      $type=1;

                      $cost=$Saleservice->AssemblyCost($rows->Product,$store);
                      $qty=$Saleservice->AssemblyQty($rows->Product,$store);

                  }elseif($rows->Product()->first()->P_Type == 'Service'){

                      $type=2;
                      $cost=0;
                      $qty=1000;
                  }

                  $v_name='';
                  $vv_name='';
                  $serial=0;
                  $p_code=$rr->Barcode;

                  if($rows->Product()->first()->P_Type == 'Assembly'  or $rows->Product()->first()->P_Type == 'Service') {
                      $Filter = [

                          'store' => $store,
                          'product' => $rows->Product,
                          'name_ar' => $rows->P_Ar_Name,
                          'name_en' => $rows->P_En_Name,
                          'v1' => $rows->V1,
                          'v2' => $rows->V2,
                          'type' => $type,
                          'PrrroName' => $PrrroName,
                          'UniiName' => $UniiName,
                          'StoreNemo' => $StoreNemo,
                          'P_Code' => $p_code,
                          'qty' => $qty,
                          'Original' => $rows->Original,
                          'Patch_Number' => $rows->Patch_Number,
                          'v_name' => $v_name,
                          'vv_name' => $vv_name,
                          'serial' => $serial,
                          'Exp_Date' => $rows->Exp_Date,
                          'cost' => $cost,
                          'search'=>$search,
                      ];

                      $output .= $service->ItemsFilterExchangeTwo($Filter);
                  }




              }
          }


      }else
      {
       $output = '
        <div class="col-md-3">'.trans('admin.No_Data_Find').'</div>
       ';
      }
      $data = array(
       'table_data'  => $output,
      );
      echo json_encode($data);
     }
    }

      public function AddExchangeGoods(){

           try {
    DB::beginTransaction();

            $data= $this->validate(request(),[
             'Date'=>'required',
             'Store'=>'required',
             'Coin'=>'required',
             'Draw'=>'required',
             'Account'=>'required',

               ],[

            'Date.required' => trans('admin.DateRequired'),
            'Store.required' => trans('admin.StoreRequired'),
            'Safe.required' => trans('admin.SafeRequired'),
            'Coin.required' => trans('admin.CoinRequired'),
            'Draw.required' => trans('admin.TDrawRequired'),
            'Payment_Method.required' => trans('admin.Payment_MethodRequired'),
            'Status.required' => trans('admin.StatusRequired'),
            'Account.required' => trans('admin.ClientRequired'),

         ]);


           $ID = DB::table('permission_to_exchange_goods')->insertGetId(
        array(


            'Date' => request('Date'),
            'Draw' => request('Draw'),
            'Note' => request('Note'),
            'Product_Numbers' => request('Product_Numbers'),
            'Total_Qty' => request('Total_Qty'),
            'Total_Discount' => request('Total_Discount'),
            'Total_BF_Taxes' => request('Total_BF_Taxes'),
            'Total_Taxes' => request('Total_Taxes'),
            'Total_Price' => request('Total_Price'),
            'Account' => request('Account'),
            'To_Store' => request('To_Store'),
            'Store' => request('Store'),
            'Coin' => request('Coin'),
            'Status' => 0,
            'Cost_Center' => request('Cost_Center'),
            'User' => auth()->guard('admin')->user()->id,

        )
    );



                 $notii['Date']=date('Y-m-d');
         $notii['Status']=0;
         $notii['Noti_Ar_Name']='اذن صرف بضاعة';
         $notii['Noti_En_Name']='Permission to receive goods';
         $notii['Type']='اذن صرف بضاعة';
  $notii['TypeEn']='Safe Permission to exchange goods';
         $notii['Type_Code']=request('Code');
         $notii['Emp']=null;
         $notii['Client']=request('Account');
         $notii['Product']=null;
         $notii['Store']=request('Store');
         $notii['Safe']=null;
         Notifications::create($notii);

                notify()->success(trans('admin.Permission_to_exchange_goods'));

          if(!empty(request('Unit'))){

                   StoreCountSales::truncate();
              $P_Ar_Name=request('P_Ar_Name');
              $P_En_Name=request('P_En_Name');
              $Unit=request('Unit');
              $P_Code=request('P_Code');
              $Qty=request('Qty');
              $AvQty=request('AvQty');
              $Price=request('Price');
              $Discount=request('Discount');
              $TotalBFTax=request('TotalBFTax');
              $TotalTax=request('TotalTax');
              $PurchTax=request('PurchTax');
              $Total=request('Total');
              $StorePurch=request('StorePurch');
              $To_Store=request('To_Store');
              $Exp_Date=request('Exp_Date');
              $Product=request('Product');
              $VOne=request('VOne');
              $VTwo=request('VTwo');
              $V_Name=request('V_Name');
              $VV_Name=request('VV_Name');
              $Exp_Date=request('Exp_Date');
              $CostPrice=request('CostPrice');
              $TDiscount=request('TDiscount');
              $TotCostNew=request('TotCostNew');


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

                $unit=ProductUnits::where('Product',$Product[$i])->where('Unit',$Unit[$i])->first();
                $uu['Product_Code']=$P_Code[$i];
                $uu['P_Ar_Name']=$P_Ar_Name[$i];
                $uu['P_En_Name']=$P_En_Name[$i];
                $uu['V_Name']=$V_Name[$i];
                $uu['VV_Name']=$VV_Name[$i];
                $uu['Original_Qty']=$Qty[$i];
                $uu['Qty']=$Qty[$i];
                $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];
                $uu['Store']=$StorePurch[$i];
                $uu['To_Store']=request('To_Store');
                $uu['Product']=$Product[$i];
                $uu['Unit']=$Unit[$i];
                $uu['Exp_Date']=$Exp_Date[$i];
                $uu['Exchange']=$ID;
                $uu['V1']=$VOne[$i];
                $uu['V2']=$VTwo[$i];
                $uu['CostPrice']=$CostPrice[$i];
                $uu['TDiscount']=$Discount[$i] * $Qty[$i];
                $uu['Patch_Number']=null;
                $uu['Pro_Note']=null;
                $uu['SubVID']=null;
                $uu['Total_Wight']=null;
                $uu['UnitRate']=$unit->Rate;
                $uu['weight']=null;
                $uu['SalesProDesc']=null;
                $uu['TotCostNew']=$TotCostNew[$i];
                $uu['SmallQty']=null;
                $uu['SmallCode']=null;
                $uu['Total_Net']=( ( $Qty[$i] * $Price[$i] ) + $TotalTax[$i]  )  - ($Discount[$i] * $Qty[$i]);
                 $uu['Date']=request('Date');

               ProductsPermissionToExchangeGoods::create($uu);





            }

                }




       $dataUser=[
    'screen_ar'=>'اذن صرف بضاعه',
    'screen_en'=>'Permission to exchange goods',
    'explain_ar'=>request('Code'),
    'explain_en'=>request('Code'),
    ];
    $this->UserCreateMoves($dataUser);

 DB::commit();
           session()->flash('success',trans('admin.Added_Successfully'));
         if(request('SP') == 0){  return back(); }elseif(request('SP') == 1){  return redirect('ExchangePrint/'.$ID); }

                         }catch(\Exception $ex){

     $MODEL=PermissionToExchangeGoods::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

           session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }catch(\Error $ex){


             $MODEL=PermissionToExchangeGoods::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }


     }

     public function DeletePremissionExchange($id){


           try {
    DB::beginTransaction();

        $del=PermissionToExchangeGoods::find($id);
                        Notifications::where('Type_Code',$del->Code)->where('Type','اذن صرف بضاعة')->delete();
PermissionToExchangeGoods::where('id',$id)->update(['Delete'=>1]);


      $dataUser=[
    'screen_ar'=>'اذن صرف بضاعه',
    'screen_en'=>'Permission to exchange goods',
    'explain_ar'=>$del->Code,
    'explain_en'=>$del->Code,
    ];
    $this->UserDeleteMoves($dataUser);

 DB::commit();
        session()->flash('error',trans('admin.Deleted'));
        return back();


                         }catch(\Exception $ex){

     $MODEL=PermissionToExchangeGoods::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

           session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }catch(\Error $ex){


             $MODEL=PermissionToExchangeGoods::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }



           }


      public function PostEditExchangeGoods($id){

                try {
    DB::beginTransaction();

            $data= $this->validate(request(),[
             'Date'=>'required',
             'Store'=>'required',
             'Coin'=>'required',
             'Draw'=>'required',
             'Account'=>'required',

               ],[

            'Date.required' => trans('admin.DateRequired'),
            'Store.required' => trans('admin.StoreRequired'),
            'Safe.required' => trans('admin.SafeRequired'),
            'Coin.required' => trans('admin.CoinRequired'),
            'Draw.required' => trans('admin.TDrawRequired'),
            'Payment_Method.required' => trans('admin.Payment_MethodRequired'),
            'Status.required' => trans('admin.StatusRequired'),
            'Client.required' => trans('admin.ClientRequired'),

         ]);

PermissionToExchangeGoods::where('id',$id)->update(['Edit'=>1,'Edit_New_Code'=>request('Code')]);

           $ID = DB::table('permission_to_exchange_goods')->insertGetId(
        array(


            'Date' => request('Date'),
            'Draw' => request('Draw'),
            'Note' => request('Note'),
            'Product_Numbers' => request('Product_Numbers'),
            'Total_Qty' => request('Total_Qty'),
            'Total_Discount' => request('Total_Discount'),
            'Total_BF_Taxes' => request('Total_BF_Taxes'),
            'Total_Taxes' => request('Total_Taxes'),
            'Total_Price' => request('Total_Price'),
            'Account' => request('Account'),
            'To_Store' => request('To_Store'),
            'Store' => request('Store'),
            'Coin' => request('Coin'),
            'Status' => 0,
            'Cost_Center' => request('Cost_Center'),
            'User' => auth()->guard('admin')->user()->id,

        )
    );



                 $notii['Date']=date('Y-m-d');
         $notii['Status']=0;
         $notii['Noti_Ar_Name']='اذن صرف بضاعة';
         $notii['Noti_En_Name']='Permission to receive goods';
         $notii['Type']='اذن صرف بضاعة';
  $notii['TypeEn']='Safe Permission to exchange goods';
         $notii['Type_Code']=request('Code');
         $notii['Emp']=null;
         $notii['Client']=request('Account');
         $notii['Product']=null;
         $notii['Store']=request('Store');
         $notii['Safe']=null;
         Notifications::create($notii);

                notify()->success(trans('admin.Permission_to_exchange_goods'));

          if(!empty(request('Unit'))){

                   StoreCountSales::truncate();
              $P_Ar_Name=request('P_Ar_Name');
              $P_En_Name=request('P_En_Name');
              $Unit=request('Unit');
              $P_Code=request('P_Code');
              $Qty=request('Qty');
              $AvQty=request('AvQty');
              $Price=request('Price');
              $Discount=request('Discount');
              $TotalBFTax=request('TotalBFTax');
              $TotalTax=request('TotalTax');
              $PurchTax=request('PurchTax');
              $Total=request('Total');
              $StorePurch=request('StorePurch');
              $To_Store=request('To_Store');
              $Exp_Date=request('Exp_Date');
              $Product=request('Product');
              $VOne=request('VOne');
              $VTwo=request('VTwo');
              $V_Name=request('V_Name');
              $VV_Name=request('VV_Name');
              $Exp_Date=request('Exp_Date');
              $CostPrice=request('CostPrice');
              $TotCostNew=request('TotCostNew');



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

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

                $uu['Product_Code']=$P_Code[$i];
                $uu['P_Ar_Name']=$P_Ar_Name[$i];
                $uu['P_En_Name']=$P_En_Name[$i];
                $uu['V_Name']=$V_Name[$i];
                $uu['VV_Name']=$VV_Name[$i];
                $uu['Original_Qty']=$Qty[$i];
                $uu['Qty']=$Qty[$i];
                $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];
                $uu['Store']=$StorePurch[$i];
                $uu['To_Store']=request('To_Store');
                $uu['Product']=$Product[$i];
                $uu['Unit']=$Unit[$i];
                $uu['Exp_Date']=$Exp_Date[$i];
                $uu['Exchange']=$ID;
                $uu['V1']=$VOne[$i];
                $uu['V2']=$VTwo[$i];
                $uu['CostPrice']=$CostPrice[$i];
                $uu['TDiscount']=$Discount[$i] * $Qty[$i];
                $uu['Patch_Number']=null;
                $uu['Pro_Note']=null;
                $uu['SubVID']=null;
                $uu['Total_Wight']=null;
                $uu['UnitRate']=$unit->Rate;
                $uu['weight']=null;
                $uu['SalesProDesc']=null;
                $uu['TotCostNew']=$TotCostNew[$i];
                $uu['SmallQty']=null;
                $uu['SmallCode']=null;
                $uu['Total_Net']=( ( $Qty[$i] * $Price[$i] ) + $TotalTax[$i]  )  - ($Discount[$i] * $Qty[$i]);
                 $uu['Date']=request('Date');

               ProductsPermissionToExchangeGoods::create($uu);





            }

                }




       $dataUser=[
    'screen_ar'=>'اذن صرف بضاعه',
    'screen_en'=>'Permission to exchange goods',
    'explain_ar'=>request('Old_Code'),
    'explain_en'=>request('Old_Code'),
    ];
    $this->UserUpdateMoves($dataUser);

 DB::commit();



           session()->flash('success',trans('admin.Updated'));
      return redirect('ExchangeGoodsSechdule');

           }catch(\Exception $ex){

     $MODEL=PermissionToExchangeGoods::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

           session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }catch(\Error $ex){


             $MODEL=PermissionToExchangeGoods::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }


     }


    //Transfer to Sales

         public function PostTransSalesExchange($id,SalesRequest $request,SalesService $service){


            try {
    DB::beginTransaction();

      $validated = $request->validated();


           $del=PermissionToExchangeGoods::find($id);

            PermissionToExchangeGoods::where('id',$id)->update(['Status'=>1]);

           $Sale_Type='Sales';

         //Service Create New Bill
         $ID=$service->CreateNewSalesBill($request->all(),$Sale_Type);



         //Event New Bill
          SalesEvent::dispatch($request->all(),$ID,$Sale_Type);


            $dataUser=[
    'screen_ar'=>'المبيعات',
    'screen_en'=>'Sales',
    'explain_ar'=>request('Code'),
    'explain_en'=>request('Code'),
    ];
    $this->UserCreateMoves($dataUser);


       DB::commit();


             session()->flash('success',trans('admin.Transfered'));
            return redirect('SalesSechdule');


                          }catch(\Exception $ex){

     $MODEL=Sales::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

           session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }catch(\Error $ex){


             $MODEL=Sales::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }




     }


    // ===   Permission_to_receive_goods ===  //zy moshtryat
      public function Permission_to_receive_goods(){

           $Code=$this->ReturnCode(PermissionToRecivedGoods::class);
         $CostCenters=CostCenter::all();
         $Coins=Coins::all();
         $Stores=Stores::all();
         $Accounts = AcccountingManual::where('Type',1)->where('Parent',37)->get();


         return view('admin.Stores.PermissionToReceiveGoods',get_defined_vars());
    }

      public function RecivedPrint($id){

           $item=PermissionToRecivedGoods::find($id);

         return view('admin.Stores.RecivedPrint',get_defined_vars());
    }

     public function ReceiveGoodsSechdule(){

        $items=PermissionToRecivedGoods::paginate(100);
         return view('admin.Stores.ReceiveGoodsSechdule',get_defined_vars());
    }


     public function EditPremissionRercived($id){

            $item=PermissionToRecivedGoods::find($id);
 $details=ProductsPermissionToRecivedGoods::where('Recived',$item->id)->get();
    $Code=$this->ReturnCode(PermissionToRecivedGoods::class);
         $CostCenters=CostCenter::all();
         $Coins=Coins::all();
         $Stores=Stores::all();
         $Accounts = AcccountingManual::where('Type',1)->where('Parent',37)->get();


                                   if($item->Status != 0){
   session()->flash('error',trans('admin.Already_Done'));
               return redirect('ReceiveGoodsSechdule');

                    }

         return view('admin.Stores.EditPermissionToReceiveGoods',get_defined_vars());
    }


     public function TransferToPurchasesRecived($id){

           $item=PermissionToRecivedGoods::find($id);
      $details=ProductsPermissionToRecivedGoods::where('Recived',$item->id)->get();
        $CostCenters=CostCenter::all();
        $Coins=Coins::all();
        $Stores=Stores::type()->get();
        $Brands=Brands::all();
        $ItemsGroups=ItemsGroups::all();
        $Safes = AcccountingManual::where('Type',1)->safetype()->lazy();
        $Vendors = AcccountingManual::where('Type',1)->accountpurchtype()->lazy();
        $Employess = Employess::where('Emp_Type','Buyer')->type()->lazy();
        $Shippings = AcccountingManual::where('Type',1)->where('Parent',97)->get();
        $ChecksTypes=ChecksTypes::all();
        $Units=Measuerments::all();
        $Def=PurchasesDefaultData::orderBy('id','desc')->first();
        $show=DefaultDataShowHide::orderBy('id','desc')->first();
        $credStyle="none";
        $title=trans('admin.Transfer_To_Purchases');
        $urll=url('PostTransferPurchasesRecived');
        $Code=$this->ReturnCode(Purchases::class);
        $CodeUser=$this->ReturnCode(Vendors::class);
  $Place='RecivedPurchases';

                                          if($item->Status != 0){
   session()->flash('error',trans('admin.Already_Done'));
               return redirect('ReceiveGoodsSechdule');

                    }

            return view('admin.Stores.TransferToPurchasesRecived',get_defined_vars());
    }


       public function AddRecivedGoods(){

                      try {
    DB::beginTransaction();
            $data= $this->validate(request(),[
             'Date'=>'required',
             'Store'=>'required',
             'Coin'=>'required',
             'Draw'=>'required',
             'Account'=>'required',

               ],[

            'Date.required' => trans('admin.DateRequired'),
            'Store.required' => trans('admin.StoreRequired'),
            'Safe.required' => trans('admin.SafeRequired'),
            'Coin.required' => trans('admin.CoinRequired'),
            'Draw.required' => trans('admin.TDrawRequired'),
            'Payment_Method.required' => trans('admin.Payment_MethodRequired'),
            'Status.required' => trans('admin.StatusRequired'),
            'Client.required' => trans('admin.ClientRequired'),

         ]);

           $ID = DB::table('permission_to_recived_goods')->insertGetId(
        array(

            'Code' => request('Code'),
            'Date' => request('Date'),
            'Draw' => request('Draw'),
            'Note' => request('Note'),
            'Product_Numbers' => request('Product_Numbers'),
            'Total_Qty' => request('Total_Qty'),
            'Total_Discount' => request('Total_Discount'),
            'Total_BF_Taxes' => request('Total_BF_Taxes'),
            'Total_Taxes' => request('Total_Taxes'),
            'Total_Price' => request('Total_Price'),
            'Account' => request('Account'),
            'Store' => request('Store'),
            'To_Store' => request('To_Store'),
            'Coin' => request('Coin'),
             'Status' => 0,
            'Cost_Center' => request('Cost_Center'),
            'User' => auth()->guard('admin')->user()->id,

        )
    );



         $notii['Date']=date('Y-m-d');
         $notii['Status']=0;
         $notii['Noti_Ar_Name']='اذن استلام بضاعة';
         $notii['Noti_En_Name']='Permission to receive goods';
         $notii['Type']='اذن استلام بضاعة';
  $notii['TypeEn']='Safe Permission to receive goods';
         $notii['Type_Code']=request('Code');
         $notii['Emp']=null;
         $notii['Client']=request('Account');
         $notii['Product']=null;
         $notii['Store']=request('Store');
         $notii['Safe']=null;
         Notifications::create($notii);

                notify()->success(trans('admin.Permission_to_receive_goods'));



          if(!empty(request('Unit'))){

                   StoreCountSales::truncate();
              $P_Ar_Name=request('P_Ar_Name');
              $P_En_Name=request('P_En_Name');
              $Unit=request('Unit');
              $P_Code=request('P_Code');
              $Qty=request('Qty');
              $AvQty=request('AvQty');
              $Price=request('Price');
              $Discount=request('Discount');
              $TotalBFTax=request('TotalBFTax');
              $TotalTax=request('TotalTax');
              $PurchTax=request('PurchTax');
              $Total=request('Total');
              $StorePurch=request('StorePurch');
              $Exp_Date=request('Exp_Date');
              $Product=request('Product');
              $VOne=request('VOne');
              $VTwo=request('VTwo');
              $V_Name=request('V_Name');
              $VV_Name=request('VV_Name');
              $Exp_Date=request('Exp_Date');


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


                $uu['Product_Code']=$P_Code[$i];
                $uu['P_Ar_Name']=$P_Ar_Name[$i];
                $uu['P_En_Name']=$P_En_Name[$i];
                $uu['V_Name']=$V_Name[$i];
                $uu['VV_Name']=$VV_Name[$i];
                $uu['Original_Qty']=$Qty[$i];
                $uu['Qty']=$Qty[$i];
                $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];
                $uu['Store']=$StorePurch[$i];
                $uu['To_Store']=request('To_Store');
                $uu['Product']=$Product[$i];
                $uu['Unit']=$Unit[$i];
                $uu['Exp_Date']=$Exp_Date[$i];
                $uu['Recived']=$ID;
                $uu['V1']=$VOne[$i];
                $uu['V2']=$VTwo[$i];
                $uu['TDiscount']=$Discount[$i] * $Qty[$i];
                $uu['Total_Net']=( ($Price[$i] * $Qty[$i]) + $TotalTax[$i] )  - ($Discount[$i] * $Qty[$i]);
                $uu['SmallCode']=null;
                $uu['SmallQty']=null;
                 $uu['Date']=request('Date');


               ProductsPermissionToRecivedGoods::create($uu);



            }


          }



               $dataUser=[
    'screen_ar'=>'اذن استلام بضاعه',
    'screen_en'=>'Permission to receive goods',
    'explain_ar'=>request('Code'),
    'explain_en'=>request('Code'),
    ];
    $this->UserCreateMoves($dataUser);

                            DB::commit();
           session()->flash('success',trans('admin.Added_Successfully'));
         if(request('SP') == 0){  return back(); }elseif(request('SP') == 1){  return redirect('RecivedPrint/'.$ID); }


             }catch(\Exception $ex){

     $MODEL=PermissionToRecivedGoods::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

           session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }catch(\Error $ex){


             $MODEL=PermissionToRecivedGoods::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }


     }


        public function DeletePremissionRercived($id){


           try {
    DB::beginTransaction();

        $del=PermissionToRecivedGoods::find($id);
                        Notifications::where('Type_Code',$del->Code)->where('Type','اذن صرف بضاعة')->delete();
PermissionToRecivedGoods::where('id',$id)->update(['Delete'=>1]);


      $dataUser=[
       'screen_ar'=>'اذن استلام بضاعه',
    'screen_en'=>'Permission to receive goods',
    'explain_ar'=>$del->Code,
    'explain_en'=>$del->Code,
    ];
    $this->UserDeleteMoves($dataUser);

 DB::commit();
        session()->flash('error',trans('admin.Deleted'));
        return back();


                         }catch(\Exception $ex){

     $MODEL=PermissionToRecivedGoods::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

           session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }catch(\Error $ex){


             $MODEL=PermissionToRecivedGoods::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }



           }



    public function PostEditRecivedGoods($id){


                      try {
    DB::beginTransaction();
            $data= $this->validate(request(),[
             'Date'=>'required',
             'Store'=>'required',
             'Coin'=>'required',
             'Draw'=>'required',
             'Account'=>'required',

               ],[

            'Date.required' => trans('admin.DateRequired'),
            'Store.required' => trans('admin.StoreRequired'),
            'Safe.required' => trans('admin.SafeRequired'),
            'Coin.required' => trans('admin.CoinRequired'),
            'Draw.required' => trans('admin.TDrawRequired'),
            'Payment_Method.required' => trans('admin.Payment_MethodRequired'),
            'Status.required' => trans('admin.StatusRequired'),
            'Client.required' => trans('admin.ClientRequired'),

         ]);



PermissionToRecivedGoods::where('id',$id)->update(['Edit'=>1,'Edit_New_Code'=>request('Code')]);

           $ID = DB::table('permission_to_recived_goods')->insertGetId(
        array(

            'Code' => request('Code'),
            'Date' => request('Date'),
            'Draw' => request('Draw'),
            'Note' => request('Note'),
            'Product_Numbers' => request('Product_Numbers'),
            'Total_Qty' => request('Total_Qty'),
            'Total_Discount' => request('Total_Discount'),
            'Total_BF_Taxes' => request('Total_BF_Taxes'),
            'Total_Taxes' => request('Total_Taxes'),
            'Total_Price' => request('Total_Price'),
            'Account' => request('Account'),
            'Store' => request('Store'),
            'To_Store' => request('To_Store'),
            'Coin' => request('Coin'),
             'Status' => 0,
            'Cost_Center' => request('Cost_Center'),
            'User' => auth()->guard('admin')->user()->id,

        )
    );



         $notii['Date']=date('Y-m-d');
         $notii['Status']=0;
         $notii['Noti_Ar_Name']='اذن استلام بضاعة';
         $notii['Noti_En_Name']='Permission to receive goods';
         $notii['Type']='اذن استلام بضاعة';
  $notii['TypeEn']='Safe Permission to receive goods';
         $notii['Type_Code']=request('Code');
         $notii['Emp']=null;
         $notii['Client']=request('Account');
         $notii['Product']=null;
         $notii['Store']=request('Store');
         $notii['Safe']=null;
         Notifications::create($notii);

                notify()->success(trans('admin.Permission_to_receive_goods'));



          if(!empty(request('Unit'))){

                   StoreCountSales::truncate();
              $P_Ar_Name=request('P_Ar_Name');
              $P_En_Name=request('P_En_Name');
              $Unit=request('Unit');
              $P_Code=request('P_Code');
              $Qty=request('Qty');
              $AvQty=request('AvQty');
              $Price=request('Price');
              $Discount=request('Discount');
              $TotalBFTax=request('TotalBFTax');
              $TotalTax=request('TotalTax');
              $PurchTax=request('PurchTax');
              $Total=request('Total');
              $StorePurch=request('StorePurch');
              $Exp_Date=request('Exp_Date');
              $Product=request('Product');
              $VOne=request('VOne');
              $VTwo=request('VTwo');
              $V_Name=request('V_Name');
              $VV_Name=request('VV_Name');
              $Exp_Date=request('Exp_Date');


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


                $uu['Product_Code']=$P_Code[$i];
                $uu['P_Ar_Name']=$P_Ar_Name[$i];
                $uu['P_En_Name']=$P_En_Name[$i];
                $uu['V_Name']=$V_Name[$i];
                $uu['VV_Name']=$VV_Name[$i];
                $uu['Original_Qty']=$Qty[$i];
                $uu['Qty']=$Qty[$i];
                $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];
                $uu['Store']=$StorePurch[$i];
                $uu['To_Store']=request('To_Store');
                $uu['Product']=$Product[$i];
                $uu['Unit']=$Unit[$i];
                $uu['Exp_Date']=$Exp_Date[$i];
                $uu['Recived']=$ID;
                $uu['V1']=$VOne[$i];
                $uu['V2']=$VTwo[$i];
                $uu['TDiscount']=$Discount[$i] * $Qty[$i];
                $uu['Total_Net']=( ($Price[$i] * $Qty[$i]) + $TotalTax[$i] )  - ($Discount[$i] * $Qty[$i]);
                $uu['SmallCode']=null;
                $uu['SmallQty']=null;
                 $uu['Date']=request('Date');


               ProductsPermissionToRecivedGoods::create($uu);



            }


          }



               $dataUser=[
    'screen_ar'=>'اذن استلام بضاعه',
    'screen_en'=>'Permission to receive goods',
   'explain_ar'=>request('Old_Code'),
    'explain_en'=>request('Old_Code'),
    ];
    $this->UserCreateMoves($dataUser);

                            DB::commit();



           session()->flash('success',trans('admin.Updated'));
          return redirect('ReceiveGoodsSechdule');

        }catch(\Exception $ex){

     $MODEL=PermissionToRecivedGoods::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

           session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }catch(\Error $ex){


             $MODEL=PermissionToRecivedGoods::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }



     }

          function RecivedProductsFilter(Request $request,StoresService $service)
             {

     if($request->ajax())
     {
      $output = '';
      $search = $request->get('search');
      $store = $request->get('store');

    if($search != '' and $store != '')
    {

        $data =$this->FilterPurchProduct($search,null,null);


     }

         $total_row = $data->count();
      if($total_row > 0)
      {


          $st=Stores::find($store);


          foreach($data as $row){

              if(is_numeric($search)){

                  $ser_x=1;
                  $ser_y=0;

              }else{


                  $ser_x=1;
                  $ser_y=1;


              }



              if($row->Def == $ser_x or $row->Def == $ser_y){


                  $rr=ProductUnits::where('Product',$row->Product)->where('Def',1)->first();



                  if(app()->getLocale() == 'ar' ){
                      $PrrroName=$row->P_Ar_Name;
                      $UniiName=$row->Unit()->first()->Name;
                      $StoreNemo=$st->Name;

                  }else{
                      $PrrroName=$row->P_En_Name;
                      $UniiName=$row->Unit()->first()->NameEn;
                      $StoreNemo=$st->NameEn;

                  }



                  $Filter=[

                      'store'=>$store,
                      'product'=>$row->Product,
                      'id'=>$row->id,
                      'name_ar'=>$row->P_Ar_Name,
                      'name_en'=>$row->P_En_Name,
                      'PrrroName'=>$PrrroName,
                      'UniiName'=>$UniiName,
                      'StoreNemo'=>$StoreNemo,
                      'search'=>$search,

                  ];

                  $output .=$service->ItemsFilterRecived($Filter);

              }
          }

      }else
      {
       $output = '
        <div class="col-md-3"> '.trans('admin.No_Data_Find').'</div>
       ';
      }
      $data = array(
       'table_data'  => $output,
      );
      echo json_encode($data);
     }
    }

   //===  Transfer to Purchases


  public function PostTransferPurchasesRecived(PurchasesRequest $request){

          try {
    DB::beginTransaction();

    $validated = $request->validated();


         if(request('Payment_Method') == 'Cash'){

         $paid = request('Total_Price') ;
        $SafyFatora=(request('Total_Price') + request('Total_Taxes')) - (request('Total_Discount') + request('DiscountBill')) ;

         }elseif(request('Payment_Method') == 'Later'){

             if(!empty(request('Pay'))){
              $SafyFatora= request('Pay') ;
                 $paid = request('Pay') ;
             }else{
               $SafyFatora= 0 ;
                 $paid = 0 ;
             }

         }elseif(request('Payment_Method') == 'Check'){

         $paid = request('Total_Price') ;
        $SafyFatora=(request('Total_Price') + request('Total_Taxes')) - (request('Total_Discount') + request('DiscountBill')) ;

         }

                $SafeBalance=$this->SafeCredit(request('Safe'),$SafyFatora);

                  if($SafeBalance == 1){
                      session()->flash('error',trans('admin.SafeNotEnoughMoney'));
             return back();

             }


  $branch=Stores::find(request('Store'));
  $custG=Customers::where('Account',request('Vendor'))->orderBy('id','desc')->first();

         if(!empty($branch)){
         $BRAAA=$branch->Branch;
         }else{
         $BRAAA=null;
         }

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


               $image=request()->file('File');
             $zFile=$this->UploadFile($image);


           $ID = DB::table('purchases')->insertGetId(
        array(


            'Date' => request('Date'),
            'Draw' => request('Draw'),
            'Payment_Method' => request('Payment_Method'),
            'Status' => request('Status'),
            'Vendor_Bill_Date' => request('Vendor_Bill_Date'),
            'Refernce_Number' => request('Refernce_Number'),
            'Note' => request('Note'),
            'Product_Numbers' => request('Product_Numbers'),
            'Total_Qty' => request('Total_Qty'),
            'Total_Discount' => request('Total_Discount') + request('DiscountBill'),
            'Total_BF_Taxes' => request('Total_BF_Taxes'),
            'Total_Taxes' => request('Total_Taxes'),
            'Total_Price' => request('Total_Price'),
            'Pay' => $paid,
            'P_Order_Num' => request('P_Order_Num'),
            'Safe' => request('Safe'),
            'Vendor' => request('Vendor'),
            'Delegate' => request('Delegate'),
            'Store' => request('Store'),
            'Coin' => request('Coin'),
            'Ship' => request('Ship'),
            'TaxBill' => request('TaxBill'),
            'Time' => date("h:i:s a", time()),
            'Branch' => $BRAAA,
            'CustomerGroup' => $CUSTGROP,
            'TaxCode' => 1,
            'File' => $zFile,
            'Check_Type' => request('Check_Type'),
            'Due_Date' => request('Due_Date'),
            'Check_Number' => request('Check_Number'),
            'Cost_Center' => request('Cost_Center'),
            'Later_Due' => request('Later_Due'),
            'User' => auth()->guard('admin')->user()->id,
            'Current_Credit' =>request('Current_Credit'),
            'Residual' =>$SafyFatora - $paid,
            'Total_Net' =>$SafyFatora,
            'Edit' =>0,
            'Delete' =>0,
            'Edit_New_Code' =>0,

        )
    );



                 //Purchases Event
         $Bill_Code=Purchases::findOrFail($ID);
         PurchasesEvent::dispatch($request->all(),$ID);


      $id=request('ID');




          $del=PermissionToRecivedGoods::findOrFail($id);
         PermissionToRecivedGoods::where('id',$id)->update(['Status'=>1]);



    $dataUser=[
    'screen_ar'=>'المشتريات',
    'screen_en'=>'Purchases',
    'explain_ar'=>$Bill_Code->Code,
    'explain_en'=>$Bill_Code->Code,
    ];
    $this->UserCreateMoves($dataUser);

                DB::commit();



             session()->flash('success',trans('admin.Added_Successfully'));
             return redirect('PurchasesSechdule');


              }catch(\Exception $ex){

     $MODEL=Purchases::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

           session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }catch(\Error $ex){


             $MODEL=Purchases::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }



    }





}
