<?php

namespace App\Http\Controllers;
use App\Events\ReturnSalesEvent;
use App\Events\ReturnSalesEventApi;
use App\Events\SalesEvent;
use App\Events\SalesEventApi;
use App\Events\SalesOrderEvent;
use App\Events\StoresTransferApiEvent;
use App\Events\StoresTransferEvent;
use App\Http\Requests\SafeTransferRequest;
use App\Http\Requests\SalesRequest;
use App\Http\Resources\AccountsDefaultResources;
use App\Http\Resources\BondsTypeApiResources;
use App\Http\Resources\BrandsResources;
use App\Http\Resources\CreditStoresResources;
use App\Http\Resources\CrmDefaultResources;
use App\Http\Resources\CustomerAccountStatementResources;
use App\Http\Resources\CustomersAddressesResources;
use App\Http\Resources\CustomersResources;
use App\Http\Resources\CustomPrintResources;
use App\Http\Resources\DefaultCompanyResources;
use App\Http\Resources\DefaultShowHideResources;
use App\Http\Resources\DelegateCollectionResources;
use App\Http\Resources\EducationResources;
use App\Http\Resources\ArEnNameResources;
use App\Http\Resources\EmpMailResources;
use App\Http\Resources\GroupsParentResources;
use App\Http\Resources\ItemsGroupsResources;
use App\Http\Resources\ItineraryClientResources;
use App\Http\Resources\ItineraryResources;
use App\Http\Resources\MovesTypeApiResources;
use App\Http\Resources\MyHolidaysResources;
use App\Http\Resources\MyMettingResources;
use App\Http\Resources\MyMissionsResources;
use App\Http\Resources\NameResources;
use App\Http\Resources\HolidaysTypesResources;
use App\Http\Resources\IntroResources;
use App\Http\Resources\ModulesResources;
use App\Http\Resources\NotificationsResources;
use App\Http\Resources\PrevMettingResources;
use App\Http\Resources\PrivacyResources;
use App\Http\Resources\ProductInfoResources;
use App\Http\Resources\ProductInfoResourcesQty;
use App\Http\Resources\ProUnitsResources;
use App\Http\Resources\PurchasesDefaultResources;
use App\Http\Resources\ReportsSettingsResources;
use App\Http\Resources\ReturnSalesResources;
use App\Http\Resources\SafeTransfersResources;
use App\Http\Resources\SalesDefaultResources;
use App\Http\Resources\SalesOrderResources;
use App\Http\Resources\SalesResources;
use App\Http\Resources\ScreensApiResources;
use App\Http\Resources\ShiftsCodeResources;
use App\Http\Resources\ShiftsDetailsReportResources;
use App\Http\Resources\ShiftsReportResources;
use App\Http\Resources\StoresCostResources;
use App\Http\Resources\StoresDefaultResources;
use App\Http\Resources\StorsTransfersResources;
use App\Http\Resources\TarnsferStoresFilterResources;
use App\Http\Resources\TaxesResources;
use App\Http\Resources\TermsResources;
use App\Http\Resources\TotalDelegateCollectionResources;
use App\Http\Resources\UserResources;
use App\Mail\AdminResetPasswordApi;
use App\Models\AcccountingManual;
use App\Models\AccountsDefaultData;
use App\Models\Activites;
use App\Models\Addressses;
use App\Models\Admin;
use App\Models\AllGroups;
use App\Models\AssemblyProducts;
use App\Models\Branches;
use App\Models\Brands;
use App\Models\Campaigns;
use App\Models\ChecksTypes;
use App\Models\City;
use App\Models\ClientStatus;
use App\Models\Coins;
use App\Models\CommentsClients;
use App\Models\CompanyData;
use App\Models\CostCenter;
use App\Models\CrmDefaultData;
use App\Models\Customers;
use App\Models\CustomersGroup;
use App\Models\CustomersRateTypes;
use App\Models\CustomersTickets;
use App\Models\CustomPrint;
use App\Models\DefaultDataShowHide;
use App\Models\Employess;
use App\Models\EmpMail;
use App\Models\EmpPOSStores;
use App\Models\EmpRatio;
use App\Models\EmpSafes;
use App\Models\Event;
use App\Models\ExchangeCommissions;
use App\Models\ExpireDateQty;
use App\Models\FifoQty;
use App\Models\GeneralDaily;
use App\Models\Governrate;
use App\Models\Holidays;
use App\Models\HolidaysTypes;
use App\Models\Installment;
use App\Models\InstallmentCompanies;
use App\Models\InstallmentCompaniesRatios;
use App\Models\Interviews;
use App\Models\InterviewsTypes;
use App\Models\Intro;
use App\Models\ItemsGroups;
use App\Models\Itinerary;
use App\Models\ItineraryVisit;
use App\Models\Journalizing;
use App\Models\JournalizingDetails;
use App\Models\Missions;
use App\Models\Modules;
use App\Models\Notifications;
use App\Models\OutcomManufacturingModel;
use App\Models\PaymentVoucher;
use App\Models\PaymentVoucherDetails;
use App\Models\Places;
use App\Models\Platforms;
use App\Models\ProductMoves;
use App\Models\Products;
use App\Models\ProductSales;
use App\Models\ProductSalesOrder;
use App\Models\ProductsPurchases;
use App\Models\ProductsQty;
use App\Models\ProductsStartPeriods;
use App\Models\ProductsStoresTransfers;
use App\Models\ProductUnits;
use App\Models\PurchasesDefaultData;
use App\Models\RabihEducation;
use App\Models\Rate;
use App\Models\ReciptVoucher;
use App\Models\ReciptVoucherDetails;
use App\Models\ReportsSettings;
use App\Models\ReturnMaintainceBill;
use App\Models\ReturnSales;
use App\Models\SafesBanks;
use App\Models\SafeTransfers;
use App\Models\Sales;
use App\Models\SalesDefaultData;
use App\Models\SalesOrder;
use App\Models\Shifts;
use App\Models\ShippingCompany;
use App\Models\Stores;
use App\Models\StoresDefaultData;
use App\Models\StoresMoves;
use App\Models\StorsTransfers;
use App\Models\Taxes;
use App\Models\UsersMoves;
use App\Models\Vendors;
use App\Services\Average;
use App\Services\ChecksService;
use App\Services\SalesService;
use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use App\Traits\GeneralTrait;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;
use Spatie\DbDumper\Databases\PostgreSql;
use Str;
use File;

use App\Http\Resources\AdminResources;

class ApiDelegateAppController extends Controller
{
      use GeneralTrait;

    public function __construct(Request $request) {

        $header =!empty( $request->header('lang')) ? $request->header('lang') : "ar";
        app()->setLocale($header);

    }



    //Login
       public function LoginApi(Request $request){

  try {

            $rules = [
                "email" => "required",
                "password" => "required"

            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $code = $this->returnCodeAccordingToInput($validator);
                return $this->returnValidationError($code, $validator);
            }



      $rememberme = request('rememberme') == 1?true:false;

       if(auth()->guard('admin')->attempt(['email'=>request('email'),'password'=>request('password')],$rememberme)){


           $ad=Admin::where('email',request('email'))->first();

           if($ad->emp == 0){

               return $this->returnError(trans('admin.This_Acc_Not_Correct_For_Delegate_or_Employee'));
           }



     $dataUser=[
    'screen_ar'=>'تسجيل دخول التطبيق',
    'screen_en'=>'Login App',
    'type_ar'=>'تسجيل الدخول',
    'type_en'=>'Login',
    'explain_ar'=>request('email'),
    'explain_en'=>request('email'),
    ];
    $this->UserCustomMoves($dataUser);

     $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < 100 ; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }

           $ad=Admin::where('email',request('email'))->first();
           Admin::where('id',$ad->id)->update(['token'=>$randomString]);


     $Admin=Admin::where('email',request('email'))->first();
              $data=AdminResources::make($Admin);


             return $this->returnData('data', $data);



       }else{

             return $this->returnError(trans('admin.incorrect_information_login'));

       }


        } catch (\Exception $ex) {

            return $this->returnError($ex->getMessage());

        }catch (\Error $ex) {

            return $this->returnError($ex->getMessage());
        }

    }


    //TokenCheck
      public function TokenCheck(Request $request){

         $header = $request->header('Authorization', '');
   if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
   }

          $Admin=Admin::where('token',$x)->first();
          $data=AdminResources::make($Admin);

          return $this->returnData('data', $data);
    }


    //Forget Password
           public function forgotpasswordApi(){
         $admin = Admin::where('email',request('email'))->first();
               if(!empty($admin)){

                   if($admin->emp == 0){

                       return $this->returnError(trans('admin.This_Acc_Not_Correct_For_Delegate_or_Employee'));
                   }



                   $code=rand(10,10000);
                   Admin::where('id',$admin->id)->update(['code'=>$code]);

                   Mail::to($admin->email)->send(new AdminResetPasswordApi(['data'=>$admin,'code'=>$code]));


                   return $this->returnData('data', ['code'=> $code,'email'=>$admin->email]);



               }else{



                   return $this->returnError(trans('admin.WrongEmail'));


               }


        }

    //VerifyCode
     public function VerifyCode(){
         $admin = Admin::where('email',request('email'))->first();

               if($admin->code == request('code')){



                   return $this->returnSuccessMessage(trans('admin.Code_Success'));



               }else{

                   return $this->returnError(trans('admin.WrongCode'));
               }


        }

    //ResetPasswordApi
      public function ResetPasswordApi(){


         $admin = Admin::where('email',request('email'))->first();

          Admin::where('id',$admin->id)->update(
              [
                  'password'=>bcrypt(request('new_password')),
                  'code'=>null
              ]
          );

          return $this->returnSuccessMessage(trans('admin.success_reset'));



        }

    //LogoutApi
      public function LogoutApi(Request $request){

          $header = $request->header('Authorization', '');
          if (Str::startsWith($header, 'Bearer ')) {
              $x=Str::substr($header, 7);
          }

          $admin=Admin::where('token',$x)->first();

          Admin::where('id',$admin->id)->update(['token'=>null]);

          return $this->returnSuccessMessage(trans('admin.LogoutSuccess'));


 }

    //UpdateAdminProfile
     public function UpdateAdminProfile(Request $request){

          $header = $request->header('Authorization', '');
   if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
   }

       $admin=Admin::where('token',$x)->first();


            $data['phone']=request('phone');
            $data['name']=request('name');

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

            if(request()->has('old_password')){

                if (Hash::check(request('old_password'), $admin->password)) {
                  $data['password']  =bcrypt(request('new_password'));
                  Admin::where('id',$admin->id)->update($data);

                    return $this->returnSuccessMessage(trans('admin.Updated'));

                }else{



                    return $this->returnError(trans('admin.OldPasswordNotCorrect'));

                }
            }

         return $this->returnSuccessMessage(trans('admin.Updated'));


     }

    //indebtedness
    public function indebtedness(Request $request){

        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }

        $admin=Admin::where('token',$x)->first();


            $Array=array();


            $TotalDeb=DB::table('customers')

                ->where('customers.Responsible',$admin->emp)

                ->join('general_dailies', function ($join) {

                    $join->on('customers.Account', '=', 'general_dailies.Account');
                })

                ->get()->sum('Debitor_Coin');


            $TotalCred=DB::table('customers')

                ->where('customers.Responsible',$admin->emp)


                ->leftJoin('general_dailies', function ($join) {

                    $join->on('customers.Account', '=', 'general_dailies.Account');
                })

                ->get()->sum('Creditor_Coin');



            $x= $TotalDeb  - $TotalCred  ;


            $from=date('Y-m-01');
            $to=date('Y-m-t',strtotime('today'));

            $CurrentMonth=Sales::where('Delegate',$admin->emp)
                ->whereBetween('Date',[$from,$to])
                ->where('Edit',0)
                ->where('Delete',0)
                ->get()->sum('Total_Net');



            $Emp=Employess::find($admin->emp);


            if($Emp->MonthlyTarget != 0){
                $Target= ($CurrentMonth / $Emp->MonthlyTarget)  * 100  ;
            }else{

                $Target=  ($CurrentMonth / 100)  * 100 ;

            }



            array_push($Array,[
                'total_debt'=>$x,
                'monthly_target'=>$Target,
            ]);




            return response()->json([
                'status'=>200,
                'message'=>trans('admin.Success'),
                'data'=>$Array,

            ]);

    }

    //Location
    public function LocationTwo(Request $request){


        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }

        $admin=Admin::where('token',$x)->first();

        Admin::where('id',$admin->id)
            ->update(['lat'=>request('lat'),'long'=>request('long')]);


        return response()->json([
            'status'=>200,
            'msg'=>trans('admin.Location_Updated'),

        ]);



    }


    //========================= Default Data ============================

    //DefaultCompany
    public function DefaultCompany(Request $request){

        $item=CompanyData::latest('id')->first();
        $data=DefaultCompanyResources::make($item);


        return $this->returnData('data', $data);


    }

    //DefaultAccount
    public function DefaultAccount(Request $request){


        $item=AccountsDefaultData::latest('id')->first();
        $data=AccountsDefaultResources::make($item);


        return $this->returnData('data', $data);


    }

    //DefaultStore
    public function DefaultStore(Request $request){


        $item=StoresDefaultData::latest('id')->first();
        $data=StoresDefaultResources::make($item);


        return $this->returnData('data', $data);


    }

    //DefaultCrm
    public function DefaultCrm(Request $request){


        $item=CrmDefaultData::latest('id')->first();
        $data=CrmDefaultResources::make($item);

        return $this->returnData('data', $data);

    }


    //DefaultPurchases
    public function DefaultPurchases(Request $request){

        $item=PurchasesDefaultData::latest('id')->first();
        $data=PurchasesDefaultResources::make($item);

        return $this->returnData('data', $data);

    }


    //DefaultSales
    public function DefaultSales(Request $request){

        $item=SalesDefaultData::latest('id')->first();
        $data=SalesDefaultResources::make($item);

        return $this->returnData('data', $data);


    }


    //DefaultShowHide
    public function DefaultShowHide(Request $request){

        $item=DefaultDataShowHide::latest('id')->first();
        $data=DefaultShowHideResources::make($item);

        return $this->returnData('data', $data);

    }


    //IntroView
    public function IntroView(Request $request){

        $item=Intro::latest('id')->first();
        $data=IntroResources::make($item);

        return $this->returnData('data', $data);


    }


    //TermsView
    public function TermsView(Request $request){

        $item=Intro::latest('id')->first();
        $data=TermsResources::make($item);

        return $this->returnData('data', $data);


    }


    //PrivacyView
    public function PrivacyView(Request $request){

        $item=Intro::latest('id')->first();
        $data=PrivacyResources::make($item);

        return $this->returnData('data', $data);


    }

    //Notifications
    public function Notifications(Request $request){
        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }

        $admin=Admin::where('token',$x)->first();

        $item=Notifications::latest('id')->where('Status',0)->where('Emp',$admin->emp)->get();
        $data=NotificationsResources::collection($item);
        return $this->returnData('data', $data);
    }


//ReadNotifications
    public function ReadNotifications(Request $request){


        Notifications::where('id',request('id'))->update(['Status'=>1]);

        return response()->json([
            'status'=>200,
            'msg'=>trans('admin.Updated'),
        ]);



    }

//DeleteNotifications
    public function DeleteNotifications(Request $request){


        Notifications::where('id',request('id'))->delete();

        return response()->json([
            'status'=>200,
            'msg'=>trans('admin.Deleted'),
        ]);



    }

    //RabihEducation
    public function RabihEducation(Request $request){

        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }

        $admin=Admin::where('token',$x)->first();
        $Videos=RabihEducation::where('Package',$admin->package)->get();

        $data=EducationResources::collection($Videos);

        return $this->returnData('data', $data);

    }


    //Modules_SettingsPage
    public function Modules_SettingsApi(Request $request){

        $item=Modules::latest('id')->first();
        $data=ModulesResources::make($item);

        return $this->returnData('data', $data);

    }


    //EmpMailApi
    public function EmpMailApi(Request $request){

        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }

        $admin=Admin::where('token',$x)->first();
        $items=EmpMail::where('Status',0)->where('Emp',$admin->emp)->get();

        $data=EmpMailResources::collection($items);

        return $this->returnData('data', $data);

    }


    //ReadEmpMailApi
    public function ReadEmpMailApi(Request $request){


        EmpMail::where('id',request('id'))->update(['Status'=>1]);

        return response()->json([
            'status'=>200,
            'msg'=>trans('admin.Updated'),
        ]);



    }


//DefaultReportSettings

    public function DefaultReportSettings(Request $request){

        $item=ReportsSettings::latest('id')->first();
        $data=ReportsSettingsResources::make($item);

        return $this->returnData('data', $data);


    }


    //CustomPrint
    public function CustomPrintApi(Request $request){

        $item=CustomPrint::latest('id')->first();
        $data=CustomPrintResources::make($item);

        return $this->returnData('data', $data);


    }


    //========================= End Default Data ============================


    //========================= Addation  Data ============================

//Meetings Types
    public function MeetingsTypes(Request $request){

        $items=InterviewsTypes::all();
        $data=ArEnNameResources::collection($items);

        return $this->returnData('data', $data);

    }

//Rates Types
    public function RatesTypes(Request $request){

        $items=CustomersRateTypes::all();
        $data=ArEnNameResources::collection($items);

        return $this->returnData('data', $data);

    }

//Activites
    public function Activites(Request $request){

        $items=Activites::all();
        $data=ArEnNameResources::collection($items);

        return $this->returnData('data', $data);

    }

    //Platforms
    public function Platforms(Request $request){

        $items=Platforms::all();
        $data=ArEnNameResources::collection($items);

        return $this->returnData('data', $data);
    }


    //Campaigns
    public function Campaigns(Request $request){

        $items=Campaigns::all();
        $data=ArEnNameResources::collection($items);
        return $this->returnData('data', $data);

    }


    //ClientsStatus
    public function ClientsStatus(Request $request){

        $items=ClientStatus::all();
        $data=ArEnNameResources::collection($items);
        return $this->returnData('data', $data);

    }


    //Holiday Types
    public function HolidayTypesApi(Request $request){


        $items=HolidaysTypes::all();
        $data=HolidaysTypesResources::collection($items);
        return $this->returnData('data', $data);


    }

    //Taxes

    public function TaxesApi(Request $request){

        $items=Taxes::all();
        $data=TaxesResources::collection($items);
        return $this->returnData('data', $data);



    }

    //Brands
    public function AllBrands(Request $request){

        $items=Brands::get();
        $data=BrandsResources::collection($items);
        return $this->returnData('data', $data);


    }

    //Installment_Companies
    public function Installment_Companies(Request $request){

        $items=InstallmentCompanies::all();
        $data=ArEnNameResources::collection($items);
        return $this->returnData('data', $data);

    }

    //InstallCompanyFilter
    public function InstallCompanyFilter(Request $request){

        $id = $request->get('InstallCompany');
        $Total = $request->get('TotalNet');

        $Array=array();

        $Ratios=InstallmentCompaniesRatios::where('Company',$id)->get();

        foreach($Ratios as $rat){

            if($rat->From <= $Total and $rat->To >= $Total){

                $x=$rat->Service_Fee / 100 ;
                $y=$rat->Company_Precent / 100 ;

                $fee=$Total *  $x ;
                $prec=$fee *  $y ;
                $tot=$fee +  $y ;

                $fee= $fee - $prec ;

            }

        }


        array_push($Array,[
            'fees'=>$fee,
            'precent'=>$prec,
            'total'=>(int)$tot,

        ]);

        return response()->json([
            'status'=>200,
            'message'=>trans('admin.Success'),
            'data'=>$Array,

        ]);


    }

    //AllCheckTypes
    public function AllCheckTypes(Request $request){

        $items=ChecksTypes::all();
        $data=ArEnNameResources::collection($items);
        return $this->returnData('data', $data);

    }


    //Employes
    public function Employes(Request $request){

        $items=Employess::where("EmpSort", 1)->where('Active', 1)->get();
        $data=NameResources::collection($items);
        return $this->returnData('data', $data);

    }

    //Deliveries
    public function Deliveries(Request $request){

        $items=Employess::type()->where('Emp_Type','Delivery')->get();
        $data=NameResources::collection($items);

        return $this->returnData('data', $data);
    }

    //AllExecutors
    public function AllExecutors(Request $request){

        $items=Employess::type()->get();
        $data=NameResources::collection($items);

        return $this->returnData('data', $data);

    }


    //AllDelegates
    public function AllDelegates(Request $request){

        $items=Employess::type()->where('Emp_Type','Saller')->get();
        $data=NameResources::collection($items);

        return $this->returnData('data', $data);

    }


    //AllCoins
    public function AllCoins(Request $request){

        $items=Coins::all();
        $data=ArEnNameResources::collection($items);
        return $this->returnData('data', $data);

    }

    //AllStores
    public function AllStores(Request $request){

        $items=Stores::get();
        $data=NameResources::collection($items);

        return $this->returnData('data', $data);

    }


    //AllShippingCompanies
    public function AllShippingCompanies(Request $request){

        $items=ShippingCompany::get();
        $data=NameResources::collection($items);

        return $this->returnData('data', $data);

    }

    //AllBranches
    public function AllBranches(Request $request){
        $items=Branches::all();
        $data=ArEnNameResources::collection($items);
        return $this->returnData('data', $data);
    }

    //AllCustomersGroup
    public function AllCustomersGroup(Request $request){
        $items=CustomersGroup::all();
        $data=ArEnNameResources::collection($items);
        return $this->returnData('data', $data);
    }

    //AllCostCenter
    public function AllCostCenter(Request $request){

        $items=CostCenter::all();
        $data=ArEnNameResources::collection($items);
        return $this->returnData('data', $data);
    }

    //AllSafes
    public function AllSafes(Request $request){

        $items=AcccountingManual::whereIn('Parent',[28,29])->get();
        $data=NameResources::collection($items);

        return $this->returnData('data', $data);

    }

    //AllBanks
    public function AllBanks(Request $request){

        $items=AcccountingManual::where('Parent',29)->get();
        $data=NameResources::collection($items);

        return $this->returnData('data', $data);

    }

    //AllVendors
    public function AllVendors(Request $request){

        $items=AcccountingManual::where('Parent',37)->where('Type',1)->get();
        $data=NameResources::collection($items);
        return $this->returnData('data', $data);

    }

    //AllClients
    public function AllClients(Request $request){
        $items=AcccountingManual::where('Parent',24)->where('Type',1)->get();
        $data=NameResources::collection($items);
        return $this->returnData('data', $data);
    }

    //AllExpensesMainAccounts
    public function AllExpensesMainAccounts(Request $request){

        $AMsrfoat=AcccountingManual::where('id',20)->first();
        if($AMsrfoat->Parent == 0){

            $wordsss=$AMsrfoat->Code.'0';

        }else{

            $wordsss=$AMsrfoat->Code;

        }
        $items=AcccountingManual::where('Code', 'like', $wordsss.'%')->where('Type',0)->get();
        $data=NameResources::collection($items);
        return $this->returnData('data', $data);
    }

    //AllExpensesSubAccounts
    public function AllExpensesSubAccounts(Request $request){

        $AMsrfoat=AcccountingManual::where('id',20)->first();
        if($AMsrfoat->Parent == 0){

            $wordsss=$AMsrfoat->Code.'0';

        }else{

            $wordsss=$AMsrfoat->Code;

        }
        $items=AcccountingManual::where('Code', 'like', $wordsss.'%')->where('Type',1)->get();
        $data=NameResources::collection($items);
        return $this->returnData('data', $data);
    }

    //ExpensesAccounts
    public function ExpensesAccounts(Request $request){

        $items=AcccountingManual::where('Parent',55)->where('Type',1)->get();
        $data=NameResources::collection($items);
        return $this->returnData('data', $data);
    }


    //CreditAccount
    public function CreditAccount(Request $request){

        $debt=GeneralDaily::where('Account',request('client_id'))->get()->sum('Debitor');
        $crdt=GeneralDaily::where('Account',request('client_id'))->get()->sum('Creditor');
        $dif=$debt - $crdt ;
        return $this->returnData('data', number_format($dif,2));


    }

    //CreditSafes
    public function CreditSafes(Request $request){


        $debt=GeneralDaily::where('Account',request('safe_id'))->get()->sum('Debitor');
        $crdt=GeneralDaily::where('Account',request('safe_id'))->get()->sum('Creditor');
        $dif=$debt - $crdt ;
        return $this->returnData('data', number_format($dif,2));
    }

    //Governrates
    public function Governrates(Request $request){

        $items=Governrate::all();
        $data=ArEnNameResources::collection($items);
        return $this->returnData('data', $data);

    }

    //Cities
    public function Cities(Request $request){


        $items=City::all();
        $data=ArEnNameResources::collection($items);
        return $this->returnData('data', $data);


    }

    public function CitiesFilter(Request $request){

        $items=City::where('Gov',request('gov'))->get();
        $data=ArEnNameResources::collection($items);
        return $this->returnData('data', $data);

    }

    //Places
    public function Places(Request $request){


        $items=Places::all();
        $data=ArEnNameResources::collection($items);
        return $this->returnData('data', $data);


    }

    public function PlacesFilter(Request $request){
        $items=Places::where('City',request('city'))->get();
        $data=ArEnNameResources::collection($items);
        return $this->returnData('data', $data);
    }

    //AllUsers
    public function AllUsers(Request $request){

        $items=Admin::where('hidden',0)->get();
        $data=UserResources::collection($items);
        return $this->returnData('data', $data);
    }

    //Groups
    public function AllGroups(Request $request){

        $items=ItemsGroups::where('Sales_Show',1)->get();
        $data=ItemsGroupsResources::collection($items);
        return $this->returnData('data', $data);
    }


//GroupSingleFilterApi
    public function GroupSingleFilterApi(Request $request){

        $lang = $request->header('lang', '');
        AllGroups::truncate();
        $Group = $request->get('Group');
        $GroupR=ItemsGroups::find($Group);


        $gr['Group']=$GroupR->id;
        if($lang == 'ar' ){
            $gr['Name']=$GroupR->Name;
        }else{
            $gr['Name']=$GroupR->NameEn;
        }
        AllGroups::create($gr);


        $GRPS=ItemsGroups::where('Parent',$GroupR->id)->get();

        foreach($GRPS as $gb){

            $grs['Group']=$gb->id;

            if($lang == 'ar' ){
                $grs['Name']=$gb->Name;
            }else{
                $grs['Name']=$gb->NameEn;
            }
            AllGroups::create($grs);

            $GRPSSUB=ItemsGroups::where('Parent',$gb->id)->get();

            foreach($GRPSSUB as $gbA){

                $grsA['Group']=$gbA->id;
                if($lang == 'ar' ){
                    $grsA['Name']=$gbA->Name;
                }else{
                    $grsA['Name']=$gbA->NameEn;
                }
                AllGroups::create($grsA);

                $GRPSSUBA=ItemsGroups::where('Parent',$gbA->id)->get();

                foreach($GRPSSUBA as $gbB){

                    $grsB['Group']=$gbB->id;
                    if($lang == 'ar' ){
                        $grsB['Name']=$gbB->Name;
                    }else{
                        $grsB['Name']=$gbB->NameEn;
                    }
                    AllGroups::create($grsB);

                    $GRPSSUBB=ItemsGroups::where('Parent',$gbB->id)->get();

                    foreach($GRPSSUBB as $gbC){

                        $grsC['Group']=$gbC->id;
                        if($lang == 'ar' ){
                            $grsC['Name']=$gbC->Name;
                        }else{
                            $grsC['Name']=$gbC->NameEn;
                        }
                        AllGroups::create($grsC);

                        $GRPSSUBC=ItemsGroups::where('Parent',$gbC->id)->get();

                        foreach($GRPSSUBC as $gbD){

                            $grsD['Group']=$gbD->id;
                            if($lang == 'ar' ){
                                $grsD['Name']=$gbD->Name;
                            }else{
                                $grsD['Name']=$gbD->NameEn;

                            }
                            AllGroups::create($grsD);

                            $GRPSSUBE=ItemsGroups::where('Parent',$gbD->id)->get();

                            foreach($GRPSSUBE as $gbE){

                                $grsE['Group']=$gbE->id;

                                if($lang == 'ar' ){
                                    $grsE['Name']=$gbE->Name;
                                }else{
                                    $grsE['Name']=$gbE->NameEn;
                                }
                                AllGroups::create($grsE);

                                $GRPSSUBF=ItemsGroups::where('Parent',$gbE->id)->get();

                                foreach($GRPSSUBF as $gbF){

                                    $grsF['Group']=$gbF->id;
                                    if($lang == 'ar' ){
                                        $grsF['Name']=$gbF->Name;
                                    }else{
                                        $grsF['Name']=$gbF->NameEn;
                                    }
                                    AllGroups::create($grsF);

                                    $GRPSSUBG=ItemsGroups::where('Parent',$gbF->id)->get();

                                    foreach($GRPSSUBG as $gbG){

                                        $grsG['Group']=$gbG->id;
                                        if($lang == 'ar' ){
                                            $grsG['Name']=$gbG->Name;
                                        }else{

                                            $grsG['Name']=$gbG->NameEn;
                                        }
                                        AllGroups::create($grsG);

                                        $GRPSSUBH=ItemsGroups::where('Parent',$gbG->id)->get();

                                        foreach($GRPSSUBH as $gbH){

                                            $grsH['Group']=$gbH->id;
                                            if($lang == 'ar' ){
                                                $grsH['Name']=$gbH->Name;
                                            }else{
                                                $grsH['Name']=$gbH->NameEn;
                                            }
                                            AllGroups::create($grsH);

                                        }


                                    }


                                }


                            }


                        }


                    }


                }



            }


        }



        $states = AllGroups::orderBy('id','asc')->get();


        $data=GroupsParentResources::collection($states);
        return $this->returnData('data', $data);
    }

//BondsTypeApi
    public function BondsTypeApi(Request $request){

        $Types=GeneralDaily::select('Type','TypeEn')->distinct(['Type'])->get();
        $data=BondsTypeApiResources::collection($Types);
        return $this->returnData('data', $data);
    }

//MovesTypeApi
    public function MovesTypeApi(Request $request){

        $Types=UsersMoves::select('Type','TypeEn')->distinct(['Type'])->get();
        $data=MovesTypeApiResources::collection($Types);
        return $this->returnData('data', $data);
    }


    //ScreensApi
    public function ScreensApi(Request $request){

        $Screens=UsersMoves::select('Screen','ScreenEn')->distinct(['Screen'])->get();
        $data=ScreensApiResources::collection($Screens);
        return $this->returnData('data', $data);
    }



    //========================= End  Addation  Data ============================



    //========================  Delegate App =================================

//==========
    // Clients

    public function Clients(Request $request){
        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }

        $admin=Admin::where('token',$x)->first();


        $items=Customers::where('Responsible',$admin->emp)->get();
        $data=CustomersResources::collection($items);
        $x=[
'status'=>200,
'msg'=>trans('admin.Success'),
];

return $data->additional($x) ;

    }

    public function ClientsSechduleFilter(Request $request){

        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }

        $admin=Admin::where('token',$x)->first();


        $Code=request('search_code');
        $User=request('user');
        $Name=request('name');
        $Phone=request('phone');
        $Governrate=request('governrate');
        $City=request('city');
        $Place=request('place');
        $Activity=request('activity');
        $Responsible=request('responsible');

        $items=Customers::where('Responsible',$admin->emp)

            ->when(!empty($Code), function ($query) use ($Code) {
                return $query->where('SearchCode', $Code);
            })
            ->when(!empty($User), function ($query) use ($User) {
                return $query->where('User', $User);
            })
            ->when(!empty($Name), function ($query) use ($Name) {
                return $query->where('Name','ILIKE', "%{$Name}%");
            })
            ->when(!empty($Phone), function ($query) use ($Phone) {
                return $query->where('Phone', $Phone);
            })

            ->when(!empty($Governrate), function ($query) use ($Governrate) {
                return $query->where('Governrate', $Governrate);
            })
            ->when(!empty($City), function ($query) use ($City) {
                return $query->where('City', $City);
            })       ->when(!empty($Place), function ($query) use ($Place) {
                return $query->where('Place', $Place);
            })
            ->when(!empty($Activity), function ($query) use ($Activity) {
                return $query->where('Activity', $Activity);
            })
            ->when(!empty($Responsible), function ($query) use ($Responsible) {
                return $query->where('Responsible', $Responsible);
            })

            ->paginate(100);





        $data=CustomersResources::collection($items);
        $x=[
'status'=>200,
'msg'=>trans('admin.Success'),
];

return $data->additional($x) ;

    }

    //AddClient
    public function AddClient(Request $request){


        try {
            DB::beginTransaction();

            $header = $request->header('Authorization', '');
            if (Str::startsWith($header, 'Bearer ')) {
                $x=Str::substr($header, 7);
            }

            $admin=Admin::where('token',$x)->first();


            $rules = [
                "name" => "required",
            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $code = $this->returnCodeAccordingToInput($validator);
                return $this->returnValidationError($code, $validator);
            }


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

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

                $english_name=request('name');
            }


            $Acc=$this->CreateAccountApi(request('name'),$english_name ,24 ,null,$admin->id);
            $Code=$this->ReturnCode(Customers::class);


            $data['Code']=$Code;
            $data['Date']=date('Y-m-d');
            $data['Name']=request('name');
            $data['NameEn']=$english_name;
            $data['Price_Level']=request('price_level');
            $data['Phone']=request('phone');
            $data['Address']=request('address');
            $data['Company_Name']=request('company_name');
            $data['Governrate']=request('governrate_id');
            $data['City']=request('city_id');
            $data['Place']=request('place_id');
            $data['Responsible']=$admin->emp;
            $data['Activity']=request('activity_id');
            $data['Group']=request('group');
            $data['Account']=$Acc;
            $data['User']=$admin->id;
            $data['Phone2']=request('phone2');
            $data['SearchCode']=request('search_code');
            Customers::create($data);


            $dataUser=[
                'id'=>$admin->id,
                'screen_ar'=>'العملاء',
                'screen_en'=>'Clients',
                'explain_ar'=>request('name'),
                'explain_en'=>$english_name,
            ];
            $this->UserCreateMoves($dataUser);
            DB::commit();


            return $this->returnSuccessMessage(trans('admin.Added_Successfully'));


        } catch (\Exception $ex) {

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch (\Error $ex) {
            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());
        }

    }

    //EditClient
    public function EditClient(Request $request){


        try {
            DB::beginTransaction();

            $header = $request->header('Authorization', '');
            if (Str::startsWith($header, 'Bearer ')) {
                $x=Str::substr($header, 7);
            }

            $admin=Admin::where('token',$x)->first();


            $rules = [
                "name" => "required",
            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $code = $this->returnCodeAccordingToInput($validator);
                return $this->returnValidationError($code, $validator);
            }


            $dataX['Name']=request('name');
            $dataX['NameEn']=request('nameEn');
            AcccountingManual::where('id',request('account_id'))->update($dataX);

            $data['Date']=date('Y-m-d');
            $data['Name']=request('name');
            $data['NameEn']=request('nameEn');
            $data['Price_Level']=request('price_level');
            $data['Phone']=request('phone');
            $data['Address']=request('address');
            $data['Company_Name']=request('company_name');
            $data['Governrate']=request('governrate_id');
            $data['City']=request('city_id');
            $data['Place']=request('place_id');
            $data['Activity']=request('activity_id');
            $data['Group']=request('group');
            $data['Phone2']=request('phone2');
            $data['SearchCode']=request('search_code');
            Customers::where('id',request('client_id'))->update($data);


            $dataUser=[
                'id'=>$admin->id,
                'screen_ar'=>'العملاء',
                'screen_en'=>'Clients',
                'explain_ar'=>request('name'),
                'explain_en'=>request('nameEn'),
            ];
            $this->UserUpdateMoves($dataUser);
            DB::commit();


            return $this->returnSuccessMessage(trans('admin.Updated'));


        } catch (\Exception $ex) {

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch (\Error $ex) {
            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());
        }

    }


    //AddTicket
    public function AddTicket(Request $request){


        try {
            DB::beginTransaction();

            $rules = [
                "problem" => "required",
            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $code = $this->returnCodeAccordingToInput($validator);
                return $this->returnValidationError($code, $validator);
            }



            $header = $request->header('Authorization', '');
            if (Str::startsWith($header, 'Bearer ')) {
                $x=Str::substr($header, 7);
            }

            $admin=Admin::where('token',$x)->first();

            $Code=$this->ReturnCode(CustomersTickets::class);


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

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

                $english_name=request('problem');
            }

            $data['Code']=$Code;
            $data['Problem']=request('problem');
            $data['ProblemEn']=$english_name;
            $data['Status']=1;
            $data['Bill_Number']=request('bill_number');
            $data['Responsible']=request('responsible');
            $data['Customer']=request('client_id');
            $data['User']=$admin->id;

            CustomersTickets::create($data);


            $dataUser=[
                'id'=>$admin->id,
                'screen_ar'=>'تذاكر العملاء',
                'screen_en'=>'Clients Ticket',
                'explain_ar'=>$Code,
                'explain_en'=>$Code,
            ];
            $this->UserCreateMoves($dataUser);
            DB::commit();


            return $this->returnSuccessMessage(trans('admin.Added_Successfully'));


        } catch (\Exception $ex) {

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch (\Error $ex) {
            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());
        }



    }

    public function SolveTicketsClient(){


        try {
            DB::beginTransaction();


            $id=request('ticket_id');

            $del=CustomersTickets::find($id);
            CustomersTickets::where('id',$id)->update(['Status'=>2]);



            $cli=Customers::find($del->Customer);

            $notii['Date']=date('Y-m-d');
            $notii['Status']=0;
            $notii['Noti_Ar_Name']='حل تذكرة عميل';
            $notii['Noti_En_Name']='Solve Client Tiecket';
            $notii['Type']='تذاكر عملاء';
            $notii['TypeEn']='Client Tiecket';
            $notii['Type_Code']=$del->Code;
            $notii['Emp']=$del->Responsible;
            $notii['Client']=$cli->Account;
            $notii['Product']=null;
            $notii['Store']=null;
            $notii['Safe']=null;
            Notifications::create($notii);

            notify()->success(trans('admin.SolveTicketClient'));


            DB::commit();


            return $this->returnSuccessMessage(trans('admin.Solved'));


        } catch (\Exception $ex) {

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch (\Error $ex) {
            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());
        }



    }

    //AddComment
    public function AddComment(Request $request){

        try {
            DB::beginTransaction();

            $rules = [
                "comment" => "required",
            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $code = $this->returnCodeAccordingToInput($validator);
                return $this->returnValidationError($code, $validator);
            }



            $header = $request->header('Authorization', '');
            if (Str::startsWith($header, 'Bearer ')) {
                $x=Str::substr($header, 7);
            }

            $admin=Admin::where('token',$x)->first();

            $Code=$this->ReturnCode(CommentsClients::class);


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

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

                $english_name=request('comment');
            }

            $data['Code']=$Code;
            $data['Date']=date('Y-m-d');
            $data['Comment']=request('comment');
            $data['CommentEn']=$english_name;
            $data['Responsible']=$admin->emp;
            $data['Customer']=request('client_id');
            $data['Rate']=request('rate');
            $data['Visit_Cost']=request('visit_cost');
            $data['Note']=request('note');
            $data['Time']=date('H:i:s');
            $data['Type']=request('interview_type_id');
            $data['lat']=request('lat');
            $data['lng']=request('lng');

            CommentsClients::create($data);


            $dataUser=[
                'id'=>$admin->id,
                'screen_ar'=>'تعليقات العملاء',
                'screen_en'=>'Clients Comment',
                'explain_ar'=>$Code,
                'explain_en'=>$Code,
            ];
            $this->UserCreateMoves($dataUser);
            DB::commit();


            return $this->returnSuccessMessage(trans('admin.Added_Successfully'));


        } catch (\Exception $ex) {

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch (\Error $ex) {
            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());
        }



    }

    //AddMeet
    public function AddMeet(Request $request){

        try {
            DB::beginTransaction();

            $rules = [
                "date" => "required",
                "time" => "required",
                "meet_type" => "required",
            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $code = $this->returnCodeAccordingToInput($validator);
                return $this->returnValidationError($code, $validator);
            }



            $header = $request->header('Authorization', '');
            if (Str::startsWith($header, 'Bearer ')) {
                $x=Str::substr($header, 7);
            }

            $admin=Admin::where('token',$x)->first();

            $Code=$this->ReturnCode(Interviews::class);



            $data['Code']=$Code;
            $data['Date']=request('date');
            $data['Time']=request('time');
            $data['Status']=0;
            $data['Rate']=0;
            $data['Note']=request('note');
            $data['Emp']=$admin->emp;
            $data['Client']=request('client_id');
            $data['Type']=request('meet_type');
            $data['User']=$admin->id;


            Interviews::create($data);



            $dataUser=[
                'id'=>$admin->id,
                'screen_ar'=>'المقابلات',
                'screen_en'=>'Interviews',
                'explain_ar'=>$Code,
                'explain_en'=>$Code,
            ];
            $this->UserCreateMoves($dataUser);
            DB::commit();


            return $this->returnSuccessMessage(trans('admin.Added_Successfully'));


        } catch (\Exception $ex) {

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch (\Error $ex) {
            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());
        }


    }


//CustomerAddAddresses
    public function CustomerAddAddresses(Request $request){

        try {
            DB::beginTransaction();

            $rules = [
                "address_name" => "required",
                "governrate" => "required",
                "city" => "required",
                "place" => "required",
            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $code = $this->returnCodeAccordingToInput($validator);
                return $this->returnValidationError($code, $validator);
            }


            $Addr['Address_Name']=request('address_name');
            $Addr['Street']=request('street');
            $Addr['Special_Mark']=request('special_mark');
            $Addr['Buliding']=request('buliding');
            $Addr['Floor']=request('floor');
            $Addr['Flat']=request('flat');
            $Addr['Details']=request('details');
            $Addr['Location']=request('location');
            $Addr['Governrate']=request('governrate');
            $Addr['City']=request('city');
            $Addr['Place']=request('place');
            $Addr['Lat']=request('lat');
            $Addr['Lng']=request('lng');
            $Addr['Customer']=request('client_id');

            Addressses::create($Addr);


            DB::commit();


            return $this->returnSuccessMessage(trans('admin.Added_Successfully'));


        } catch (\Exception $ex) {

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch (\Error $ex) {
            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());
        }


    }

    public function CustomerEditAddresses(Request $request){

        try {
            DB::beginTransaction();

            $rules = [
                "address_name" => "required",
                "governrate" => "required",
                "city" => "required",
                "place" => "required",
            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $code = $this->returnCodeAccordingToInput($validator);
                return $this->returnValidationError($code, $validator);
            }


            $Addr['Address_Name']=request('address_name');
            $Addr['Street']=request('street');
            $Addr['Special_Mark']=request('special_mark');
            $Addr['Buliding']=request('buliding');
            $Addr['Floor']=request('floor');
            $Addr['Flat']=request('flat');
            $Addr['Details']=request('details');
            $Addr['Location']=request('location');
            $Addr['Governrate']=request('governrate');
            $Addr['City']=request('city');
            $Addr['Place']=request('place');
            $Addr['Lat']=request('lat');
            $Addr['Lng']=request('lng');
            $Addr['Customer']=request('client_id');

            Addressses::where('id',request('address_id'))->update($Addr);


            DB::commit();


            return $this->returnSuccessMessage(trans('admin.Updated'));


        } catch (\Exception $ex) {

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch (\Error $ex) {
            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());
        }


    }

    public function CustomerDeleteAddresses(Request $request){

        try {
            DB::beginTransaction();



            Addressses::where('id',request('address_id'))->delete();


            DB::commit();


            return $this->returnSuccessMessage(trans('admin.Deleted'));


        } catch (\Exception $ex) {

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch (\Error $ex) {
            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());
        }


    }


//MyMeetings
    public function MyMeetings(Request $request){

        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }

        $admin=Admin::where('token',$x)->first();


        $items=Interviews::where('Emp',$admin->emp)->where('Status',0)->get();
        $data=MyMettingResources::collection($items);
        return $this->returnData('data', $data);


    }

    public function PervMeetings(Request $request){

     //   $items=Interviews::where('Client',request('client_id'))->where('Status',1)->get();

        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }
        $admin=Admin::where('token',$x)->first();


        $items=Interviews::latest('id')->where('Emp',$admin->emp)->where('Status','!=',0)->get();
        $data=PrevMettingResources::collection($items);
        return $this->returnData('data', $data);

    }

    public function EndMeet(Request $request){


        try {
            DB::beginTransaction();

            $rules = [
                "biref" => "required",
            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $code = $this->returnCodeAccordingToInput($validator);
                return $this->returnValidationError($code, $validator);
            }



            Interviews::where('id',request('meet_id'))
                ->update(['StatusNote'=>request('biref'),'Status'=>1]);
            DB::commit();


            return $this->returnSuccessMessage(trans('admin.End_Meeting_Successfully'));


        } catch (\Exception $ex) {

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch (\Error $ex) {
            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());
        }


    }


    public function AddNewMeetApi(Request $request){

        try {
            DB::beginTransaction();


            $rules = [
                "biref" => "required",
                "Date" => "required",
                "Time" => "required",
                "employee_id" => "required",
                "client_id" => "required",
                "type_id" => "required",
            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $code = $this->returnCodeAccordingToInput($validator);
                return $this->returnValidationError($code, $validator);
            }



            $header = $request->header('Authorization', '');
            if (Str::startsWith($header, 'Bearer ')) {
                $x=Str::substr($header, 7);
            }

            $admin=Admin::where('token',$x)->first();



            $data['Date']=request('Date');
            $data['Time']=request('Time');
            $data['Status']=1;
            $data['Rate']=0;
            $data['Note']=null;
            $data['StatusNote']=request('biref');
            $data['Emp']=request('employee_id');
            $data['Client']=request('client_id');
            $data['Type']=request('type_id');
            $data['User']=$admin->id;
            Interviews::create($data);

            $cli=Customers::find(request('client_id'));

            $CODE=Interviews::latest('id')->first()->Code;


            $event['Start_Date']=request('Date');
            $event['End_Date']=request('Date');
            $event['Event_Ar_Name']='مقابلة';
            $event['Event_En_Name']='Meet';
            $event['Type']='المقابلات';
            $event['Type_ID']=null;
            $event['Type_Code']=$CODE;
            $event['Emp']=request('employee_id');
            $event['Client']=$cli->Account;
            $event['Product']=null;
            $event['Customer']=null;
            Event::create($event);


            $notii['Date']=date('Y-m-d');
            $notii['Status']=0;
            $notii['Noti_Ar_Name']='مقابلة جديدة';
            $notii['Noti_En_Name']='New Meet';
            $notii['Type']='المقابلات';
            $notii['TypeEn']='Interviews';
            $notii['Type_Code']=$CODE;
            $notii['Emp']=request('employee_id');
            $notii['Client']=$cli->Account;
            $notii['Product']=null;
            $notii['Store']=null;
            $notii['Safe']=null;
            Notifications::create($notii);
            notify()->success(trans('admin.NewMeet'));

            $dataUser=[
                'id'=>$admin->id,
                'screen_ar'=>'المقابلات',
                'screen_en'=>'Interviews',
                'explain_ar'=>$CODE,
                'explain_en'=>$CODE,
            ];
            $this->UserCreateMoves($dataUser);

            DB::commit();


            return $this->returnSuccessMessage(trans('admin.Added_Successfully'));

        } catch (\Exception $ex) {

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch (\Error $ex) {
            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());
        }

    }



    //MyMission
    public function MyMission(Request $request){


        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }

        $admin=Admin::where('token',$x)->first();


        $items=Missions::where('Task_Owner',$admin->emp)->where('Status',1)->get();
        $data=MyMissionsResources::collection($items);
        return $this->returnData('data', $data);



    }

    //SureMyMission
    public function SureMyMission(Request $request){


        try {
            DB::beginTransaction();

            $rules = [
                "mission_id" => "required",
            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $code = $this->returnCodeAccordingToInput($validator);
                return $this->returnValidationError($code, $validator);
            }



            Missions::where('id',request('mission_id'))->update(['Status'=>2]);
            DB::commit();


            return $this->returnSuccessMessage(trans('admin.End_Meeting_Successfully'));


        } catch (\Exception $ex) {

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch (\Error $ex) {
            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());
        }





    }

    //HoildayRequest
    public function MyHoildayRequests(Request $request){


        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }

        $admin=Admin::where('token',$x)->first();


        $items=Holidays::where('Emp',$admin->emp)->where('Status',1)->get();
        $data=MyHolidaysResources::collection($items);
        return $this->returnData('data', $data);



    }


    public function AddHoildayRequest(Request $request){

        try {
            DB::beginTransaction();

            $rules = [
                "mission_id" => "required",
            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $code = $this->returnCodeAccordingToInput($validator);
                return $this->returnValidationError($code, $validator);
            }



            $header = $request->header('Authorization', '');
            if (Str::startsWith($header, 'Bearer ')) {
                $x=Str::substr($header, 7);
            }

            $admin=Admin::where('token',$x)->first();

            $Code=$this->ReturnCode(Holidays::class);

            $data['Code']=$Code;
            $data['Date']=request('Date');
            $data['Month']=request('Month');
            $data['Num_of_Days']=request('Num_of_Days');
            $data['Start_Date']=request('Start_Date');
            $data['Discount']=request('Discount');
            $data['Status']=1;
            $data['Note']=request('Note');
            $data['Emp']=$admin->emp;
            $data['Type']=request('Type');
            $data['User']=$admin->id;

            Holidays::create($data);
            DB::commit();


            return $this->returnSuccessMessage(trans('admin.End_Meeting_Successfully'));


        } catch (\Exception $ex) {

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch (\Error $ex) {
            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());
        }



    }

    //========


    //=====  Reports  =====================

    //StoresCost
    public function StoresCost(Request $request){

            $search = $request->get('search');
            $store = $request->get('store');
            $group = $request->get('group');
            $Zero = $request->get('zero');

            $Array=array();

            if($Zero == 0){
                $Prods=ProductsQty::whereRelation('Product', 'Status', 0)

                    ->whereRelation('Product',function ($query)  {

                        $query->whereIn('P_Type',['Completed','Raw','Industrial','Additions','Serial','Single_Variable','Duble_Variable']);


                    })


                    ->when(!empty($group), function ($query) use ($group) {
                        return $query->whereIn('Group', $group);
                    })

                    ->when(!empty($search), function ($query) use ($search) {
                        return $query->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}%")
                            ;
                    })

                    ->where('Store',$store)
                    ->paginate(50);
            }else{
                $Prods=ProductsQty::whereRelation('Product', 'Status', 0)

                    ->whereRelation('Product',function ($query)  {

                        $query->whereIn('P_Type',['Completed','Raw','Industrial','Additions','Serial','Single_Variable','Duble_Variable']);


                    })
                    ->where('Qty','!=',0)

                    ->when(!empty($group), function ($query) use ($group) {
                        return $query->where('Group', $group);
                    })

                    ->when(!empty($search), function ($query) use ($search) {
                        return $query->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}%")
                            ;
                    })
                    ->where('Store',$store)
                    ->paginate(50);
            }


            if($Zero == 0){
                $Products_Num=ProductsQty::whereRelation('Product', 'Status', 0)

                    ->whereRelation('Product',function ($query)  {

                        $query->whereIn('P_Type',['Completed','Raw','Industrial','Additions','Serial','Single_Variable','Duble_Variable']);


                    })


                    ->when(!empty($group), function ($query) use ($group) {
                        return $query->where('Group', $group);
                    })




                    ->when(!empty($search), function ($query) use ($search) {
                        return $query->where('P_Ar_Name','ILIKE', "%{$search}%" )->orWhere('P_Code','ILIKE', "%{$search}%");
                    })

                    ->where('Store',$store)
                    ->count();



                $Total_Qty=ProductsQty::whereRelation('Product', 'Status', 0)

                    ->whereRelation('Product',function ($query)  {

                        $query->whereIn('P_Type',['Completed','Raw','Industrial','Additions','Serial','Single_Variable','Duble_Variable']);


                    })




                    ->when(!empty($group), function ($query) use ($group) {
                        return $query->where('Group', $group);
                    })




                    ->when(!empty($search), function ($query) use ($search) {
                        return $query->where('P_Ar_Name','ILIKE', "%{$search}%" )->orWhere('P_Code','ILIKE', "%{$search}%");
                    })
                    ->where('Store',$store)
                    ->get()->sum('Qty');

                $Total_Cost=ProductsQty::whereRelation('Product', 'Status', 0)

                    ->whereRelation('Product',function ($query)  {

                        $query->whereIn('P_Type',['Completed','Raw','Industrial','Additions','Serial','Single_Variable','Duble_Variable']);


                    })




                    ->when(!empty($group), function ($query) use ($group) {
                        return $query->where('Group', $group);
                    })




                    ->when(!empty($search), function ($query) use ($search) {
                        return $query->where('P_Ar_Name','ILIKE', "%{$search}%" )->orWhere('P_Code','ILIKE', "%{$search}%");
                    })
                    ->where('Store',$store)
                    ->get()->sum('TotalCost');
            }else{

                $Products_Num=ProductsQty::whereRelation('Product', 'Status', 0)

                    ->whereRelation('Product',function ($query)  {

                        $query->whereIn('P_Type',['Completed','Raw','Industrial','Additions','Serial','Single_Variable','Duble_Variable']);


                    })

                        ->where('Qty','!=',0)


                    ->when(!empty($group), function ($query) use ($group) {
                        return $query->where('Group', $group);
                    })




                    ->when(!empty($search), function ($query) use ($search) {
                        return $query->where('P_Ar_Name','ILIKE', "%{$search}%" )->orWhere('P_Code','ILIKE', "%{$search}%");
                    })

                    ->where('Store',$store)
                    ->count();



                $Total_Qty=ProductsQty::where('Qty','!=',0)->whereRelation('Product', 'Status', 0)

                    ->whereRelation('Product',function ($query)  {

                        $query->whereIn('P_Type',['Completed','Raw','Industrial','Additions','Serial','Single_Variable','Duble_Variable']);


                    })




                    ->when(!empty($group), function ($query) use ($group) {
                        return $query->where('Group', $group);
                    })




                    ->when(!empty($search), function ($query) use ($search) {
                        return $query->where('P_Ar_Name','ILIKE', "%{$search}%" )->orWhere('P_Code','ILIKE', "%{$search}%");
                    })
                    ->where('Store',$store)
                    ->get()->sum('Qty');

                $Total_Cost=ProductsQty::where('Qty','!=',0)->whereRelation('Product', 'Status', 0)

                    ->whereRelation('Product',function ($query)  {

                        $query->whereIn('P_Type',['Completed','Raw','Industrial','Additions','Serial','Single_Variable','Duble_Variable']);


                    })




                    ->when(!empty($group), function ($query) use ($group) {
                        return $query->where('Group', $group);
                    })




                    ->when(!empty($search), function ($query) use ($search) {
                        return $query->where('P_Ar_Name','ILIKE', "%{$search}%" )->orWhere('P_Code','ILIKE', "%{$search}%");
                    })
                    ->where('Store',$store)
                    ->get()->sum('TotalCost');


            }


        $data=StoresCostResources::collection($Prods);
        $x=[
            'status'=>200,
            'msg'=>trans('admin.Success'),
            'products_number'=>$Products_Num,
            'total_qty'=>$Total_Qty,
            'total_cost'=>$Total_Cost,
        ];

        return $data->additional($x) ;


    }

    //CreditStores
    public function CreditStores(Request $request){

        $search = $request->get('search');
        $store = $request->get('store');
        $group = $request->get('group');
        $Zero = $request->get('zero');

        if($Zero == 0){
            $Prods=ProductsQty::whereRelation('Product', 'Status', 0)

                ->whereRelation('Product',function ($query)  {

                    $query->whereIn('P_Type',['Completed','Raw','Industrial','Additions','Serial','Single_Variable','Duble_Variable']);


                })


                ->when(!empty($group), function ($query) use ($group) {
                    return $query->whereIn('Group', $group);
                })

                ->when(!empty($search), function ($query) use ($search) {
                    return $query->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}%")
                        ;
                })

                ->where('Store',$store)
                ->paginate(50);
        }else{
            $Prods=ProductsQty::whereRelation('Product', 'Status', 0)

                ->whereRelation('Product',function ($query)  {

                    $query->whereIn('P_Type',['Completed','Raw','Industrial','Additions','Serial','Single_Variable','Duble_Variable']);


                })
                ->where('Qty','!=',0)

                ->when(!empty($group), function ($query) use ($group) {
                    return $query->where('Group', $group);
                })

                ->when(!empty($search), function ($query) use ($search) {
                    return $query->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}%")
                        ;
                })
                ->where('Store',$store)
                ->paginate(50);
        }


        if($Zero == 0){
            $Products_Num=ProductsQty::whereRelation('Product', 'Status', 0)

                ->whereRelation('Product',function ($query)  {

                    $query->whereIn('P_Type',['Completed','Raw','Industrial','Additions','Serial','Single_Variable','Duble_Variable']);


                })


                ->when(!empty($group), function ($query) use ($group) {
                    return $query->where('Group', $group);
                })




                ->when(!empty($search), function ($query) use ($search) {
                    return $query->where('P_Ar_Name','ILIKE', "%{$search}%" )->orWhere('P_Code','ILIKE', "%{$search}%");
                })

                ->where('Store',$store)
                ->count();



            $Total_Qty=ProductsQty::whereRelation('Product', 'Status', 0)

                ->whereRelation('Product',function ($query)  {

                    $query->whereIn('P_Type',['Completed','Raw','Industrial','Additions','Serial','Single_Variable','Duble_Variable']);


                })




                ->when(!empty($group), function ($query) use ($group) {
                    return $query->where('Group', $group);
                })




                ->when(!empty($search), function ($query) use ($search) {
                    return $query->where('P_Ar_Name','ILIKE', "%{$search}%" )->orWhere('P_Code','ILIKE', "%{$search}%");
                })
                ->where('Store',$store)
                ->get()->sum('Qty');


        }else{

            $Products_Num=ProductsQty::whereRelation('Product', 'Status', 0)

                ->whereRelation('Product',function ($query)  {

                    $query->whereIn('P_Type',['Completed','Raw','Industrial','Additions','Serial','Single_Variable','Duble_Variable']);


                })

                ->where('Qty','!=',0)


                ->when(!empty($group), function ($query) use ($group) {
                    return $query->where('Group', $group);
                })




                ->when(!empty($search), function ($query) use ($search) {
                    return $query->where('P_Ar_Name','ILIKE', "%{$search}%" )->orWhere('P_Code','ILIKE', "%{$search}%");
                })

                ->where('Store',$store)
                ->count();



            $Total_Qty=ProductsQty::where('Qty','!=',0)->whereRelation('Product', 'Status', 0)

                ->whereRelation('Product',function ($query)  {

                    $query->whereIn('P_Type',['Completed','Raw','Industrial','Additions','Serial','Single_Variable','Duble_Variable']);


                })




                ->when(!empty($group), function ($query) use ($group) {
                    return $query->where('Group', $group);
                })




                ->when(!empty($search), function ($query) use ($search) {
                    return $query->where('P_Ar_Name','ILIKE', "%{$search}%" )->orWhere('P_Code','ILIKE', "%{$search}%");
                })
                ->where('Store',$store)
                ->get()->sum('Qty');



        }


        $data=CreditStoresResources::collection($Prods);
        $x=[
            'status'=>200,
            'msg'=>trans('admin.Success'),
            'products_number'=>$Products_Num,
            'total_qty'=>$Total_Qty,

        ];
        return $data->additional($x) ;


    }

    //ProductInfo
    public function ProductInfo(Request $request){

        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }

        $admin=Admin::where('token',$x)->first();
            $search = $request->get('search');

        $Prs=$this->FilterProductQty($search,$admin->store);
        $data=$this->FilterProduct($search);

            if(!empty($data)){
                $result=ProductInfoResources::collection($data);
            }

        if(count($data) == 0) {
            if (!empty($Prs)) {
                $result = ProductInfoResourcesQty::collection($Prs);
            }
        }
        $x=[
            'status'=>200,
            'msg'=>trans('admin.Success'),
        ];
        return $result->additional($x) ;




    }

    //DelegateCollectionReport
    public function DelegateCollectionReport(Request $request){

        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }
        $admin=Admin::where('token',$x)->first();
        $Custs=Customers::where('Responsible',$admin->emp)->paginate(20);
        $data=DelegateCollectionResources::collection($Custs);
        $x=[
            'status'=>200,
            'msg'=>trans('admin.Success'),
        ];
        return $data->additional($x) ;


    }


    //Total Delegate Collection
    public function TotalDelegateCollectionReport(Request $request){

        $from = $request->get('from');
        $to = $request->get('to');
        $account = $request->get('account_id');
        $Collector = $request->get('collector_id');

        $items =ReciptVoucherDetails::whereRelation('RV_ID', function ($query) use ($from,$to,$Collector) {
            return $query->whereBetween('Date',  [$from, $to])->where('Collector',$Collector);
        })
            ->when(!empty($account), function ($query) use ($account) {
                return $query->where('Account',$account);

            })
            ->paginate(50);


        $total =ReciptVoucherDetails::whereRelation('RV_ID', function ($query) use ($from,$to,$Collector) {

            return $query->whereBetween('Date',  [$from, $to])->where('Collector',$Collector);
        })
            ->when(!empty($account), function ($query) use ($account) {
                return $query->where('Account',$account);

            })
            ->get()->sum('Creditor');

        $result = TotalDelegateCollectionResources::collection($items);

        $x=[
            'status'=>200,
            'msg'=>trans('admin.Success'),
            'total'=>$total,
        ];
        return $result->additional($x) ;




    }

    //Shifts Report
    public function ShiftsReport(Request $request){

        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }

        $admin=Admin::where('token',$x)->first();


        $Shift = $request->get('shift_id');



        $Shifts=Shifts::where('Emp',$admin->emp)


            ->when(!empty($Shift), function ($query) use ($Shift) {
                return $query->where('Code',$Shift);

            })

            ->where('Close',1)
            ->paginate(20);




        $result = ShiftsReportResources::collection($Shifts);

        $x=[
            'status'=>200,
            'msg'=>trans('admin.Success'),
        ];
        return $result->additional($x) ;




    }


    //ShiftsCode
    public function ShiftsCodeApi(Request $request){


        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }

        $admin=Admin::where('token',$x)->first();


        $Shifts=Shifts::where('Emp',$admin->emp)

            ->where('Close',1)
            ->get();


        $data=ShiftsCodeResources::collection($Shifts);
        return $this->returnData('data', $data);




    }



    //ShiftsDetailsApi
    public function ShiftsDetailsApi(Request $request){

        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }

        $admin=Admin::where('token',$x)->first();

        $Shift = $request->get('shift_id');


        $Shifts=Shifts::where('Emp',$admin->emp)


            ->when(!empty($Shift), function ($query) use ($Shift) {
                return $query->where('Code',$Shift);

            })

            ->where('Close',1)
            ->paginate(20);




        $data = ShiftsDetailsReportResources::collection($Shifts);

        return $this->returnData('data', $data);




    }


//EmpCommission
    public function EmpCommission(Request $request,Average $average){

        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }

        $admin=Admin::where('token',$x)->first();

        $Emp = $admin->emp;


        $EXX=ExchangeCommissions::where('Emp',$Emp)->get()->sum('Amount');
        $returns=ReturnMaintainceBill::where('Eng',$Emp)->get();

        $co=0;
        $s=0;
        $e=0;
        $sR=0;
        $totalcost=0;
        $ReturnCount=0;

        foreach($returns as $ret){

            $i= $ret->Cost_Precent / 100 ;
            $ii= $i *  $ret->Total_Cost ;
            $co += $ii ;

        }

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

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

        $ReturnSales=ReturnSales::all();

        foreach($ReturnSales as $RS){
            if($RS->Sales()->first()->Delegate == $Emp){

                $ReturnCount +=1;

            }
        }

        $products=ProductSales::where('Executor',$Emp)->get();
        $Executors=ProductSales::where('Executor',$Emp)->get()->sum('Total');


        $Name=Employess::find($Emp);
        foreach($products as $pro){

            $plow=ProductUnits::where('Product',$pro->Product)->where('Rate',1)->first();
            $unit=ProductUnits::where('Product',$pro->Product)->where('Def',1)->first();




            $def=StoresDefaultData::orderBy('id','desc')->first();

            $totCost=$average->AverageCostGetUnit($pro->Product,$pro->P_Code,$pro->Store,$pro->Unit);

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


                $totCost=0;





                $rr = ProductUnits::where("Unit",$plow->Unit)->where('Product',$pro->Product)->first();


                $fifo =FifoQty::
                where('Store',$pro->Store)
                    ->where('Product',$pro->Product)
                    ->where('P_Code',$plow->Barcode)
                    ->orderBy('Purchases_Date','asc')
                    ->first();

                if(empty($fifo)){

                    $fifo =FifoQty::
                    where('Store',$pro->Store)
                        ->where('Product',$pro->Product)
                        ->where('PP_Code',$plow->Barcode)
                        ->orderBy('Purchases_Date','asc')
                        ->first();

                    if(empty($fifo)){

                        $fifo =FifoQty::
                        where('Store',$pro->Store)
                            ->where('Product',$pro->Product)
                            ->where('PPP_Code',$plow->Barcode)
                            ->orderBy('Purchases_Date','asc')
                            ->first();


                        if(empty($fifo)){

                            $fifo =FifoQty::
                            where('Store',$pro->Store)
                                ->where('Product',$pro->Product)
                                ->where('PPPP_Code',$plow->Barcode)
                                ->orderBy('Purchases_Date','asc')
                                ->first();

                        }

                    }

                }

                if(!empty($fifo)){

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



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


                        if($NNQuntatity == 0){


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


                        }else{



                            if($NNQuntatity >= $pro->Qty){

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

                            }else{

                                $res=$pro->Qty - $NNQuntatity ;


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

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

                                $totCost +=$ResdiualCost;

                            }


                        }



                    }else{


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

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

                        }else{

                            $res=$pro->Qty - $fifo->Qty ;


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

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

                            $totCost +=$ResdiualCost;

                        }



                    }


                }



                $CostS=$this->AverageCostGet($pro->Product,$plow->Barcode,$pro->Store);

                if(!empty($purchs) or !empty($purchsStart) or !empty($storesTransfer) or !empty($OUTCOME)){




                    $totalcost=$totCost;








                }else{





                    $CostS=$this->AverageCostGet($pro->Product,$plow->Barcode,$pro->Store);

                    if(!empty($purchs) or !empty($purchsStart) or !empty($storesTransfer) or !empty($OUTCOME)){



                        if($CostS != 0){
                            $Average = $CostS * $unit->Rate ;
                            $totalcost += ($Average * $pro->Qty) ;
                        }else{

                            $totalcost += ($CostS *  $unit->Rate) * $pro->Qty;
                        }

                    }else{

                        $totalcost +=0;
                    }







                }








                $Emppp=Employess::find($Emp);

                if($Emppp->Emp_Type == 'Engineer'){
                    $diff= $sales  - $totalcost ;
                }else{

                    $diff= $Executors  ;
                }

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

                foreach($Ratios as $r){

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

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

                            $x=$r->Rate  / 100 ;
                            $xx= $x *  $sales ;
                            $s+=$xx;

                        }else{

                            $s+=0;

                        }


                    }


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

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

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

                        }else{

                            $e+=0;

                        }


                    }


                }




            }
        }

        $diff= $Executors   - $totalcost ;

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

        $Recipts=ReciptVoucher::where('Status',1)->where('Collector',$Emp)->get()->sum('Total_Creditor');



        foreach($Ratios as $r){

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

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

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

                }else{

                    $e+=0;

                }


            }

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

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


                    $xR=$r->Rate  / 100 ;
                    $xxR= $xR *  $Recipts ;
                    $sR+=$xxR;

                }else{

                    $sR+=0;

                }


            }


        }



        $result = ( $s + $e )  -  $co ;

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


        }else{

            $neame=$Name->NameEn;
        }

        $Array=[];

        array_push($Array,[
            "name"=>$neame,
            "type"=>$Name->Emp_Type,
            "precentage_of_sales"=>number_format((float)abs($s), 2, '.', ''),
            "precentage_of_execute"=>number_format((float)abs($e), 2, '.', ''),
            "total_paid_commisssion"=>number_format((float)abs($EXX), 2, '.', ''),
            "total_commission"=>number_format((float)abs($result), 2, '.', ''),
            "number_of_sales_bill"=>number_format((float)abs($salesCount), 2, '.', ''),
            "number_of_return_sales_bill"=>number_format((float)abs($ReturnCount), 2, '.', ''),
            "collection"=>number_format((float)abs($sR), 2, '.', ''),
        ]);

        return response()->json([
            'status'=>200,
            'msg'=>trans('admin.Updated'),
            'data'=>$Array,
        ]);






    }



    //CustomerAccountStatement
    public function CustomerAccountStatement(Request $request){

        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }
        $admin=Admin::where('token',$x)->first();

        $lang = $request->header('lang', '');


            $from = $request->get('from');
            $to = $request->get('to');
            $account = $request->get('account');


                $items =DB::table('general_dailies')->whereBetween('Date', [$from, $to])

                    ->when(!empty($account), function ($query) use ($account) {
                        return $query->where('Account',$account);

                    })

                    ->paginate(50);

        $totalD =GeneralDaily::whereBetween('Date', [$from, $to])

            ->when(!empty($account), function ($query) use ($account) {
                return $query->where('Account',$account);

            })

            ->get()->sum('Debitor_Coin');

        $totalC =GeneralDaily::whereBetween('Date', [$from, $to])

            ->when(!empty($account), function ($query) use ($account) {
                return $query->where('Account',$account);

            })

            ->get()->sum('Creditor_Coin');



        $totalN =GeneralDaily::whereBetween('Date', [$from, $to])

            ->when(!empty($account), function ($query) use ($account) {
                return $query->where('Account',$account);

            })

            ->count();


        $D =GeneralDaily::

            when(!empty($account), function ($query) use ($account) {
                return $query->where('Account',$account);

            })

            ->get()->sum('Debitor_Coin');

        $C =GeneralDaily::

            when(!empty($account), function ($query) use ($account) {
                return $query->where('Account',$account);

            })

            ->get()->sum('Creditor_Coin');


        $user=AcccountingManual::find($account);
        $creditPeriod=$totalD - $totalC;
        $credit=$D - $C;


        $result = CustomerAccountStatementResources::collection($items);

        $x=[
            'status'=>200,
            'msg'=>trans('admin.Success'),
            'total_debitor'=>number_format((float)$totalD, 2, '.', ''),
            'total_creditor'=>number_format((float)$totalC, 2, '.', ''),
            'count'=>$totalN,
            'from'=>$from,
            'to'=>$to,
            'account'=>$user->Name,
            'credit_period'=>$creditPeriod,
            'credit'=>$credit,
        ];
        return $result->additional($x) ;





    }




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

    //==   Stores and Safes Transfer  ==================


    //Safe Transfers
    public function SafeTransfersCode(Request $request){
        $Code=$this->ReturnCode(SafeTransfers::class);
          return $this->returnData('data',$Code,trans('admin.Success'));
    }

    public function AddSafeTransfersApi(Request $request){

   try {

       DB::beginTransaction();

       $header = $request->header('Authorization', '');
       if (Str::startsWith($header, 'Bearer ')) {
           $x=Str::substr($header, 7);
       }
       $admin=Admin::where('token',$x)->first();


       $rules = [
           'Date'=>'required',
           'Draw'=>'required',
           'Amount'=>'required',
           'From_Safe'=>'required',
           'To_Safe'=>'required',
           'Coin'=>'required',
       ];

       $validator = Validator::make($request->all(), $rules);

       if ($validator->fails()) {
           $code = $this->returnCodeAccordingToInput($validator);
           return $this->returnValidationError($code, $validator);
       }


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

       $data['Delegate']=$admin->emp;
       $data['Time']=date("h:i:s a", time());
       $data['Date']=request('Date');
       $data['Draw']=request('Draw');
       $data['Amount']=request('Amount');
       $data['Note']=request('Note');
       $data['From_Safe']=request('From_Safe');
       $data['Branch']=request('Branch');
       $data['To_Safe']=request('To_Safe');
       $data['Coin']=request('Coin');
       $data['Status']=0;
       $data['File']=$zFile;
       $data['Edit']=0;
       $data['OldAmount']=request('Amount');
       $data['Cost_Center']=request('Cost_Center');
       $data['User']=$admin->id;

       SafeTransfers::create($data);

       $Code=SafeTransfers::latest('id')->first()->Code;

       $notii['Date']=date('Y-m-d');
       $notii['Status']=0;
       $notii['Noti_Ar_Name']='تحويل خزائن يحتاج للتأكيد';
       $notii['Noti_En_Name']='Safe Transfer Need Confirmation';
       $notii['Type']='تحويلات خزائن';
       $notii['TypeEn']='Safe Transfers';
       $notii['Type_Code']=$Code;
       $notii['Emp']=request('Delegate');
       $notii['Client']=null;
       $notii['Product']=null;
       $notii['Store']=null;
       $notii['Safe']=request('To_Safe');
       Notifications::create($notii);

       notify()->warning(trans('admin.Safe_Transfer_Need_Confirmation'));


       $dataUser=[
           'id'=>$admin->id,
           'screen_ar'=>'تحويلات خزائن',
           'screen_en'=>'Safes Transfer',
           'explain_ar'=>$Code,
           'explain_en'=>$Code,
       ];

       $this->UserCreateMoves($dataUser);

       DB::commit();


       return $this->returnSuccessMessage(trans('admin.Added_Successfully'));

   } catch (\Exception $ex) {

       DB::rollback();
       return $this->returnError($ex->getMessage().' '.$ex->getLine());

   }catch (\Error $ex) {
       DB::rollback();
       return $this->returnError($ex->getMessage().' '.$ex->getLine());
   }



    }

    public function SureSafeTransfersApi(Request $request){

        try {

            DB::beginTransaction();

            $header = $request->header('Authorization', '');
            if (Str::startsWith($header, 'Bearer ')) {
                $x = Str::substr($header, 7);
            }
            $admin = Admin::where('token', $x)->first();
            $id = request('transfer_id');
            $Code = SafeTransfers::findOrFail($id)->Code;

            $rules = [
                'Date'=>'required',
                'Draw'=>'required',
                'Amount'=>'required',
                'From_Safe'=>'required',
                'To_Safe'=>'required',
                'Coin'=>'required',
            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $code = $this->returnCodeAccordingToInput($validator);
                return $this->returnValidationError($code, $validator);
            }



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


            $data['Delegate'] = $admin->emp;
            $data['Time'] = date("h:i:s a", time());
            $data['Date'] = request('Date');
            $data['Draw'] = request('Draw');
            $data['Amount'] = request('Amount');
            $data['Note'] = request('Note');
            $data['From_Safe'] = request('From_Safe');
            $data['Branch'] = request('Branch');
            $data['To_Safe'] = request('To_Safe');
            $data['Coin'] = request('Coin');
            $data['Status'] = 1;
            $data['File'] = $zFile;
            $data['Edit'] = 0;
            $data['OldAmount'] = request('Amount');
            $data['Cost_Center'] = request('Cost_Center');
            $data['User'] = $admin->id;

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


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

                array(

                    'Code' => $Code,
                    'Type' => 'تحويلات الخزائن',
                    'TypeEn' => 'Safes Transfer',
                    'Code_Type' => request('Code'),
                    'Date' => request('Date'),
                    'Draw' => request('Draw'),
                    'Coin' => request('Coin'),
                    'Cost_Center' => request('Cost_Center'),
                    'Total_Debaitor' => request('Amount'),
                    'Total_Creditor' => request('Amount'),
                    'Note' => request('Note'),

                )
            );

            $PRODUCTSS['Joun_ID'] = $JunID;
            $PRODUCTSS['Debitor'] = request('Amount');
            $PRODUCTSS['Creditor'] = 0;
            $PRODUCTSS['Account'] = request('To_Safe');
            $PRODUCTSS['Statement'] = null;


            JournalizingDetails::create($PRODUCTSS);

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

            $Gen['Code'] = $Codee;
            $Gen['Code_Type'] = $Code;
            $Gen['Date'] = request('Date');
            $Gen['Type'] = 'تحويلات الخزائن';
            $Gen['TypeEn'] = 'Safes Transfer';
            $Gen['Debitor'] = request('Amount');
            $Gen['Creditor'] = 0;
            $Gen['Statement'] = null;
            $Gen['Draw'] = request('Draw');
            $Gen['Debitor_Coin'] = request('Draw') * request('Amount');
            $Gen['Creditor_Coin'] = request('Draw') * 0;
            $Gen['Account'] = request('To_Safe');
            $Gen['Coin'] = request('Coin');
            $Gen['Cost_Center'] = request('Cost_Center');
            $Gen['userr'] = $admin->id;

            GeneralDaily::create($Gen);


            $PRODUCTSS['Joun_ID'] = $JunID;
            $PRODUCTSS['Debitor'] = 0;
            $PRODUCTSS['Creditor'] = request('Amount');
            $PRODUCTSS['Account'] = request('From_Safe');
            $PRODUCTSS['Statement'] = null;


            JournalizingDetails::create($PRODUCTSS);

            $Gen['Code'] = $Codee;
            $Gen['Code_Type'] = $Code;
            $Gen['Date'] = request('Date');
            $Gen['Type'] = 'تحويلات الخزائن';
            $Gen['TypeEn'] = 'Safes Transfer';
            $Gen['Debitor'] = 0;
            $Gen['Creditor'] = request('Amount');
            $Gen['Statement'] = null;
            $Gen['Draw'] = request('Draw');
            $Gen['Debitor_Coin'] = request('Draw') * 0;
            $Gen['Creditor_Coin'] = request('Draw') * request('Amount');
            $Gen['Account'] = request('From_Safe');
            $Gen['Coin'] = request('Coin');
            $Gen['Cost_Center'] = request('Cost_Center');
            $Gen['userr'] = $admin->id;

            GeneralDaily::create($Gen);


            $notii['Date']=date('Y-m-d');
            $notii['Status']=0;
            $notii['Noti_Ar_Name']='تأكيد تحويل خزينة';
            $notii['Noti_En_Name']='Confirm Safe Transfer';
            $notii['Type']='تحويلات خزائن';
            $notii['TypeEn']='Safe Transfers';
            $notii['Type_Code']=$Code;
            $notii['Emp']=request('Delegate');
            $notii['Client']=null;
            $notii['Product']=null;
            $notii['Store']=null;
            $notii['Safe']=request('To_Safe');
            Notifications::create($notii);

            notify()->warning(trans('admin.Safe_Transfer_Need_Confirmation'));


            $dataUser = [
                'id' => $admin->id,
                'screen_ar' => 'تحويلات خزائن',
                'screen_en' => 'Safes Transfer',
                'type_ar' => 'تأكيد',
                'type_en' => 'Sure',
                'explain_ar' => $Code,
                'explain_en' => $Code,
            ];
            $this->UserCustomMoves($dataUser);

            DB::commit();
            return $this->returnSuccessMessage(trans('admin.Transferd'));

        } catch (\Exception $ex) {

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch (\Error $ex) {
            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());
        }


    }

    public function SafeTransfersSechduleApi(Request $request){


        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }
        $admin=Admin::where('token',$x)->first();

        $items=SafeTransfers::where('Status',0)->where('To_Safe',$admin->safe)->get();
        $data=SafeTransfersResources::collection($items);
        return $this->returnData('data', $data);

    }

    public function SafeTransfersDetails(Request $request){

        $item=SafeTransfers::findOrFail(request('transfer_id'));
        $data=SafeTransfersResources::make($item);
        return $this->returnData('data', $data);

    }

    public function EditSafeTransfers(Request $request){

        try {

            DB::beginTransaction();

            $header = $request->header('Authorization', '');
            if (Str::startsWith($header, 'Bearer ')) {
                $x = Str::substr($header, 7);
            }
            $admin = Admin::where('token', $x)->first();
            $id = request('transfer_id');
            $Code = SafeTransfers::findOrFail($id)->Code;

            $rules = [
                'Date'=>'required',
                'Draw'=>'required',
                'Amount'=>'required',
                'From_Safe'=>'required',
                'To_Safe'=>'required',
                'Coin'=>'required',
            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $code = $this->returnCodeAccordingToInput($validator);
                return $this->returnValidationError($code, $validator);
            }



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


            $data['Delegate'] = $admin->emp;
            $data['Time'] = date("h:i:s a", time());
            $data['Date'] = request('Date');
            $data['Draw'] = request('Draw');
            $data['Amount'] = request('Amount');
            $data['Note'] = request('Note');
            $data['From_Safe'] = request('From_Safe');
            $data['Branch'] = request('Branch');
            $data['To_Safe'] = request('To_Safe');
            $data['Coin'] = request('Coin');
            $data['Status'] = 0;
            $data['File'] = $zFile;
            $data['Edit'] = 0;
            $data['OldAmount'] = request('Amount');
            $data['Cost_Center'] = request('Cost_Center');
            $data['User'] = $admin->id;

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


            DB::commit();
            return $this->returnSuccessMessage(trans('admin.Updated'));

        } catch (\Exception $ex) {

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch (\Error $ex) {
            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());
        }


    }

    public function RefuseSafeTransfers(Request $request){


        try {

            DB::beginTransaction();

            $header = $request->header('Authorization', '');
            if (Str::startsWith($header, 'Bearer ')) {
                $x = Str::substr($header, 7);
            }
            $admin = Admin::where('token', $x)->first();
            $id = request('transfer_id');
            SafeTransfers::where('id',$id)->update(['Status'=>2]);


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

            $notii['Date']=date('Y-m-d');
            $notii['Status']=0;
            $notii['Noti_Ar_Name']='رفض تحويل خزينة';
            $notii['Noti_En_Name']='Refuse Safe Transfer';
            $notii['Type']='تحويلات خزائن';
            $notii['TypeEn']='Safe Transfers';
            $notii['Type_Code']=$del->Code;
            $notii['Emp']=$del->Delegate;
            $notii['Client']=null;
            $notii['Product']=null;
            $notii['Store']=null;
            $notii['Safe']=$del->To_Safe;
            Notifications::create($notii);

            notify()->error(trans('admin.RefuseSafeTransfer'));


            $dataUser=[
                'id'=>$admin->id,
                'screen_ar'=>'تحويلات خزائن',
                'screen_en'=>'Safes Transfer',
                'type_ar'=>'رفض تحويل خزينة',
                'type_en'=>'Refuse Safe Transfer',
                'explain_ar'=>$del->Code,
                'explain_en'=>$del->Code,
            ];

            $this->UserCustomMoves($dataUser);

            DB::commit();


            return $this->returnSuccessMessage(trans('admin.Refused'));



        } catch (\Exception $ex) {

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch (\Error $ex) {
            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());
        }




    }



    //Stores Transfer
    public function StoreTransfersCode(Request $request){

        $Code=$this->ReturnCode(StorsTransfers::class);
        return $this->returnData('data',$Code,trans('admin.Success'));

    }

    public function TarnsferStoresFilter(Request $request){


        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }
        $admin=Admin::where('token',$x)->first();


            $search = $request->get('search');
            $store = $request->get('store');
            $Brand = null;
            $Group = null;

            if(!empty($search)) {
                $Prods = $this->FilterSalesProductQty($search, $admin->store, $Group, $Brand);
            }else{
                $Prods=ProductsQty::where('Qty','!=',0)->where('Store',$admin->store)->paginate(20);
            }
        $data=TarnsferStoresFilterResources::collection($Prods);
        return $this->returnData('data', $data);

    }

    public function AddStoreTransfersApi(Request $request){

        try {

            DB::beginTransaction();

            $header = $request->header('Authorization', '');
            if (Str::startsWith($header, 'Bearer ')) {
                $x=Str::substr($header, 7);
            }
            $admin=Admin::where('token',$x)->first();


            $rules = [
                'From_Store'=>'required',
                'To_Store'=>'required',
                'Coin'=>'required',
            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $code = $this->returnCodeAccordingToInput($validator);
                return $this->returnValidationError($code, $validator);
            }



            $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' => $admin->store,
                    'To_Store' => request('To_Store'),
                    'Coin' => request('Coin'),
                    'Ship' => request('Ship'),
                    'CostShip' => request('CostShip'),
                    'Delegate' => $admin->emp,
                    'Branch' => request('Branch'),
                    'TypeTransfer' => null,
                    'Cost_Store' => request('Cost_Store'),
                    'Time' => date("h:i:s a", time()),
                    'Status' => 0,
                    'Edit' => 0,
                    'RecivedShip' => 0,
                    'Cost_Center' => null,
                    'File' => $zFile,
                    'User' => $admin->id,

                )
            );


$Code=StorsTransfers::findOrFail($ID)->Code;


            $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']=$Code;
            $notii['Emp']=$admin->emp;
            $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=[
                'id'=>$admin->id,
                'screen_ar'=>'تحويلات المخازن',
                'screen_en'=>'Stores Transfers',
                'explain_ar'=>$Code,
                'explain_en'=>$Code,
            ];
            $this->UserCreateMoves($dataUser);


            DB::commit();


            return $this->returnSuccessMessage(trans('admin.Added_Successfully'));

        } catch (\Exception $ex) {

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch (\Error $ex) {
            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());
        }



    }

    public function StoreTransfersSechduleApi(Request $request){

        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }
        $admin=Admin::where('token',$x)->first();
        $items=StorsTransfers::latest('id')->where('To_Store',$admin->store)->where('Status',0)->get();
        $data=StorsTransfersResources::collection($items);
        return $this->returnData('data', $data);

    }

    public function StoreTransfersDetails(Request $request){

        $id=request('transfer_id');
        $item=StorsTransfers::findOrFail($id);
        $data=StorsTransfersResources::make($item);
        return $this->returnData('data', $data);

    }

    public function RefusedStoreTransfer(Request $request){


        try {

            DB::beginTransaction();


            $id = request('transfer_id');
            StorsTransfers::where('id',$id)->update(['Status'=>2]);

            DB::commit();

            return $this->returnSuccessMessage(trans('admin.Refused'));


        } catch (\Exception $ex) {

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch (\Error $ex) {
            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());
        }




    }

    public function SureStoreTransfersApi(Request $request){

        try {

            DB::beginTransaction();

            $header = $request->header('Authorization', '');
            if (Str::startsWith($header, 'Bearer ')) {
                $x=Str::substr($header, 7);
            }
            $admin=Admin::where('token',$x)->first();


            $rules = [
                'From_Store'=>'required',
                'To_Store'=>'required',
                'Coin'=>'required',
            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $code = $this->returnCodeAccordingToInput($validator);
                return $this->returnValidationError($code, $validator);
            }

            $id=request('transfer_id');
            $item=StorsTransfers::find($id);
            Notifications::where('Type_Code',$item->Code)->where('Type','تحويلات المخازن')->delete();
            if($item->Status != 0){
                DB::rollBack();
                return $this->returnError(trans('admin.Already_Done'));

            }

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

            //Create Event
            $result=StoresTransferApiEvent::dispatch($request->all(),$id,1,$admin->id);


            if($result[0] == 5){
                DB::rollBack();
                return $this->returnError(trans('admin.Not_Enough_Qty'));
            }

            $dataUser=[
                'id'=>$admin->id,
                'screen_ar'=>'تحويلات المخازن',
                'screen_en'=>'Stores Transfers',
                'type_ar'=>'تأكيد',
                'type_en'=>'Sure',
                'explain_ar'=>request('Code'),
                'explain_en'=>request('Code'),
            ];
            $this->UserCustomMoves($dataUser);
            DB::commit();

            return $this->returnSuccessMessage(trans('admin.Added_Successfully'));

        } catch (\Exception $ex) {

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch (\Error $ex) {
            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());
        }



    }


    //=================== Shifts ================================

    //CheckShift
    public function CheckShift(Request $request){

        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }
        $admin=Admin::where('token',$x)->first();

            $shift=Shifts::latest('id')->where('Emp',$admin->emp)->first();

            if(empty($shift)){
                return response()->json([
                    'status'=>200,
                    'msg'=>'No Shift Found',
                    'data'=>0,
                ]);
            }elseif($shift->Close == 1){
                return response()->json([
                    'status'=>200,
                    'msg'=>'Shift Closed',
                    'data'=>0,
                ]);
            }else{
                return response()->json([
                    'status'=>200,
                    'msg'=>'Shift Found',
                    'data'=>1,
                ]);
            }


    }

    //OpenShift
    public function OpenShift(Request $request){
           $Code=$this->ReturnCode(Shifts::class);
        return $this->returnData('shift_code', $Code);
    }

    //PostOpenShift
    public function PostOpenShift(Request $request){


        try {

            DB::beginTransaction();

            $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }

        $admin=Admin::where('token',$x)->first();

            $Def=SalesDefaultData::orderBy('id','desc')->first();


            $data['Code']=request('Code');
            $data['Date']=date('Y-m-d');
            $data['Pass']=$Def->Shift_Pass;
            $data['Emp']=$admin->emp;
            $data['User']=$admin->id;
            $data['Close']=0;
            $data['Total_Cash']=0;
            $data['Total_Later']=0;
            $data['Total_Visa']=0;
            $data['Total']=0;
            $data['Total_Recipt']=0;
            $data['Total_Payment']=0;
            $data['Total_Later_Not_Paid']=0;
            $data['Total_Later_Paid']=0;
            $data['Store']=$admin->store;
            $data['Safe']=$admin->safe;
            $data['Open_Amount']=request('Open_Amount');
            $data['Open_Note']=request('Open_Note');
            Shifts::create($data);

            $item=Shifts::latest('id')->first();

            DB::commit();
        return $this->returnData('shift_id', $item->id);

        } catch (\Exception $ex) {

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch (\Error $ex) {
            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());
        }


    }

    //DetailsShiftPass
    public function DetailsShiftPass(Request $request){

        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }
        $admin=Admin::where('token',$x)->first();


            $def=SalesDefaultData::orderBy('id','desc')->first();


            if($def->Shift_Pass == request('shift_pass')){

                return $this->returnSuccessMessage(trans('admin.SuccessPass'));

            }else{


                return $this->returnError(trans('admin.WrongPass'));

            }



    }

    //DetailsShift
    public function DetailsShift(Request $request){

        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }

        $admin=Admin::where('token',$x)->first();
            $shift=Shifts::latest('id')->where('Emp',$admin->emp)->where('Close',0)->first();
            $Array=array();
            array_push($Array,[
                'total_cash'=>$shift->Total_Cash,
                'total_later'=>$shift->Total_Later,
                'total_later_not_paid'=>$shift->Total_Later_Not_Paid,
                'total_later_paid'=>$shift->Total_Later_Paid,
                'total_visa'=>$shift->Total_Visa,
                'total_recipt'=>$shift->Total_Recipt,
                'total_payment'=>$shift->Total_Payment,
                'total'=>$shift->Total,

            ]);


            return response()->json([
                'status'=>200,
                'msg'=>trans('admin.Success'),
                'data'=>$Array,

            ]);
    }

    //PostCloseShift
    public function PostCloseShift(Request $request){

        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }

        $admin=Admin::where('token',$x)->first();


            Shifts::where('id',request('shift_id'))->update(['Amount'=>request('amount'),'Note'=>request('note'),'Close'=>1]);

            return response()->json([
                'status'=>200,
                'msg'=>trans('admin.Close_Shift_Successfully'),


            ]);



    }

    //GetShiftCode
    public function GetShiftCode(Request $request){

        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }

        $admin=Admin::where('token',$x)->first();

            $shift=Shifts::orderBy('id','desc')->where('Emp',$admin->emp)->where('Close',0)->first();


            if(!empty($shift)){
                $Array=array();
                array_push($Array,[
                    'shift_code'=>$shift->Code,
                    'shift_id'=>$shift->id,

                ]);

                return $this->returnData('data',$Array);
            }else{


                return $this->returnError(trans('admin.NoShiftOpen'));

            }

    }

    public function GetNextShiftCode(Request $request){

        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }

        $admin=Admin::where('token',$x)->first();

            $shift=Shifts::latest('id')->first();

            if(!empty($shift)){
                $code=$shift->Code + 1 ;
            }else{
                $code= 1 ;
            }


            if(!empty($shift)){
                $Array=array();
                array_push($Array,[
                    'shift_code'=>$code,
                ]);

                return $this->returnData('data',$Array);
            }else{


                return $this->returnError(trans('admin.NoShiftOpen'));

            }

    }


    //=====  Sales  =============================================


    //=====  Sales Order (Quote)  =====================
    public function SalesOrderNewCode(Request $request){

        $Code=$this->ReturnCode(SalesOrder::class);
        return $this->returnData('data',$Code,trans('admin.Success'));

    }

    public function SalesOrderSechdule(Request $request){

        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }

        $admin=Admin::where('token',$x)->first();

        $items=SalesOrder::latest('id')->where('Delete',0)->where('Edit',0)
            ->where('ToSales','!=',1)->where('Delegate',$admin->emp)->where('KitchenEnd',1)->where('RecivedOrder',1)->where('Payment_Method','!=','Delivery')->where('Hold',0)->paginate(10);
        $data=SalesOrderResources::collection($items);
            $x=['status'=>200,'msg'=>trans('admin.Success')];
             return $data->additional($x) ;
    }
    public function SalesOrderDetails(Request $request){
        $id=request('bill_id');
        $item=SalesOrder::findOrFail($id);
        $data=SalesOrderResources::make($item);
        return $this->returnData('data',$data);

    }

    public function AddSalesOrder(Request $request,SalesService $service){

        try {
            DB::beginTransaction();

            $rules = [
                'Date'=>'required',
                'Store'=>'required',
                'Safe'=>'required',
                'Coin'=>'required',
                'Draw'=>'required',
                'Payment_Method'=>'required',
                'Status'=>'required',
                'Client'=>'required',
            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $code = $this->returnCodeAccordingToInput($validator);
                return $this->returnValidationError($code, $validator);
            }

            $header = $request->header('Authorization', '');
            if (Str::startsWith($header, 'Bearer ')) {
                $x=Str::substr($header, 7);
            }
            $admin=Admin::where('token',$x)->first();


            $Sale_Type='Sales_Order';

            $ID=$service->CreateNewSalesOrderApi($request->all(),$Sale_Type,$admin->id);

            //Event New Bill
            $result=SalesOrderEvent::dispatch($request->all(),$ID,$Sale_Type);


            if($result[0] == 5){
                DB::rollBack();
                return  $this->returnSuccessMessage(trans('admin.Not_Enough_Qty'));
            }


            $dataUser=[
                'id'=>$admin->id,
                'screen_ar'=>'امر بيع',
                'screen_en'=>'Sales Order',
                'explain_ar'=>request('Code'),
                'explain_en'=>request('Code'),
            ];
            $this->UserCreateMoves($dataUser);


            DB::commit();

            return $this->returnSuccessMessage(trans('admin.Added_Successfully'));

        }catch(\Exception $ex){

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch(\Error $ex){

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }




    }

    public function EditSalesOrder(Request $request,SalesService $service){

        try {
            DB::beginTransaction();

            $rules = [
                'Date'=>'required',
                'Store'=>'required',
                'Safe'=>'required',
                'Coin'=>'required',
                'Draw'=>'required',
                'Payment_Method'=>'required',
                'Status'=>'required',
                'Client'=>'required',
            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $code = $this->returnCodeAccordingToInput($validator);
                return $this->returnValidationError($code, $validator);
            }

            $header = $request->header('Authorization', '');
            if (Str::startsWith($header, 'Bearer ')) {
                $x=Str::substr($header, 7);
            }
            $admin=Admin::where('token',$x)->first();

            $id=request('bill_id');
            $del=SalesOrder::find($id);

            SalesOrder::where('id',$id)->update(['Edit'=>1,'Edit_New_Code'=>request('Code')]);
            Event::where('Type_Code',$del->Code)->where('Type','امر البيع')->delete();
            Notifications::where('Type_Code',$del->Code)->where('Type','امر بيع')->delete();

            if($del->Hold_Qty == 1){


                $service->RemoveHoldQties($id);


            }



            $Sale_Type='Sales_Order';

            $ID=$service->CreateNewSalesOrderApi($request->all(),$Sale_Type,$admin->id);

            //Event New Bill
            $result=SalesOrderEvent::dispatch($request->all(),$ID,$Sale_Type);


            if($result[0] == 5){
                DB::rollBack();
                return  $this->returnSuccessMessage(trans('admin.Not_Enough_Qty'));
            }



            $dataUser=[
                'id'=> $admin->id,
                'screen_ar'=>'امر بيع',
                'screen_en'=>'Sales Order',
                'explain_ar'=>request('Old_Code'),
                'explain_en'=>request('Old_Code'),
            ];
            $this->UserUpdateMoves($dataUser);



            DB::commit();

            return $this->returnSuccessMessage(trans('admin.Added_Successfully'));

        }catch(\Exception $ex){

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch(\Error $ex){

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }




    }

    public function DeleteSalesOrder(Request $request,SalesService $service){

        try {
            DB::beginTransaction();

            $header = $request->header('Authorization', '');
            if (Str::startsWith($header, 'Bearer ')) {
                $x=Str::substr($header, 7);
            }
            $admin=Admin::where('token',$x)->first();



            $id=request('bill_id');
            $del=SalesOrder::find($id);

            SalesOrder::where('id',$id)->update(['Delete'=>1]);
            Event::where('Type_Code',$del->Code)->where('Type','امر البيع')->delete();
            Notifications::where('Type_Code',$del->Code)->where('Type','امر بيع')->delete();

            if($del->Hold_Qty == 1){


                $service->RemoveHoldQties($id);


            }


            $dataUser=[
                'id'=>$admin->id,
                'screen_ar'=>'امر بيع',
                'screen_en'=>'Sales Order',
                'explain_ar'=>$del->Code,
                'explain_en'=>$del->Code,
            ];
            $this->UserDeleteMoves($dataUser);

            DB::commit();


            return $this->returnSuccessMessage(trans('admin.Deleted'));

        }catch(\Exception $ex){

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch(\Error $ex){

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }




    }

    //TransferToSales
    public function TransferToSales(Request $request,SalesService $service){

        try {
            DB::beginTransaction();

            $rules = [
                'Date'=>'required',
                'Store'=>'required',
                'Safe'=>'required',
                'Coin'=>'required',
                'Draw'=>'required',
                'Payment_Method'=>'required',
                'Status'=>'required',
                'Client'=>'required',
            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $code = $this->returnCodeAccordingToInput($validator);
                return $this->returnValidationError($code, $validator);
            }

            $header = $request->header('Authorization', '');
            if (Str::startsWith($header, 'Bearer ')) {
                $x=Str::substr($header, 7);
            }
            $admin=Admin::where('token',$x)->first();
            $id=request('bill_id');
            $del=SalesOrder::find($id);

            SalesOrder::where('id',$id)->update(['ToSales'=>1]);
            Event::where('Type_Code',$del->Code)->where('Type','امر البيع')->delete();
            Notifications::where('Type_Code',$del->Code)->where('Type','امر بيع')->delete();

            if($del->Hold_Qty == 1){
                $result=$service->RemoveHoldQties($id);

                if ($result == 5){
                    DB::rollBack();
                    return  $this->returnSuccessMessage(trans('admin.Not_Enough_Qty'));

                }
            }

            $Sale_Type='Sales';

            //Service Create New Bill
            $ID=$service->CreateNewSalesBillApi($request->all(),$Sale_Type,$admin->id);



            //Event New Bill

            $result=SalesEventApi::dispatch($request->all(),$ID,$Sale_Type,$admin->id);


            if($result[0] == 5){
                DB::rollBack();
                return  $this->returnSuccessMessage(trans('admin.Not_Enough_Qty'));
            }




            $dataUser=[
                'id'=>$admin->id,
                'screen_ar'=>'المبيعات',
                'screen_en'=>'Sales',
                'explain_ar'=>request('Code'),
                'explain_en'=>request('Code'),
            ];
            $this->UserCreateMoves($dataUser);

            DB::commit();

            return $this->returnSuccessMessage(trans('admin.Transfered'));

        }catch(\Exception $ex){

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch(\Error $ex){

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }




    }

    //=====  Sales =====================

//SalesSechdule
    public function SalesSechdule(Request $request){

        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }

        $admin=Admin::where('token',$x)->first();

        $items=Sales::latest('id')->where('Delete',0)->where('Edit',0)
            ->where('Status',1)->where('Delegate',$admin->emp)->where('Payment_Method','!=','Delivery')->paginate(10);


        $total_cash=Sales::where('Payment_Method','Cash')->where('Delete',0)->where('Edit',0)
            ->where('Status',1)->where('Delegate',$admin->emp)->where('Payment_Method','!=','Delivery')->get()->sum('Total_Net');



        $total_later=Sales::where('Payment_Method','Later')->where('Delete',0)->where('Edit',0)
            ->where('Status',1)->where('Delegate',$admin->emp)->where('Payment_Method','!=','Delivery')->get()->sum('Total_Net');



        $total_check=Sales::where('Payment_Method','Check')->where('Delete',0)->where('Edit',0)
            ->where('Status',1)->where('Delegate',$admin->emp)->where('Payment_Method','!=','Delivery')->get()->sum('Total_Net');



        $total_install=Sales::where('Payment_Method','Installment')->where('Delete',0)->where('Edit',0)
            ->where('Status',1)->where('Delegate',$admin->emp)->where('Payment_Method','!=','Delivery')->get()->sum('Total_Net');



        $total_cash_visa=Sales::where('Payment_Method','Cash_Visa')->where('Delete',0)->where('Edit',0)
            ->where('Status',1)->where('Delegate',$admin->emp)->where('Payment_Method','!=','Delivery')->get()->sum('Total_Net');



        $total_cash_collectionr=Sales::where('Payment_Method','Cash_Collection')->where('Delete',0)->where('Edit',0)
            ->where('Status',1)->where('Delegate',$admin->emp)->where('Payment_Method','!=','Delivery')->get()->sum('Total_Net');



        $total_delivery=Sales::where('Payment_Method','Delivery')->where('Delete',0)->where('Edit',0)
            ->where('Status',1)->where('Delegate',$admin->emp)->where('Payment_Method','!=','Delivery')->get()->sum('Total_Net');



        $total_install_companies=Sales::where('Payment_Method','InstallmentCompanies')->where('Delete',0)->where('Edit',0)
            ->where('Status',1)->where('Delegate',$admin->emp)->where('Payment_Method','!=','Delivery')->get()->sum('Total_Net');



        $total_visa=Sales::where('Payment_Method','Visa_Network')->where('Delete',0)->where('Edit',0)
            ->where('Status',1)->where('Delegate',$admin->emp)->where('Payment_Method','!=','Delivery')->get()->sum('Total_Net');


        $total_discount=Sales::where('Delete',0)->where('Edit',0)
            ->where('Status',1)->where('Delegate',$admin->emp)->where('Payment_Method','!=','Delivery')->get()->sum('Total_Discount');

        $total_return=ReturnSales::where('Delegate',$admin->emp)->get()->sum('Total_Return_Value');




        $data=SalesResources::collection($items);
        $x=[
            'status'=>200,
            'msg'=>trans('admin.Success'),
            'total_cash'=>$total_cash,
            'total_later'=>$total_later,
            'total_check'=>$total_check,
            'total_install'=>$total_install,
            'total_cash_visa'=>$total_cash_visa,
            'total_cash_collectionr'=>$total_cash_collectionr,
            'total_delivery'=>$total_delivery,
            'total_install_companies'=>$total_install_companies,
            'total_visa'=>$total_visa,
            'total_discount'=>$total_discount,
            'total_return'=>$total_return,

        ];
        return $data->additional($x) ;
    }

   public function FilterSalesSechdule(Request $request){

        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }

        $admin=Admin::where('token',$x)->first();


       $Code=request('Code');
       $User=request('User');
       $Store=request('Store');
       $Client=request('Client');
       $Coin=request('Coin');
       $Safe=request('Safe');
       $Payment_Method=request('Payment_Method');
       $Cost_Center=request('Cost_Center');
       $Delegate=request('Delegate');
       $Executor=request('Executor');
       $From=request('From');
       $To=request('To');


       $items=Sales::latest('id')->where('Status',1)->where('Payment_Method','!=','Delivery')->where('Delegate',$admin->emp)->where('Delete',0)->where('Edit',0)


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


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


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




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


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




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


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




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


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




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


           ->whereBetween('Date', [request('From'), request('To')])
           ->paginate(10);



       $total_cash=Sales::where('Payment_Method','Cash')->where('Delete',0)->where('Edit',0)
           ->when(!empty($Code), function ($query) use ($Code) {
               $query->where('Code', $Code);
           })


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


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




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


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




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


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




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


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




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


           ->whereBetween('Date', [request('From'), request('To')])
           ->where('Status',1)->where('Delegate',$admin->emp)->where('Payment_Method','!=','Delivery')->get()->sum('Total_Net');



       $total_later=Sales::where('Payment_Method','Later')->where('Delete',0)->where('Edit',0)
           ->when(!empty($Code), function ($query) use ($Code) {
               $query->where('Code', $Code);
           })


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


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




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


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




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


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




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


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




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


           ->whereBetween('Date', [request('From'), request('To')])
           ->where('Status',1)->where('Delegate',$admin->emp)->where('Payment_Method','!=','Delivery')->get()->sum('Total_Net');



       $total_check=Sales::where('Payment_Method','Check')->where('Delete',0)->where('Edit',0)
       ->when(!empty($Code), function ($query) use ($Code) {
               $query->where('Code', $Code);
           })


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


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




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


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




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


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




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


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




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


           ->whereBetween('Date', [request('From'), request('To')])
           ->where('Status',1)->where('Delegate',$admin->emp)->where('Payment_Method','!=','Delivery')->get()->sum('Total_Net');



       $total_install=Sales::where('Payment_Method','Installment')->where('Delete',0)->where('Edit',0)
->when(!empty($Code), function ($query) use ($Code) {
               $query->where('Code', $Code);
           })


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


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




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


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




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


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




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


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




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


           ->whereBetween('Date', [request('From'), request('To')])
           ->where('Status',1)->where('Delegate',$admin->emp)->where('Payment_Method','!=','Delivery')->get()->sum('Total_Net');



       $total_cash_visa=Sales::where('Payment_Method','Cash_Visa')->where('Delete',0)->where('Edit',0)
       ->when(!empty($Code), function ($query) use ($Code) {
               $query->where('Code', $Code);
           })


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


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




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


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




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


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




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


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




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


           ->whereBetween('Date', [request('From'), request('To')])
           ->where('Status',1)->where('Delegate',$admin->emp)->where('Payment_Method','!=','Delivery')->get()->sum('Total_Net');



       $total_cash_collectionr=Sales::where('Payment_Method','Cash_Collection')->where('Delete',0)->where('Edit',0)
       ->when(!empty($Code), function ($query) use ($Code) {
               $query->where('Code', $Code);
           })


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


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




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


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




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


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




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


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




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


           ->whereBetween('Date', [request('From'), request('To')])
           ->where('Status',1)->where('Delegate',$admin->emp)->where('Payment_Method','!=','Delivery')->get()->sum('Total_Net');



       $total_delivery=Sales::where('Payment_Method','Delivery')->where('Delete',0)->where('Edit',0)
           ->when(!empty($Code), function ($query) use ($Code) {
               $query->where('Code', $Code);
           })


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


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




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


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




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


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




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


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




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


           ->whereBetween('Date', [request('From'), request('To')])
           ->where('Status',1)->where('Delegate',$admin->emp)->where('Payment_Method','!=','Delivery')->get()->sum('Total_Net');



       $total_install_companies=Sales::where('Payment_Method','InstallmentCompanies')->where('Delete',0)->where('Edit',0)
       ->when(!empty($Code), function ($query) use ($Code) {
               $query->where('Code', $Code);
           })


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


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




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


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




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


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




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


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




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


           ->whereBetween('Date', [request('From'), request('To')])
           ->where('Status',1)->where('Delegate',$admin->emp)->where('Payment_Method','!=','Delivery')->get()->sum('Total_Net');



       $total_visa=Sales::where('Payment_Method','Visa_Network')->where('Delete',0)->where('Edit',0)
 ->when(!empty($Code), function ($query) use ($Code) {
               $query->where('Code', $Code);
           })


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


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




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


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




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


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




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


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




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


           ->whereBetween('Date', [request('From'), request('To')])
           ->where('Status',1)->where('Delegate',$admin->emp)->where('Payment_Method','!=','Delivery')->get()->sum('Total_Net');


       $total_discount=Sales::where('Delete',0)->where('Edit',0)
           ->when(!empty($Code), function ($query) use ($Code) {
               $query->where('Code', $Code);
           })


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


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




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


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




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


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




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


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




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


           ->whereBetween('Date', [request('From'), request('To')])
           ->where('Status',1)->where('Delegate',$admin->emp)->where('Payment_Method','!=','Delivery')->get()->sum('Total_Discount');

       $total_return=ReturnSales::where('Delegate',$admin->emp)->get()->sum('Total_Return_Value');




       $data=SalesResources::collection($items);
        $x=['status'=>200,'msg'=>trans('admin.Success'),
            'total_cash'=>$total_cash,
            'total_later'=>$total_later,
            'total_check'=>$total_check,
            'total_install'=>$total_install,
            'total_cash_visa'=>$total_cash_visa,
            'total_cash_collectionr'=>$total_cash_collectionr,
            'total_delivery'=>$total_delivery,
            'total_install_companies'=>$total_install_companies,
            'total_visa'=>$total_visa,
            'total_discount'=>$total_discount,
            'total_return'=>$total_return,

            ];
        return $data->additional($x) ;
    }

    public function SalesBillDetailsApi(Request $request){

        $id=request('bill_id');
        $item=Sales::findOrFail($id);
        $data=SalesResources::make($item);
        return $this->returnData('data',$data);

    }

    public function AddSalesBill(Request $request,SalesService $service){

        try {
            DB::beginTransaction();

            $rules = [
                'Date'=>'required',
                'Store'=>'required',
                'Safe'=>'required',
                'Coin'=>'required',
                'Draw'=>'required',
                'Payment_Method'=>'required',
                'Status'=>'required',
                'Client'=>'required',
            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $code = $this->returnCodeAccordingToInput($validator);
                return $this->returnValidationError($code, $validator);
            }

            $header = $request->header('Authorization', '');
            if (Str::startsWith($header, 'Bearer ')) {
                $x=Str::substr($header, 7);
            }
            $admin=Admin::where('token',$x)->first();

            $Sale_Type='POS';

            //Service Create New Bill
            $ID=$service->CreateNewSalesBillApi($request->all(),$Sale_Type,$admin->id);



            //Event New Bill

            $result=SalesEventApi::dispatch($request->all(),$ID,$Sale_Type,$admin->id);


            if($result[0] == 5){
                DB::rollBack();
                return  $this->returnSuccessMessage(trans('admin.Not_Enough_Qty'));
            }




            $dataUser=[
                'id'=>$admin->id,
                'screen_ar'=>'المبيعات',
                'screen_en'=>'Sales',
                'explain_ar'=>request('Code'),
                'explain_en'=>request('Code'),
            ];
            $this->UserCreateMoves($dataUser);

            DB::commit();

            return $this->returnSuccessMessage(trans('admin.Added_Successfully'));

        }catch(\Exception $ex){

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch(\Error $ex){

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }




    }

    public function EditSalesApi(Request $request,SalesService $service){

        try {
            DB::beginTransaction();

            $rules = [
                'Date'=>'required',
                'Store'=>'required',
                'Safe'=>'required',
                'Coin'=>'required',
                'Draw'=>'required',
                'Payment_Method'=>'required',
                'Status'=>'required',
                'Client'=>'required',
            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $code = $this->returnCodeAccordingToInput($validator);
                return $this->returnValidationError($code, $validator);
            }

            $header = $request->header('Authorization', '');
            if (Str::startsWith($header, 'Bearer ')) {
                $x=Str::substr($header, 7);
            }
            $admin=Admin::where('token',$x)->first();

            $id=request('bill_id');

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

            $Returns=ReturnSales::where('Sales',$del->id)->get();
            if(!empty($Returns)){

                foreach($Returns as $return){
                    GeneralDaily::where('Code_Type',$return->Code)->where('Type','مرتجع مبيعات')->delete();
                    Journalizing::where('Code_Type',$return->Code)->where('Type','مرتجع مبيعات')->update(['Edit'=>1,'Edit_New_Code'=>request('Code')]);
                    StoresMoves::where('ID',$return->id)->where('Type','مرتجع مبيعات')->update(['Edit'=>1,'Edit_New_Code'=>request('Code')]);
                    ReturnPurch::where('id',$return->id)->update(['Edit'=>1,'Edit_New_Code'=>request('Code')]);
                }
            }

            Notifications::where('Type_Code',$del->Code)->where('Type','المبيعات')->delete();
            Event::where('Type_Code',$del->Code)->where('Type','المبيعات')->delete();
            GeneralDaily::where('Code_Type',$del->Code)->where('Type','المبيعات')->delete();
            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')]);
            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')]);
            Installment::where('Sales',$del->id)->delete();



            $Sale_Type='POS';

            //Service Create New Bill
            $ID=$service->CreateNewSalesBillApi($request->all(),$Sale_Type,$admin->id);



            //Event New Bill

            $result=SalesEventApi::dispatch($request->all(),$ID,$Sale_Type,$admin->id);


            if($result[0] == 5){
                DB::rollBack();
                return  $this->returnSuccessMessage(trans('admin.Not_Enough_Qty'));
            }




            $dataUser=[
                'id'=>$admin->id,
                'screen_ar'=>'المبيعات',
                'screen_en'=>'Sales',
                'explain_ar'=>request('Old_Code'),
                'explain_en'=>request('Old_Code'),
            ];
            $this->UserUpdateMoves($dataUser);

            DB::commit();

            return $this->returnSuccessMessage(trans('admin.Added_Successfully'));

        }catch(\Exception $ex){

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch(\Error $ex){

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }




    }

    public function DeleteSalesApi(Request $request,SalesService $service){


        try {
            DB::beginTransaction();

            $header = $request->header('Authorization', '');
            if (Str::startsWith($header, 'Bearer ')) {
                $x=Str::substr($header, 7);
            }
            $admin=Admin::where('token',$x)->first();



            $id=request('bill_id');
            $del=Sales::find($id);
            Sales::where('id',$id)->update(['Delete'=>1]);

            $Returns=ReturnSales::where('Sales',$del->id)->get();
            if(!empty($Returns)){

                foreach($Returns as $return){
                    GeneralDaily::where('Code_Type',$return->Code)->where('Type','مرتجع مبيعات')->delete();
                    Journalizing::where('Code_Type',$return->Code)->where('Type','مرتجع مبيعات')->update(['Delete'=>1]);
                    StoresMoves::where('ID',$return->id)->where('Type','مرتجع مبيعات')->update(['Delete'=>1]);
                    ReturnPurch::where('id',$return->id)->update(['Delete'=>1]);
                }
            }

            Notifications::where('Type_Code',$del->Code)->where('Type','المبيعات')->delete();
            Event::where('Type_Code',$del->Code)->where('Type','المبيعات')->delete();
            GeneralDaily::where('Code_Type',$del->Code)->where('Type','المبيعات')->delete();
            GeneralDaily::where('Code_Type',$del->Code)->where('Type','استحقاق عمولة')->delete();
            Journalizing::where('Code_Type',$del->Code)->where('Type','استحقاق عمولة')->update(['Delete'=>1]);
            Journalizing::where('Code_Type',$del->Code)->where('Type','المبيعات')->update(['Delete'=>1]);
            StoresMoves::where('ID',$del->id)->where('Type','مبيعات')->update(['Delete'=>1]);
            Installment::where('Sales',$del->id)->delete();


            //Service

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


            $dataUser=[
                'id'=>$admin->id,
                'screen_ar'=>'المبيعات',
                'screen_en'=>'Sales',
                'explain_ar'=>$del->Code,
                'explain_en'=>$del->Code,
            ];
            $this->UserDeleteMoves($dataUser);


            DB::commit();
            return $this->returnSuccessMessage(trans('admin.Deleted'));
        }catch(\Exception $ex){

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch(\Error $ex){

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }



    }

    //=====  MyRequestsDelivery =====================

    //MyRequestsDelivery
    public function MyRequestsDelivery(Request $request){

        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }

        $admin=Admin::where('token',$x)->first();

        $items=Sales::latest('id')->where('Delete',0)->where('Edit',0)
            ->where('Status',1)->where('Delivery',$admin->emp)->where('Payment_Method','Delivery')->paginate(10);
        $data=SalesResources::collection($items);
        $x=['status'=>200,'msg'=>trans('admin.Success')];
        return $data->additional($x) ;
    }

    public function RecivedDeliveryApi(Request $request){

        $id=request('sales_id');
        $del=Sales::where('id',$id)->update(['Delivery_Status'=>1]);
        return $this->returnSuccessMessage(trans('admin.Updated'));

    }


    //=====  Return Sales =====================

    public function ReturnSalesNewCodeApi(Request $request){

        $Code=$this->ReturnCode(ReturnSales::class);
        return $this->returnData('data',$Code,trans('admin.Success'));

    }

//ReturnSalesSechdule
    public function ReturnSalesSechdule(Request $request){

        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }

        $admin=Admin::where('token',$x)->first();

        $items=ReturnSales::orderBy('id','desc')->paginate(100);
        $data=ReturnSalesResources::collection($items);
        $x=['status'=>200,'msg'=>trans('admin.Success')];
        return $data->additional($x) ;
    }

//ReturnSalesApi
    public function ReturnSalesApi(Request $request){

        try {
            DB::beginTransaction();

            $header = $request->header('Authorization', '');
            if (Str::startsWith($header, 'Bearer ')) {
                $x=Str::substr($header, 7);
            }
            $admin=Admin::where('token',$x)->first();

            if(request('Payment_Method') == 'Cash'){
                $paid=request('Total_Return_Value');

                $SafyFatora=request('Total_Return_Value');
            }else{
                $paid=request('Pay');

                if(!empty($paid)){

                    $SafyFatora=$paid;
                }else{
                    $SafyFatora=0;

                }

            }

            if(request('Payment_Method') == 'Cash') {
                $SafeBalance = $this->SafeCredit(request('Safe'), $SafyFatora);

                if ($SafeBalance == 1) {

                    return $this->returnError(trans('admin.SafeNotEnoughMoney'));

                }
            }

            $id=request('sales_id');
            $item=Sales::find($id);
            $branch=Stores::find($item->Store);
            $custG=Customers::where('Account',$item->Client)->orderBy('id','desc')->first();

            if(!empty($branch)){
                $BRAAA=$branch->Branch;
            }else{
                $BRAAA=null;
            }


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


            if($item->TaxBill == 1){
                $TaxBill=$item->TaxBill;
                $TaxCode=$item->TaxCode;
            }else{
                $TaxBill=null;
                $TaxCode=null;
            }

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


                    'Date' => request('Date'),
                    'Total_Return_Qty' => request('Total_Return_Qty'),
                    'Total_Return_Value' => request('Total_Return_Value'),
                    'Total_BF_Taxes' => request('Total_BF_Taxes'),
                    'Total_Taxes' => request('Total_Taxes'),
                    'Total_Discount' => request('Total_Discount'),
                    'Pay' => $paid,
                    'Time' => date("h:i:s a", time()),
                    'Branch' => $BRAAA,
                    'CustomerGroup' => $CUSTGROP,
                    'Refernce_Number' => $item->Refernce_Number,
                    'Safe' => $item->Safe,
                    'Client' => $item->Client,
                    'Executor' => $item->Executor,
                    'Delegate' => $item->Delegate,
                    'Store' => $item->Store,
                    'Coin' => $item->Coin,
                    'Cost_Center' => $item->Cost_Center,
                    'Ship' => $item->Ship,
                    'Later_Due' => $item->Later_Due,
                    'InstallCompany' => $item->InstallCompany,
                    'Delivery' => $item->Delivery,
                    'Payment_Method' => request('Payment_Method'),
                    'TaxBill' =>$TaxBill,
                    'TaxCode' =>$TaxCode,
                    'Sales' => $id,
                    'Edit' => 0,
                    'Delete' => 0,
                    'Edit_New_Code' => 0,
                    'Current_Credit' => request('Current_Credit'),
                    'User' => $admin->id,

                )
            );


            //Return Sales Event
            $Bill_Code=ReturnSales::findOrFail($ID);
            ReturnSalesEventApi::dispatch($request->all(),$ID,$admin->id);



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

            $NTQty= $pr->Total_Qty - request('Total_Return_Qty') ;
            $NTBFTax= $pr->Total_BF_Taxes - request('Total_BF_Taxes') ;
            $NTTax= $pr->Total_Taxes - request('Total_Taxes') ;
            $NTPrice= $pr->Total_Price - request('Total_Return_Value') ;
            $TOTALCOST= $pr->Total_Cost - request('Total_Cost_Return_Value') ;

            Sales::where('id',$id)
                ->update(['Total_Qty'=>$NTQty,'Total_BF_Taxes'=>$NTBFTax,'Total_Taxes'=>$NTTax,'Total_Price'=>$NTPrice,'Total_Cost'=>$TOTALCOST]);



            $dataUser=[
                'id'=>$admin->id,
                'screen_ar'=>'مرتجع المبيعات',
                'screen_en'=>'Return Sales',
                'explain_ar'=>$Bill_Code->Code,
                'explain_en'=>$Bill_Code->Code,
            ];
            $this->UserCreateMoves($dataUser);


            DB::commit();

            return $this->returnSuccessMessage(trans('admin.Return_Successfully'));

        }catch(\Exception $ex){

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch(\Error $ex){

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }



    }


    //=====  POS  =====================

    // = =========  SerachProductFilter ==============
    public function SerachProductFilter(Request $request,SalesService $service){

            $Array=array();

            $search = $request->get('search');
            $store = $request->get('store_id');
            $client = $request->get('client_id');
            $Brand='';
            $Group='';

        $Prods=$this->FilterSalesProductQty($search,$store,$Brand,$Group);
        $data=$this->FilterSalesProduct($search,$Brand,$Group);


        $total_row = $Prods->count();
        $total_row2 = $data->count();
        $total_row3 = $total_row + $total_row2;
        if($total_row3 > 0)
        {

            if(count($Prods) != 0) {

                $Def=SalesDefaultData::orderBy('id','desc')->first();
                $showw=DefaultDataShowHide::orderBy('id','desc')->first();
                $st = Stores::find($store);
                $Array=[];
                foreach($Prods as $rows) {


                    if($rows->Store == $store) {
                        $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()->Weight)) {
                            $weigh = $rows->Product()->first()->Weight;
                        } else {
                            $weigh = 0;
                        }

                        if (!empty($rows->Product()->first()->Maximum_Sales_Qty)) {
                            $maxSa = $rows->Product()->first()->Maximum_Sales_Qty;
                        } else {
                            $maxSa = 0;
                        }

                        if (!empty($rows->Product()->first()->Group()->first()->Discount)) {
                            $Higher = $rows->Product()->first()->Group()->first()->Discount;
                        } else {

                            $Higher = 0;
                        }

                        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;
                        }

                        $Filter = [

                            'client' => $client,
                            '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,
                            'weigh' => $weigh,
                            'maxSa' => $maxSa,
                            'P_Code' => $p_code,
                            'qty' => $rows->Qty,
                            'Original' => $rows->Original,
                            'Patch_Number' => $rows->Patch_Number,
                            'brandd' => $brandd,
                            'ShowGrBr' => $ShowGrBr,
                            'Higher' => $Higher,
                            'v_name' => $v_name,
                            'vv_name' => $vv_name,
                            'serial' => $serial,
                            'Exp_Date' => $rows->Exp_Date,
                            'pro_store' => $rows->Store,


                        ];
                        $filter = $service->ProductsQtyFilterApi($Filter);

                        if (count($filter) != 0) {
                            array_push($Array, [

                                'row_id' => $filter['row_id'],
                                'product_name' => $filter['product_name'],
                                'product_ar_name' => $filter['product_ar_name'],
                                'product_en_name' => $filter['product_en_name'],
                                'product_id' => $filter['product_id'],
                                'virable_one_id' => $filter['virable_one_id'],
                                'virable_two_id' => $filter['virable_two_id'],
                                'virable_one_name' => $filter['virable_one_name'],
                                'virable_two_name' => $filter['virable_two_name'],
                                'product_code' => $filter['product_code'],
                                'unit_name' => $filter['unit_name'],
                                'unit_id' => $filter['unit_id'],
                                'unit_default' => $filter['unit_default'],
                                'units' => $filter['units'],
                                'code_default' => $filter['code_default'],
                                'tax_rate' => $filter['tax_rate'],
                                'tax_type' => $filter['tax_type'],
                                'tax_id' => $filter['tax_id'],
                                'avalible_qty' => $filter['avalible_qty'],
                                'qty' => $filter['qty'],
                                'price' => $filter['price'],
                                'priceOne' => $filter['priceOne'],
                                'priceTwo' => $filter['priceTwo'],
                                'priceThree' => $filter['priceThree'],
                                'discount' => $filter['discount'],
                                'total_disc_pro' => $filter['total_disc_pro'],
                                'total_before_tax' => $filter['total_before_tax'],
                                'tax_value' => $filter['tax_value'],
                                'total' => $filter['total'],
                                'store_id' => $filter['store_id'],
                                'store_name' => $filter['store_name'],
                                'ExpDate' => $filter['ExpDate'],
                                'serial' => $filter['serial'],
                                'high_disc' => $filter['high_disc'],
                                'cost_price' => $filter['cost_price'],
                                'weight' => $filter['weight'],
                                'max_sales' => $filter['max_sales'],
                                'unit_rate' => $filter['unit_rate'],
                                'sales_pro_desc' => $filter['sales_pro_desc'],

                            ]);
                        }

                    }
                }

            }else{

                $Def=SalesDefaultData::orderBy('id','desc')->first();
                $showw=DefaultDataShowHide::orderBy('id','desc')->first();
                $st = Stores::find($store);
                $Array=[];
                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){

                        $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()->Weight)){
                            $weigh=$rows->Product()->first()->Weight;
                        }else{
                            $weigh=0;
                        }

                        if(!empty($rows->Product()->first()->Maximum_Sales_Qty)){
                            $maxSa=$rows->Product()->first()->Maximum_Sales_Qty;
                        }else{
                            $maxSa=0;
                        }

                        if(!empty($rows->Product()->first()->Group()->first()->Discount)){
                            $Higher=$rows->Product()->first()->Group()->first()->Discount;
                        }else{

                            $Higher=0;
                        }

                        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 == 'Assembly'){

                            $type=1;

                            $cost=$service->AssemblyCost($rows->Product,$store);
                            $qty=$service->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=[

                                'client'=>$client,
                                '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,
                                'weigh'=>$weigh,
                                'maxSa'=>$maxSa,
                                'P_Code'=>$p_code,
                                'qty'=>$qty,
                                'Original'=>$rows->Original,
                                'Patch_Number'=>$rows->Patch_Number,
                                'brandd'=>$brandd,
                                'ShowGrBr'=>$ShowGrBr,
                                'Higher'=>$Higher,
                                'v_name'=>$v_name,
                                'vv_name'=>$vv_name,
                                'serial'=>$serial,
                                'Exp_Date'=>$rows->Exp_Date,
                                'cost'=>$cost,

                            ];

                            $filter = $service->ProductsFilterApi($Filter);
                            if(count($filter) != 0) {
                                array_push($Array, [



                                    'product_name'=>$filter['product_name'],
                                    'product_ar_name'=>$filter['product_ar_name'],
                                    'product_en_name'=>$filter['product_en_name'],
                                    'product_id'=>$filter['product_id'],
                                    'virable_one_id'=>$filter['virable_one_id'],
                                    'virable_two_id'=>$filter['virable_two_id'],
                                    'virable_one_name'=>$filter['virable_one_name'],
                                    'virable_two_name'=>$filter['virable_two_name'],
                                    'product_code'=>$filter['product_code'],
                                    'unit_name'=>$filter['unit_name'],
                                    'unit_id'=>$filter['unit_id'],
                                    'unit_default'=>$filter['unit_default'],
                                    'units'=>$filter['units'],
                                    'code_default'=>$filter['code_default'],
                                    'tax_rate'=>$filter['tax_rate'],
                                    'tax_type'=>$filter['tax_type'],
                                    'tax_id'=>$filter['tax_id'],
                                    'avalible_qty'=>$filter['avalible_qty'],
                                    'qty'=>$filter['qty'],
                                    'price'=>$filter['price'],
                                    'priceOne'=>$filter['priceOne'],
                                    'priceTwo'=>$filter['priceTwo'],
                                    'priceThree'=>$filter['priceThree'],
                                    'discount'=>$filter['discount'],
                                    'total_disc_pro'=>$filter['total_disc_pro'],
                                    'total_before_tax'=>$filter['total_before_tax'],
                                    'tax_value'=>$filter['tax_value'],
                                    'total'=>$filter['total'],
                                    'store_id'=>$filter['store_id'],
                                    'store_name'=>$filter['store_name'],
                                    'ExpDate'=>$filter['ExpDate'],
                                    'serial'=>$filter['serial'],
                                    'high_disc'=>$filter['high_disc'],
                                    'cost_price'=>$filter['cost_price'],
                                    'weight'=>$filter['weight'],
                                    'max_sales'=>$filter['max_sales'],
                                    'unit_rate'=>$filter['unit_rate'],
                                    'sales_pro_desc'=>$filter['sales_pro_desc'],


                                ]);
                            }


                        }

                    }
                }

            }

        }else
        {

            return $this->returnError(trans('admin.No_Data_Find'));

        }

        return $this->returnData('data',$Array);

    }

    public function SerachProductGroupFilter(Request $request,SalesService $service){

            $Array=array();

            $search = $request->get('search');
            $store = $request->get('store_id');
            $client = $request->get('client_id');
            $Brand='';
            $group=$request->get('group');

        $Prods=$this->FilterSalesProductQtyGroup($group,$store);
        $data=$this->FilterSalesProductGroup($group);


        $total_row = $Prods->count();
        $total_row2 = $data->count();
        $total_row3 = $total_row + $total_row2;
        if($total_row3 > 0)
        {

            if(count($Prods) != 0) {

                $Def=SalesDefaultData::orderBy('id','desc')->first();
                $showw=DefaultDataShowHide::orderBy('id','desc')->first();
                $st = Stores::find($store);
                $Array=[];
                foreach($Prods as $rows) {
                    if($rows->Store == $store) {
                    $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()->Weight)){
                        $weigh=$rows->Product()->first()->Weight;
                    }else{
                        $weigh=0;
                    }

                    if(!empty($rows->Product()->first()->Maximum_Sales_Qty)){
                        $maxSa=$rows->Product()->first()->Maximum_Sales_Qty;
                    }else{
                        $maxSa=0;
                    }

                    if(!empty($rows->Product()->first()->Group()->first()->Discount)){
                        $Higher=$rows->Product()->first()->Group()->first()->Discount;
                    }else{

                        $Higher=0;
                    }

                    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($rows->Product()->first()->Group == $group) {
                        $Filter = [

                            'client' => $client,
                            '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,
                            'weigh' => $weigh,
                            'maxSa' => $maxSa,
                            'P_Code' => $p_code,
                            'qty' => $rows->Qty,
                            'Original' => $rows->Original,
                            'Patch_Number' => $rows->Patch_Number,
                            'brandd' => $brandd,
                            'ShowGrBr' => $ShowGrBr,
                            'Higher' => $Higher,
                            'v_name' => $v_name,
                            'vv_name' => $vv_name,
                            'serial' => $serial,
                            'Exp_Date' => $rows->Exp_Date,
                            'pro_store' => $rows->Store,


                        ];
                        $filter = $service->ProductsQtyFilterApi($Filter);

                        if (count($filter) != 0) {
                            array_push($Array, [

                                'row_id'=>$filter['row_id'],
                                'product_name'=>$filter['product_name'],
                                'product_ar_name'=>$filter['product_ar_name'],
                                'product_en_name'=>$filter['product_en_name'],
                                'product_id'=>$filter['product_id'],
                                'virable_one_id'=>$filter['virable_one_id'],
                                'virable_two_id'=>$filter['virable_two_id'],
                                'virable_one_name'=>$filter['virable_one_name'],
                                'virable_two_name'=>$filter['virable_two_name'],
                                'product_code'=>$filter['product_code'],
                                'unit_name'=>$filter['unit_name'],
                                'unit_id'=>$filter['unit_id'],
                                'unit_default'=>$filter['unit_default'],
                                'units'=>$filter['units'],
                                'code_default'=>$filter['code_default'],
                                'tax_rate'=>$filter['tax_rate'],
                                'tax_type'=>$filter['tax_type'],
                                'tax_id'=>$filter['tax_id'],
                                'avalible_qty'=>$filter['avalible_qty'],
                                'qty'=>$filter['qty'],
                                'price'=>$filter['price'],
                                'discount'=>$filter['discount'],
                                'total_disc_pro'=>$filter['total_disc_pro'],
                                'total_before_tax'=>$filter['total_before_tax'],
                                'tax_value'=>$filter['tax_value'],
                                'total'=>$filter['total'],
                                'store_id'=>$filter['store_id'],
                                'store_name'=>$filter['store_name'],
                                'ExpDate'=>$filter['ExpDate'],
                                'serial'=>$filter['serial'],
                                'high_disc'=>$filter['high_disc'],
                                'cost_price'=>$filter['cost_price'],
                                'weight'=>$filter['weight'],
                                'max_sales'=>$filter['max_sales'],
                                'unit_rate'=>$filter['unit_rate'],
                                'sales_pro_desc'=>$filter['sales_pro_desc'],

                            ]);
                        }
                    }

                }
                }

            }else{

                $Def=SalesDefaultData::orderBy('id','desc')->first();
                $showw=DefaultDataShowHide::orderBy('id','desc')->first();
                $st = Stores::find($store);
                $Array=[];
                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){

                        $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()->Weight)){
                            $weigh=$rows->Product()->first()->Weight;
                        }else{
                            $weigh=0;
                        }

                        if(!empty($rows->Product()->first()->Maximum_Sales_Qty)){
                            $maxSa=$rows->Product()->first()->Maximum_Sales_Qty;
                        }else{
                            $maxSa=0;
                        }

                        if(!empty($rows->Product()->first()->Group()->first()->Discount)){
                            $Higher=$rows->Product()->first()->Group()->first()->Discount;
                        }else{

                            $Higher=0;
                        }

                        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 == 'Assembly'){

                            $type=1;

                            $cost=$service->AssemblyCost($rows->Product,$store);
                            $qty=$service->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'){
                            if($rows->Product()->first()->Group == $group) {
                            $Filter=[

                                'client'=>$client,
                                '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,
                                'weigh'=>$weigh,
                                'maxSa'=>$maxSa,
                                'P_Code'=>$p_code,
                                'qty'=>$qty,
                                'Original'=>$rows->Original,
                                'Patch_Number'=>$rows->Patch_Number,
                                'brandd'=>$brandd,
                                'ShowGrBr'=>$ShowGrBr,
                                'Higher'=>$Higher,
                                'v_name'=>$v_name,
                                'vv_name'=>$vv_name,
                                'serial'=>$serial,
                                'Exp_Date'=>$rows->Exp_Date,
                                'cost'=>$cost,

                            ];

                            $filter = $service->ProductsFilterApi($Filter);
                            if(count($filter) != 0) {
                                array_push($Array, [


                                    'product_name'=>$filter['product_name'],
                                    'product_ar_name'=>$filter['product_ar_name'],
                                    'product_en_name'=>$filter['product_en_name'],
                                    'product_id'=>$filter['product_id'],
                                    'virable_one_id'=>$filter['virable_one_id'],
                                    'virable_two_id'=>$filter['virable_two_id'],
                                    'virable_one_name'=>$filter['virable_one_name'],
                                    'virable_two_name'=>$filter['virable_two_name'],
                                    'product_code'=>$filter['product_code'],
                                    'unit_name'=>$filter['unit_name'],
                                    'unit_id'=>$filter['unit_id'],
                                    'unit_default'=>$filter['unit_default'],
                                    'units'=>$filter['units'],
                                    'code_default'=>$filter['code_default'],
                                    'tax_rate'=>$filter['tax_rate'],
                                    'tax_type'=>$filter['tax_type'],
                                    'tax_id'=>$filter['tax_id'],
                                    'avalible_qty'=>$filter['avalible_qty'],
                                    'qty'=>$filter['qty'],
                                    'price'=>$filter['price'],
                                    'discount'=>$filter['discount'],
                                    'total_disc_pro'=>$filter['total_disc_pro'],
                                    'total_before_tax'=>$filter['total_before_tax'],
                                    'tax_value'=>$filter['tax_value'],
                                    'total'=>$filter['total'],
                                    'store_id'=>$filter['store_id'],
                                    'store_name'=>$filter['store_name'],
                                    'ExpDate'=>$filter['ExpDate'],
                                    'serial'=>$filter['serial'],
                                    'high_disc'=>$filter['high_disc'],
                                    'cost_price'=>$filter['cost_price'],
                                    'weight'=>$filter['weight'],
                                    'max_sales'=>$filter['max_sales'],
                                    'unit_rate'=>$filter['unit_rate'],
                                    'sales_pro_desc'=>$filter['sales_pro_desc'],

                                ]);
                            }


                        }
                        }

                    }
                }

            }

        }else
        {

            return $this->returnError(trans('admin.No_Data_Find'));

        }

        return $this->returnData('data',$Array);

    }

    public function SerachProductBrandFilter(Request $request,SalesService $service){

            $Array=array();

            $search = $request->get('search');
            $store = $request->get('store_id');
            $client = $request->get('client_id');
            $Brand='';
            $group=$request->get('brand');

        $Prods=$this->FilterSalesProductQtyBrand($group,$store);
        $data=$this->FilterSalesProductBrand($group);


        $total_row = $Prods->count();
        $total_row2 = $data->count();
        $total_row3 = $total_row + $total_row2;
        if($total_row3 > 0)
        {

            if(count($Prods) != 0) {

                $Def=SalesDefaultData::orderBy('id','desc')->first();
                $showw=DefaultDataShowHide::orderBy('id','desc')->first();
                $st = Stores::find($store);
                $Array=[];
                foreach($Prods as $rows) {
                    if($rows->Store == $store) {
                    $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()->Weight)){
                        $weigh=$rows->Product()->first()->Weight;
                    }else{
                        $weigh=0;
                    }

                    if(!empty($rows->Product()->first()->Maximum_Sales_Qty)){
                        $maxSa=$rows->Product()->first()->Maximum_Sales_Qty;
                    }else{
                        $maxSa=0;
                    }

                    if(!empty($rows->Product()->first()->Group()->first()->Discount)){
                        $Higher=$rows->Product()->first()->Group()->first()->Discount;
                    }else{

                        $Higher=0;
                    }

                    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($rows->Product()->first()->Brand == $group) {
                        $Filter = [

                            'client' => $client,
                            '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,
                            'weigh' => $weigh,
                            'maxSa' => $maxSa,
                            'P_Code' => $p_code,
                            'qty' => $rows->Qty,
                            'Original' => $rows->Original,
                            'Patch_Number' => $rows->Patch_Number,
                            'brandd' => $brandd,
                            'ShowGrBr' => $ShowGrBr,
                            'Higher' => $Higher,
                            'v_name' => $v_name,
                            'vv_name' => $vv_name,
                            'serial' => $serial,
                            'Exp_Date' => $rows->Exp_Date,
                            'pro_store' => $rows->Store,


                        ];
                        $filter = $service->ProductsQtyFilterApi($Filter);

                        if (count($filter) != 0) {
                            array_push($Array, [

                                'row_id'=>$filter['row_id'],
                                'product_name'=>$filter['product_name'],
                                'product_ar_name'=>$filter['product_ar_name'],
                                'product_en_name'=>$filter['product_en_name'],
                                'product_id'=>$filter['product_id'],
                                'virable_one_id'=>$filter['virable_one_id'],
                                'virable_two_id'=>$filter['virable_two_id'],
                                'virable_one_name'=>$filter['virable_one_name'],
                                'virable_two_name'=>$filter['virable_two_name'],
                                'product_code'=>$filter['product_code'],
                                'unit_name'=>$filter['unit_name'],
                                'unit_id'=>$filter['unit_id'],
                                'unit_default'=>$filter['unit_default'],
                                'units'=>$filter['units'],
                                'code_default'=>$filter['code_default'],
                                'tax_rate'=>$filter['tax_rate'],
                                'tax_type'=>$filter['tax_type'],
                                'tax_id'=>$filter['tax_id'],
                                'avalible_qty'=>$filter['avalible_qty'],
                                'qty'=>$filter['qty'],
                                'price'=>$filter['price'],
                                'discount'=>$filter['discount'],
                                'total_disc_pro'=>$filter['total_disc_pro'],
                                'total_before_tax'=>$filter['total_before_tax'],
                                'tax_value'=>$filter['tax_value'],
                                'total'=>$filter['total'],
                                'store_id'=>$filter['store_id'],
                                'store_name'=>$filter['store_name'],
                                'ExpDate'=>$filter['ExpDate'],
                                'serial'=>$filter['serial'],
                                'high_disc'=>$filter['high_disc'],
                                'cost_price'=>$filter['cost_price'],
                                'weight'=>$filter['weight'],
                                'max_sales'=>$filter['max_sales'],
                                'unit_rate'=>$filter['unit_rate'],
                                'sales_pro_desc'=>$filter['sales_pro_desc'],

                            ]);
                        }
                    }

                }
                }

            }else{

                $Def=SalesDefaultData::orderBy('id','desc')->first();
                $showw=DefaultDataShowHide::orderBy('id','desc')->first();
                $st = Stores::find($store);
                $Array=[];
                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){

                        $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()->Weight)){
                            $weigh=$rows->Product()->first()->Weight;
                        }else{
                            $weigh=0;
                        }

                        if(!empty($rows->Product()->first()->Maximum_Sales_Qty)){
                            $maxSa=$rows->Product()->first()->Maximum_Sales_Qty;
                        }else{
                            $maxSa=0;
                        }

                        if(!empty($rows->Product()->first()->Group()->first()->Discount)){
                            $Higher=$rows->Product()->first()->Group()->first()->Discount;
                        }else{

                            $Higher=0;
                        }

                        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 == 'Assembly'){

                            $type=1;

                            $cost=$service->AssemblyCost($rows->Product,$store);
                            $qty=$service->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'){
                            if($rows->Product()->first()->Brand == $group) {
                            $Filter=[

                                'client'=>$client,
                                '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,
                                'weigh'=>$weigh,
                                'maxSa'=>$maxSa,
                                'P_Code'=>$p_code,
                                'qty'=>$qty,
                                'Original'=>$rows->Original,
                                'Patch_Number'=>$rows->Patch_Number,
                                'brandd'=>$brandd,
                                'ShowGrBr'=>$ShowGrBr,
                                'Higher'=>$Higher,
                                'v_name'=>$v_name,
                                'vv_name'=>$vv_name,
                                'serial'=>$serial,
                                'Exp_Date'=>$rows->Exp_Date,
                                'cost'=>$cost,

                            ];

                            $filter = $service->ProductsFilterApi($Filter);
                            if(count($filter) != 0) {
                                array_push($Array, [


                                    'product_name'=>$filter['product_name'],
                                    'product_ar_name'=>$filter['product_ar_name'],
                                    'product_en_name'=>$filter['product_en_name'],
                                    'product_id'=>$filter['product_id'],
                                    'virable_one_id'=>$filter['virable_one_id'],
                                    'virable_two_id'=>$filter['virable_two_id'],
                                    'virable_one_name'=>$filter['virable_one_name'],
                                    'virable_two_name'=>$filter['virable_two_name'],
                                    'product_code'=>$filter['product_code'],
                                    'unit_name'=>$filter['unit_name'],
                                    'unit_id'=>$filter['unit_id'],
                                    'unit_default'=>$filter['unit_default'],
                                    'units'=>$filter['units'],
                                    'code_default'=>$filter['code_default'],
                                    'tax_rate'=>$filter['tax_rate'],
                                    'tax_type'=>$filter['tax_type'],
                                    'tax_id'=>$filter['tax_id'],
                                    'avalible_qty'=>$filter['avalible_qty'],
                                    'qty'=>$filter['qty'],
                                    'price'=>$filter['price'],
                                    'discount'=>$filter['discount'],
                                    'total_disc_pro'=>$filter['total_disc_pro'],
                                    'total_before_tax'=>$filter['total_before_tax'],
                                    'tax_value'=>$filter['tax_value'],
                                    'total'=>$filter['total'],
                                    'store_id'=>$filter['store_id'],
                                    'store_name'=>$filter['store_name'],
                                    'ExpDate'=>$filter['ExpDate'],
                                    'serial'=>$filter['serial'],
                                    'high_disc'=>$filter['high_disc'],
                                    'cost_price'=>$filter['cost_price'],
                                    'weight'=>$filter['weight'],
                                    'max_sales'=>$filter['max_sales'],
                                    'unit_rate'=>$filter['unit_rate'],
                                    'sales_pro_desc'=>$filter['sales_pro_desc'],

                                ]);
                            }


                        }
                        }

                    }
                }

            }

        }else
        {

            return $this->returnError(trans('admin.No_Data_Find'));

        }

        return $this->returnData('data',$Array);

    }

    public function SerachAllProductFilter(Request $request,SalesService $service){

            $Array=array();

            $search = $request->get('search');
            $store = $request->get('store_id');
            $client = $request->get('client_id');


        $Prods=$this->FilterSalesProductQtyAll($store);
        $data=$this->FilterSalesProductAll();


        $total_row = $Prods->count();
        $total_row2 = $data->count();
        $total_row3 = $total_row + $total_row2;
        if($total_row3 > 0)
        {

            if(count($Prods) != 0) {

                $Def=SalesDefaultData::orderBy('id','desc')->first();
                $showw=DefaultDataShowHide::orderBy('id','desc')->first();
                $st = Stores::find($store);
                $Array=[];
                foreach($Prods as $rows) {
                    if($rows->Store == $store) {
                    $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()->Weight)){
                        $weigh=$rows->Product()->first()->Weight;
                    }else{
                        $weigh=0;
                    }

                    if(!empty($rows->Product()->first()->Maximum_Sales_Qty)){
                        $maxSa=$rows->Product()->first()->Maximum_Sales_Qty;
                    }else{
                        $maxSa=0;
                    }

                    if(!empty($rows->Product()->first()->Group()->first()->Discount)){
                        $Higher=$rows->Product()->first()->Group()->first()->Discount;
                    }else{

                        $Higher=0;
                    }

                    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;
                    }


                        $Filter = [

                            'client' => $client,
                            '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,
                            'weigh' => $weigh,
                            'maxSa' => $maxSa,
                            'P_Code' => $p_code,
                            'qty' => $rows->Qty,
                            'Original' => $rows->Original,
                            'Patch_Number' => $rows->Patch_Number,
                            'brandd' => $brandd,
                            'ShowGrBr' => $ShowGrBr,
                            'Higher' => $Higher,
                            'v_name' => $v_name,
                            'vv_name' => $vv_name,
                            'serial' => $serial,
                            'Exp_Date' => $rows->Exp_Date,
                            'pro_store' => $rows->Store,


                        ];
                        $filter = $service->ProductsQtyFilterApi($Filter);

                        if (count($filter) != 0) {
                            array_push($Array, [

                                'row_id'=>$filter['row_id'],
                                'product_name'=>$filter['product_name'],
                                'product_ar_name'=>$filter['product_ar_name'],
                                'product_en_name'=>$filter['product_en_name'],
                                'product_id'=>$filter['product_id'],
                                'virable_one_id'=>$filter['virable_one_id'],
                                'virable_two_id'=>$filter['virable_two_id'],
                                'virable_one_name'=>$filter['virable_one_name'],
                                'virable_two_name'=>$filter['virable_two_name'],
                                'product_code'=>$filter['product_code'],
                                'unit_name'=>$filter['unit_name'],
                                'unit_id'=>$filter['unit_id'],
                                'unit_default'=>$filter['unit_default'],
                                'units'=>$filter['units'],
                                'code_default'=>$filter['code_default'],
                                'tax_rate'=>$filter['tax_rate'],
                                'tax_type'=>$filter['tax_type'],
                                'tax_id'=>$filter['tax_id'],
                                'avalible_qty'=>$filter['avalible_qty'],
                                'qty'=>$filter['qty'],
                                'price'=>$filter['price'],
                                'priceOne'=>$filter['priceOne'],
                                'priceTwo'=>$filter['priceTwo'],
                                'priceThree'=>$filter['priceThree'],
                                'discount'=>$filter['discount'],
                                'total_disc_pro'=>$filter['total_disc_pro'],
                                'total_before_tax'=>$filter['total_before_tax'],
                                'tax_value'=>$filter['tax_value'],
                                'total'=>$filter['total'],
                                'store_id'=>$filter['store_id'],
                                'store_name'=>$filter['store_name'],
                                'ExpDate'=>$filter['ExpDate'],
                                'serial'=>$filter['serial'],
                                'high_disc'=>$filter['high_disc'],
                                'cost_price'=>$filter['cost_price'],
                                'weight'=>$filter['weight'],
                                'max_sales'=>$filter['max_sales'],
                                'unit_rate'=>$filter['unit_rate'],
                                'sales_pro_desc'=>$filter['sales_pro_desc'],

                            ]);
                        }


                }
                }

            }else{

                $Def=SalesDefaultData::orderBy('id','desc')->first();
                $showw=DefaultDataShowHide::orderBy('id','desc')->first();
                $st = Stores::find($store);
                $Array=[];
                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){

                        $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()->Weight)){
                            $weigh=$rows->Product()->first()->Weight;
                        }else{
                            $weigh=0;
                        }

                        if(!empty($rows->Product()->first()->Maximum_Sales_Qty)){
                            $maxSa=$rows->Product()->first()->Maximum_Sales_Qty;
                        }else{
                            $maxSa=0;
                        }

                        if(!empty($rows->Product()->first()->Group()->first()->Discount)){
                            $Higher=$rows->Product()->first()->Group()->first()->Discount;
                        }else{

                            $Higher=0;
                        }

                        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 == 'Assembly'){

                            $type=1;

                            $cost=$service->AssemblyCost($rows->Product,$store);
                            $qty=$service->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=[

                                'client'=>$client,
                                '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,
                                'weigh'=>$weigh,
                                'maxSa'=>$maxSa,
                                'P_Code'=>$p_code,
                                'qty'=>$qty,
                                'Original'=>$rows->Original,
                                'Patch_Number'=>$rows->Patch_Number,
                                'brandd'=>$brandd,
                                'ShowGrBr'=>$ShowGrBr,
                                'Higher'=>$Higher,
                                'v_name'=>$v_name,
                                'vv_name'=>$vv_name,
                                'serial'=>$serial,
                                'Exp_Date'=>$rows->Exp_Date,
                                'cost'=>$cost,

                            ];

                            $filter = $service->ProductsFilterApi($Filter);
                            if(count($filter) != 0) {
                                array_push($Array, [


                                    'product_name'=>$filter['product_name'],
                                    'product_ar_name'=>$filter['product_ar_name'],
                                    'product_en_name'=>$filter['product_en_name'],
                                    'product_id'=>$filter['product_id'],
                                    'virable_one_id'=>$filter['virable_one_id'],
                                    'virable_two_id'=>$filter['virable_two_id'],
                                    'virable_one_name'=>$filter['virable_one_name'],
                                    'virable_two_name'=>$filter['virable_two_name'],
                                    'product_code'=>$filter['product_code'],
                                    'unit_name'=>$filter['unit_name'],
                                    'unit_id'=>$filter['unit_id'],
                                    'unit_default'=>$filter['unit_default'],
                                    'units'=>$filter['units'],
                                    'code_default'=>$filter['code_default'],
                                    'tax_rate'=>$filter['tax_rate'],
                                    'tax_type'=>$filter['tax_type'],
                                    'tax_id'=>$filter['tax_id'],
                                    'avalible_qty'=>$filter['avalible_qty'],
                                    'qty'=>$filter['qty'],
                                    'price'=>$filter['price'],
                                    'priceOne'=>$filter['priceOne'],
                                    'priceTwo'=>$filter['priceTwo'],
                                    'priceThree'=>$filter['priceThree'],
                                    'discount'=>$filter['discount'],
                                    'total_disc_pro'=>$filter['total_disc_pro'],
                                    'total_before_tax'=>$filter['total_before_tax'],
                                    'tax_value'=>$filter['tax_value'],
                                    'total'=>$filter['total'],
                                    'store_id'=>$filter['store_id'],
                                    'store_name'=>$filter['store_name'],
                                    'ExpDate'=>$filter['ExpDate'],
                                    'serial'=>$filter['serial'],
                                    'high_disc'=>$filter['high_disc'],
                                    'cost_price'=>$filter['cost_price'],
                                    'weight'=>$filter['weight'],
                                    'max_sales'=>$filter['max_sales'],
                                    'unit_rate'=>$filter['unit_rate'],
                                    'sales_pro_desc'=>$filter['sales_pro_desc'],

                                ]);
                            }



                        }

                    }
                }

            }

        }else
        {

            return $this->returnError(trans('admin.No_Data_Find'));

        }

        return $this->returnData('data',$Array);

    }



   //==================================================
    //AddClientPos
    public function AddClientPos(Request $request){


        try {
            DB::beginTransaction();

            $header = $request->header('Authorization', '');
            if (Str::startsWith($header, 'Bearer ')) {
                $x=Str::substr($header, 7);
            }

            $admin=Admin::where('token',$x)->first();

            $rules = [
                "name" => "required",
            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $code = $this->returnCodeAccordingToInput($validator);
                return $this->returnValidationError($code, $validator);
            }

            $NaameAddress = request('address_name');
            $Governrate = request('governrate_id');
            $City = request('city_id');
            $Place = request('place_id');
            $Street = request('street');
            $Buliding = request('buliding');
            $Floor = request('floor');
            $Flat = request('flat');
            $Special_Mark = request('special_mark');
            $Location = request('location');
            $Address_Details = request('address_details');
            $lat = request('lat');
            $lng = request('lng');


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

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

                $english_name=request('name');
            }


            $Acc=$this->CreateAccountApi(request('name'),$english_name ,24 ,null,$admin->id);
            $Code=$this->ReturnCode(Customers::class);


            $data['Code']=$Code;
            $data['Date']=date('Y-m-d');
            $data['Name']=request('name');
            $data['NameEn']=$english_name;
            $data['Price_Level']=request('price_level');
            $data['Phone']=request('phone');
            $data['Address']=request('address');
            $data['Company_Name']=request('company_name');
            $data['Governrate']=request('governrate_id');
            $data['City']=request('city_id');
            $data['Place']=request('place_id');
            $data['Responsible']=$admin->emp;
            $data['Activity']=request('activity_id');
            $data['Group']=request('group');
            $data['Account']=$Acc;
            $data['User']=$admin->id;
            $data['Phone2']=request('phone2');
            $data['SearchCode']=request('search_code');
            Customers::create($data);





            $ID = Customers::latest('id')->first();

            $Addr['Address_Name']=$NaameAddress;
            $Addr['Street']=$Street;
            $Addr['Special_Mark']=$Special_Mark;
            $Addr['Buliding']=$Buliding;
            $Addr['Floor']=$Floor;
            $Addr['Flat']=$Flat;
            $Addr['Details']=$Address_Details;
            $Addr['Location']=$Location;
            $Addr['Governrate']=$Governrate;
            $Addr['City']=$City;
            $Addr['Place']=$Place;
            $Addr['Lat']=$lat;
            $Addr['Lng']=$lng;
            $Addr['Customer']=$ID->id;

            Addressses::create($Addr);

            $dataUser=[
                'id'=>$admin->id,
                'screen_ar'=>'العملاء',
                'screen_en'=>'Clients',
                'explain_ar'=>request('name'),
                'explain_en'=>$english_name,
            ];
            $this->UserCreateMoves($dataUser);
            DB::commit();


            return $this->returnSuccessMessage(trans('admin.Added_Successfully'));

        } catch (\Exception $ex) {

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch (\Error $ex) {
            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());
        }



    }

    //ClientVoucher
    public function ClientVoucher(Request $request){

        try {
            DB::beginTransaction();

            $rules = [
                "creditor" => "required",
                "client_id" => "required",
                "shift_id" => "required",
                "safe_id" => "required",
                "coin_id" => "required",
                "draw" => "required",
                "store_id" => "required",
            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $code = $this->returnCodeAccordingToInput($validator);
                return $this->returnValidationError($code, $validator);
            }


            $header = $request->header('Authorization', '');
            if (Str::startsWith($header, 'Bearer ')) {
                $x=Str::substr($header, 7);
            }

            $admin=Admin::where('token',$x)->first();
            $shift=Shifts::latest('id')->where('Emp',$admin->emp)->where('Close',0)->first();

            if(!empty($shift)){

                $Creditor = $request->get('creditor');
                $AccountCode = $request->get('client_id');
                $Shift = $request->get('shift_id');
                $Safe = $request->get('safe_id');
                $Coin = $request->get('coin_id');
                $Draw = $request->get('draw');
                $STORE = $request->get('store_id');
                $STATEMENT = $request->get('statement');


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

                    array(


                        'Date' => date('Y-m-d'),
                        'Draw' => $Draw,
                        'Coin' => $Coin,
                        'Safe' => $Safe,
                        'Cost_Center' => null,
                        'Total_Creditor' => $Creditor,
                        'Shift' => $Shift,
                        'Store' => $STORE,
                        'Note' => null,
                        'User' =>$admin->id,
                        'Collector' =>$admin->emp,
                        'Sales_Bill' =>null,

                    )
                );


                $PRODUCTS['RV_ID']=$IDD;
                $PRODUCTS['Creditor']=$Creditor;
                $PRODUCTS['Account']=$AccountCode;
                $PRODUCTS['Statement']=$STATEMENT;

                ReciptVoucherDetails::create($PRODUCTS);

                $Code=ReciptVoucher::findOrFail($IDD)->Code;

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

                    array(


                        'Type' => 'سند قبض',
                        'TypeEn' =>'Receipt Voucher',
                        'Code_Type' => $Code,
                        'Date' => date('Y-m-d'),
                        'Draw' => $Draw,
                        'Coin' => $Coin,
                        'Cost_Center' => null,
                        'Total_Debaitor' => $Creditor,
                        'Total_Creditor' => $Creditor,
                        'Note' => null,

                    )
                );

                $Codee=Journalizing::findOrFail($ID)->Code;

                $PRODUCTSS['Joun_ID']=$ID;
                $PRODUCTSS['Debitor']=0;
                $PRODUCTSS['Creditor']=$Creditor;
                $PRODUCTSS['Account']=$AccountCode;
                $PRODUCTSS['Statement']=$STATEMENT;


                JournalizingDetails::create($PRODUCTSS);

                $Gen['Code']=$Codee;
                $Gen['Code_Type']=$Code;
                $Gen['Date']=date('Y-m-d');
                $Gen['Type']= 'سند قبض';
                $Gen['TypeEn']='Receipt Voucher';
                $Gen['Debitor']=0;
                $Gen['Creditor']=$Creditor;
                $Gen['Statement']=$STATEMENT;
                $Gen['Draw']=$Draw;
                $Gen['Debitor_Coin']= $Draw * 0;
                $Gen['Creditor_Coin']=$Draw * $Creditor;
                $Gen['Account']=$AccountCode;
                $Gen['Coin']= $Coin;
                $Gen['Cost_Center']= null;
                $Gen['userr']=$admin->id;

                GeneralDaily::create($Gen);


                $PRODUCTSSS['Joun_ID']=$ID;
                $PRODUCTSSS['Debitor']=$Creditor;
                $PRODUCTSSS['Creditor']=0;
                $PRODUCTSSS['Account']=$Safe;
                $PRODUCTSSS['Statement']=$STATEMENT;
                JournalizingDetails::create($PRODUCTSSS);

                $Genn['Code']=$Codee;
                $Genn['Code_Type']=$Code;
                $Genn['Date']=date('Y-m-d');
                $Genn['Type']= 'سند قبض';
                $Genn['TypeEn']='Receipt Voucher';
                $Genn['Debitor']=$Creditor;
                $Genn['Creditor']=0;
                $Genn['Statement']=$STATEMENT;
                $Genn['Draw']=$Draw;
                $Genn['Debitor_Coin']= $Draw * $Creditor;
                $Genn['Creditor_Coin']=$Draw * 0;
                $Genn['Account']=$Safe;
                $Genn['Coin']= $Coin;
                $Genn['Cost_Center']= null;
                $Genn['userr']=$admin->id;

                GeneralDaily::create($Genn);


                if($Shift!= null){
                    $shift=Shifts::where('Code',$Shift)->first();
                    $new['Total_Recipt']=$shift->Total_Recipt  + $Creditor;
                    $new['Total']=$shift->Total  + $Creditor;
                    Shifts::where('id',$Shift)->update($new);
                }


            }else{

                return $this->returnError(trans('admin.NoShiftOpen'));

            }

            $dataUser=[
                'id'=>$admin->id,
                'screen_ar'=>'سند قبض',
                'screen_en'=>'Receipt Voucher',
                'explain_ar'=>$Code,
                'explain_en'=>$Code,
            ];
            $this->UserCreateMoves($dataUser);
            DB::commit();

            return $this->returnSuccessMessage(trans('admin.Added_Successfully'));

        } catch (\Exception $ex) {

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch (\Error $ex) {
            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());
        }


    }

    public function ClientVoucherCode(Request $request){

        $Code=$this->ReturnCode(ReciptVoucher::class);
        return $this->returnData('data',$Code,trans('admin.Success'));

    }

    //ExpensesVoucher
    public function ExpensesVoucher(Request $request){


        try {
            DB::beginTransaction();

            $rules = [
                "debitor" => "required",
                "expenses_account_id" => "required",

                "safe_id" => "required",
                "coin_id" => "required",
                "draw" => "required",
                "store_id" => "required",
            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $code = $this->returnCodeAccordingToInput($validator);
                return $this->returnValidationError($code, $validator);
            }
            $header = $request->header('Authorization', '');
            if (Str::startsWith($header, 'Bearer ')) {
                $x=Str::substr($header, 7);
            }

            $admin=Admin::where('token',$x)->first();
            $shift=Shifts::latest('id')->where('Emp',$admin->emp)->where('Close',0)->first();


            if(!empty($shift)){

                $Debitor = $request->get('debitor');
                $AccountCodee = $request->get('expenses_account_id');
                $Shift = $request->get('shift_id');
                $Safe = $request->get('safe_id');
                $Coin = $request->get('coin_id');
                $Draw = $request->get('draw');
                $STORE = $request->get('store_id');
                $STATEMENT = $request->get('statement');

                $NewSafe=SafesBanks::where('Account',$Safe)->latest('id')->first();


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

                    array(

                        'Date' => date('Y-m-d'),
                        'Draw' => $Draw,
                        'Coin' => $Coin,
                        'Safe' => $Safe,
                        'Shift' => $Shift,
                        'Store' => $STORE,
                        'Cost_Center' => null,
                        'Total_Debaitor' => $Debitor,
                        'Note' => null,
                        'User' =>$admin->id,
                        'Branch' => $NewSafe->Branch,
                    )
                );

                $PRODUCTS['PV_ID']=$IDD;
                $PRODUCTS['Debitor']=$Debitor;
                $PRODUCTS['Account']=$AccountCodee;
                $PRODUCTS['Statement']=$STATEMENT;
                $PRODUCTS['Date']=date('Y-m-d');
                $PRODUCTS['Time']=date("h:i:s a", time());
                $PRODUCTS['Cost_Center']=null;
                $PRODUCTS['Coin']=$Coin;
                $PRODUCTS['User']=$admin->id;
                $PRODUCTS['Branch']=$NewSafe->Branch;
                $PRODUCTS['Safe']=$Safe;

                PaymentVoucherDetails::create($PRODUCTS);

                $Code=PaymentVoucher::findOrFail($IDD)->Code;


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

                    array(


                        'Type' =>  'سند صرف',
                        'TypeEn' => 'Payment Voucher',
                        'Code_Type' => $Code,
                        'Date' => date('Y-m-d'),
                        'Draw' => $Draw,
                        'Coin' => $Coin,
                        'Cost_Center' => null,
                        'Total_Debaitor' => $Debitor,
                        'Total_Creditor' =>$Debitor,
                        'Note' => null,

                    )
                );


                $PRODUCTSS['Joun_ID']=$ID;
                $PRODUCTSS['Debitor']=$Debitor;
                $PRODUCTSS['Creditor']=0;
                $PRODUCTSS['Account']=$AccountCodee;
                $PRODUCTSS['Statement']=$STATEMENT;


                JournalizingDetails::create($PRODUCTSS);

                $Codee=Journalizing::findOrFail($ID)->Code;

                $Gen['Code']=$Codee;
                $Gen['Code_Type']=$Code;
                $Gen['Date']=date('Y-m-d');
                $Gen['Type']= 'سند صرف';
                $Gen['TypeEn']= 'Payment Voucher';
                $Gen['Debitor']=$Debitor;
                $Gen['Creditor']=0;
                $Gen['Statement']=$STATEMENT;
                $Gen['Draw']=$Draw;
                $Gen['Debitor_Coin']= $Draw * $Debitor;
                $Gen['Creditor_Coin']=$Draw * 0;
                $Gen['Account']=$AccountCodee;
                $Gen['Coin']= $Coin;
                $Gen['Cost_Center']= null;
                $Gen['userr']=$admin->id;

                GeneralDaily::create($Gen);



                $PRODUCTSSS['Joun_ID']=$ID;
                $PRODUCTSSS['Debitor']=0;
                $PRODUCTSSS['Creditor']=$Debitor;
                $PRODUCTSSS['Account']=$Safe;
                $PRODUCTSSS['Statement']=$STATEMENT;
                JournalizingDetails::create($PRODUCTSSS);

                $Genn['Code']=$Codee;
                $Genn['Code_Type']=$Code;
                $Genn['Date']=date('Y-m-d');
                $Genn['Type']= 'سند صرف';
                $Genn['TypeEn']= 'Payment Voucher';
                $Genn['Debitor']=0;
                $Genn['Creditor']=$Debitor;
                $Genn['Statement']=$STATEMENT;
                $Genn['Draw']=$Draw;
                $Genn['Debitor_Coin']= $Draw * 0;
                $Genn['Creditor_Coin']=$Draw * $Debitor;
                $Genn['Account']=$Safe;
                $Genn['Coin']= $Coin;
                $Genn['Cost_Center']= null;
                $Genn['userr']=$admin->id;

                GeneralDaily::create($Genn);

                if($Shift!= null){
                    $shift=Shifts::where('Code',$Shift)->first();
                    $new['Total_Payment']=$shift->Total_Payment  + $Debitor;
                    $new['Total']=$shift->Total  - $Debitor;
                    Shifts::where('id',$Shift)->update($new);

                }
            }else{
                return $this->returnError(trans('admin.NoShiftOpen'));
            }

            $dataUser=[
                'id'=>$admin->id,
                'screen_ar'=>'سند صرف',
                'screen_en'=>'Payment Voucher',
                'explain_ar'=>$Code,
                'explain_en'=>$Code,
            ];
            $this->UserCreateMoves($dataUser);
            DB::commit();

            return $this->returnSuccessMessage(trans('admin.Added_Successfully'));

        } catch (\Exception $ex) {

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch (\Error $ex) {
            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());
        }



    }

    public function ExpensesVoucherCode(Request $request){

        $Code=$this->ReturnCode(PaymentVoucher::class);
        return $this->returnData('data',$Code,trans('admin.Success'));

    }

    // Return Code POS Page
    public function POSPage(Request $request){

        $Code=$this->ReturnCode(Sales::class);
        return $this->returnData('data',$Code,trans('admin.Success'));

    }

    //POSClients
    public function POSClients(Request $request){

        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }

        $admin=Admin::where('token',$x)->first();
        $lang = $request->header('lang', '');

            $crm=CrmDefaultData::orderBy('id','desc')->first();

            if($crm->Client_Delegate == 1){


                if($lang == 'ar'){
                    $clients=DB::table('acccounting_manuals')
                        ->where('acccounting_manuals.Type',1)
                        ->where('acccounting_manuals.Parent',24)

                        ->leftJoin('customers', function ($join) {

                            $join->on('acccounting_manuals.id', '=', 'customers.Account')

                            ;
                        })
                        ->where('customers.Responsible',$admin->emp)
                        ->select('customers.Name as client_name','customers.Account as client_id','customers.Phone as phone','customers.Price_Level as price_level')
                        ->get();
                }else{
                    $clients=DB::table('acccounting_manuals')
                        ->where('acccounting_manuals.Type',1)
                        ->where('acccounting_manuals.Parent',24)
                        ->leftJoin('customers', function ($join) {

                            $join->on('acccounting_manuals.id', '=', 'customers.Account')

                            ;
                        })
                        ->where('customers.Responsible',$admin->emp)
                        ->select('customers.NameEn as client_name','customers.Account as client_id','customers.Phone as phone','customers.Price_Level as price_level')
                        ->get();

                }

            }else{

                if($lang == 'ar'){
                    $clients=DB::table('acccounting_manuals')
                        ->where('Type',1)
                        ->where('Parent',24)
                        ->leftJoin('customers', function ($join) {

                            $join->on('acccounting_manuals.id', '=', 'customers.Account')

                            ;
                        })
                        ->select('acccounting_manuals.Name as client_name','acccounting_manuals.id as client_id','customers.Phone as phone','customers.Price_Level as price_level')
                        ->get();
                }else{

                    $clients=DB::table('acccounting_manuals')
                        ->where('Type',1)
                        ->where('Parent',24)
                        ->leftJoin('customers', function ($join) {

                            $join->on('acccounting_manuals.id', '=', 'customers.Account')

                            ;
                        })
                        ->select('acccounting_manuals.NameEn as client_name','acccounting_manuals.id as client_id','customers.Phone as phone','customers.Price_Level as price_level')
                        ->get();

                }
            }


           return $this->returnData('data',$clients);



    }

    //POS Stores
    public function POSStores(Request $request){

        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }

        $admin=Admin::where('token',$x)->first();
        $lang = $request->header('lang', '');
        $Array = array();
        if($admin->pos_stores == 1) {
            $stores = EmpPOSStores::where('Emp', $admin->emp)->get();


            foreach ($stores as $store) {


                if ($lang == 'ar') {

                    $StoreName = $store->Store()->first()->Name;
                } else {

                    $StoreName = $store->Store()->first()->NameEn;

                }
                array_push($Array, [
                    'store_name' => $StoreName,
                    'store_id' => $store->Store,

                ]);


            }



        }else{


            if ($lang == 'ar') {

                $StoreName = $admin->store()->first()->Name;
            } else {

                $StoreName = $admin->store()->first()->NameEn;

            }
            array_push($Array, [
                'store_name' => $StoreName,
                'store_id' => $admin->store,

            ]);


        }



            return $this->returnData('data', $Array);



    }

        //POS Safes
    public function POSSafes(Request $request){

        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }

        $admin=Admin::where('token',$x)->first();
        $lang = $request->header('lang', '');

        $Array=array();

        if($admin->pos_safes == 1) {
            $stores = EmpSafes::where('Emp', $admin->emp)->get();
            foreach($stores as $store){


                if($lang == 'ar'){

                    $StoreName=$store->Safe()->first()->Name;
                }else{

                    $StoreName=$store->Safe()->first()->NameEn;

                }
                array_push($Array,[
                    'safe_name'=>$StoreName,
                    'safe_id'=>$store->Safe,

                ]);


            }

        }else{

            if ($lang == 'ar') {

                $StoreName = $admin->safe()->first()->Name;
            } else {

                $StoreName = $admin->safe()->first()->NameEn;

            }
            array_push($Array, [
                'safe_name' => $StoreName,
                'safe_id' => $admin->safe,

            ]);


        }



        return $this->returnData('data',$Array);



    }

//ChangeUnit
    public function ChangeUnit(SalesService $service) {

        $states=[];
        $average = new Average ;
        $id=request('unit_id');
        $Pro=request('product_id');
        $Client=request('client_id');
        $code=request('product_code');
        $Store=request('store');


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

        $x = $this->ProAvQties($Store,$Pro,$code);

        $price=$service->PriceLevel($Client,$rr);

        $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 ,
                'rate' => $rr->Product()->first()->Tax()->first()->Rate ,
                'type' => $rr->Product()->first()->Tax()->first()->Type ,
                'tax' => $rr->Product()->first()->Tax ,
                'priceOne' => $rr->Price ,
                'priceTwo' => $rr->Price_Two ,
                'priceThree' => $rr->Price_Three,
                'qty'=>$Quntity,
                'cost'=>$COSTpr
            ];


        }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)){

                    $Quntity=$EXPO->Qty;
                }

                if(!empty($x)){
                    $Quntity= $x->Qty / $rr->Rate ;
                    if(!empty($EXPO)){

                        $Quntity=$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 ,
                        'rate' => $proo->Product()->first()->Tax()->first()->Rate ,
                        'type' => $proo->Product()->first()->Tax()->first()->Type ,
                        'tax' => $proo->Product()->first()->Tax ,
                        'priceOne' => $proo->Price ,
                        'priceTwo' => $proo->Price_Two ,
                        'priceThree' => $proo->Price_Three,
                        'qty'=>$Quntity,
                        'cost'=>$COSTpr
                    ];

                }

            }


        }

        return $this->returnData('data',$states);

    }

    public function ProUnits(SalesService $service) {

        $states=[];

        $Pro=request('product_id');

        $Units = ProductUnits::where('Product',$Pro)->get();

        $data=ProUnitsResources::collection($Units);

        return $this->returnData('data',$data);

    }

    //ClientAddresses
    public function ClientAddresses(Request $request){

            $Client=Customers::where('Account',request('client_id'))->first();

            if(!empty($Client)){
                $addresses=Addressses::where('Customer',$Client->id)->get();
                $data=CustomersAddressesResources::collection($addresses);
            }else{
                return $this->returnError(trans('admin.No_Addresss_Client'));
            }

            return $this->returnData('data',$data);

    }


    // ========== Hold Bills ===================

    //HoldBills
    public function HoldBills(Request $request){

        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }

        $admin=Admin::where('token',$x)->first();
        $lang = $request->header('lang', '');

            if($admin->pos_stores == 0){
                $HoldSales=SalesOrder::where('Delete',0)->where('Edit',0)->where('ToSales',0)->where('Hold',1)->where('Store',$admin->store)->get();
            }else{

                $HoldSales=SalesOrder::where('Delete',0)->where('Edit',0)->where('ToSales',0)->where('Hold',1)->get();
            }

            $Array=array();
            foreach($HoldSales as $sal){

                if($lang == 'ar'){

                    $cliName=$sal->Client()->first()->Name;
                    $useName=$sal->User()->first()->name;
                }else{

                    $cliName=$sal->Client()->first()->NameEn;
                    $useName=$sal->User()->first()->nameEn;

                }

                array_push($Array,[
                    'bill_id'=>$sal->id,
                    'bill_code'=>$sal->Code,
                    'date'=>$sal->Date,
                    'client_name'=>$cliName,
                    'user_name'=>$useName,
                    'total_price'=>$sal->Total_Price,
                ]);
            }
;

            return  $this->returnData('data',$Array);

    }

    //FilterHoldBills
    public function FilterHoldBills(Request $request){

        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }

        $admin=Admin::where('token',$x)->first();
        $lang = $request->header('lang', '');

            $search=request('hold_bill_code');

            if($admin->pos_stores == 0){
                $HoldSales=SalesOrder::where('Delete',0)->where('Edit',0)->where('ToSales',0)->where('Hold',1)->where('Code',$search)->where('Store',$admin->store)->get();
            }else{

                $HoldSales=SalesOrder::where('Delete',0)->where('Edit',0)->where('ToSales',0)->where('Hold',1)->where('Code',$search)->get();
            }

            $Array=array();
            foreach($HoldSales as $sal){

                if($lang == 'ar'){

                    $cliName=$sal->Client()->first()->Name;
                    $useName=$sal->User()->first()->name;
                }else{

                    $cliName=$sal->Client()->first()->NameEn;
                    $useName=$sal->User()->first()->nameEn;

                }


                array_push($Array,[
                    'bill_code'=>$sal->Code,
                    'date'=>$sal->Date,
                    'client_name'=>$cliName,
                    'user_name'=>$useName,
                    'total_price'=>$sal->Total_Price,
                ]);
            }

        return  $this->returnData('data',$Array);

    }

    //HoldBillDetails
    public function HoldBillDetails(Request $request){

            $id = $request->get('bill_id');
        $item=SalesOrder::findOrFail($id);
        $data=SalesOrderResources::make($item);
        return $this->returnData('data',$data);


    }

//DeleteHoldBill
    public function DeleteHoldBill(Request $request,SalesService $service){

        try {
            DB::beginTransaction();

            $header = $request->header('Authorization', '');
            if (Str::startsWith($header, 'Bearer ')) {
                $x=Str::substr($header, 7);
            }
            $admin=Admin::where('token',$x)->first();



            $id=request('bill_id');
            $del=SalesOrder::find($id);

            SalesOrder::where('id',$id)->update(['Delete'=>1]);
            Event::where('Type_Code',$del->Code)->where('Type','امر البيع')->delete();
            Notifications::where('Type_Code',$del->Code)->where('Type','امر بيع')->delete();

            if($del->Hold_Qty == 1){


                $service->RemoveHoldQties($id);


            }


            $dataUser=[
                'id'=>$admin->id,
                'screen_ar'=>'امر بيع',
                'screen_en'=>'Sales Order',
                'explain_ar'=>$del->Code,
                'explain_en'=>$del->Code,
            ];
            $this->UserDeleteMoves($dataUser);

            DB::commit();


            return $this->returnSuccessMessage(trans('admin.Deleted'));

        }catch(\Exception $ex){

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch(\Error $ex){

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }




    }


//AddHoldBill
    public function AddHoldBill(Request $request,SalesService $service){

        try {
            DB::beginTransaction();

            $rules = [
                'Date'=>'required',
                'Store'=>'required',
                'Safe'=>'required',
                'Coin'=>'required',
                'Draw'=>'required',
                'Payment_Method'=>'required',
                'Status'=>'required',
                'Client'=>'required',
            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $code = $this->returnCodeAccordingToInput($validator);
                return $this->returnValidationError($code, $validator);
            }

            $header = $request->header('Authorization', '');
            if (Str::startsWith($header, 'Bearer ')) {
                $x=Str::substr($header, 7);
            }
            $admin=Admin::where('token',$x)->first();


            $Sale_Type='POS';

            $ID=$service->CreateNewSalesOrderApi($request->all(),$Sale_Type,$admin->id);

            //Event New Bill
            $result=SalesOrderEvent::dispatch($request->all(),$ID,$Sale_Type);


            if($result[0] == 5){
                DB::rollBack();
                return  $this->returnSuccessMessage(trans('admin.Not_Enough_Qty'));
            }


            $dataUser=[
                'id'=>$admin->id,
                'screen_ar'=>'امر بيع',
                'screen_en'=>'Sales Order',
                'explain_ar'=>request('Code'),
                'explain_en'=>request('Code'),
            ];
            $this->UserCreateMoves($dataUser);


            DB::commit();

            return $this->returnSuccessMessage(trans('admin.Added_Successfully'));

        }catch(\Exception $ex){

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch(\Error $ex){

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }




    }


    public function HoldPostPOS(Request $request,SalesService $service){


        try {
            DB::beginTransaction();

            $id=request('bill_id');

            $header = $request->header('Authorization', '');
            if (Str::startsWith($header, 'Bearer ')) {
                $x=Str::substr($header, 7);
            }
            $admin=Admin::where('token',$x)->first();



            if(request('Hold') == 0){


                $rules = [
                    'Date'=>'required',
                    'Store'=>'required',
                    'Safe'=>'required',
                    'Coin'=>'required',
                    'Draw'=>'required',
                    'Payment_Method'=>'required',
                    'Status'=>'required',
                    'Client'=>'required',
                ];

                $validator = Validator::make($request->all(), $rules);

                if ($validator->fails()) {
                    $code = $this->returnCodeAccordingToInput($validator);
                    return $this->returnValidationError($code, $validator);
                }

                $header = $request->header('Authorization', '');
                if (Str::startsWith($header, 'Bearer ')) {
                    $x=Str::substr($header, 7);
                }
                $admin=Admin::where('token',$x)->first();


                $del=SalesOrder::find($id);
                SalesOrder::where('id',$id)->update(['ToSales'=>1]);
                Event::where('Type_Code',$del->Code)->where('Type','امر البيع')->delete();
                Notifications::where('Type_Code',$del->Code)->where('Type','امر بيع')->delete();

                if($del->Hold_Qty == 1){
                    $result=$service->RemoveHoldQties($id);

                    if ($result == 5){
                        DB::rollBack();
                        return  $this->returnSuccessMessage(trans('admin.Not_Enough_Qty'));

                    }
                }

                $Sale_Type='Sales';

                //Service Create New Bill
                $ID=$service->CreateNewSalesBillApi($request->all(),$Sale_Type,$admin->id);



                //Event New Bill

                $result=SalesEventApi::dispatch($request->all(),$ID,$Sale_Type,$admin->id);


                if($result[0] == 5){
                    DB::rollBack();
                    return  $this->returnSuccessMessage(trans('admin.Not_Enough_Qty'));
                }




                $dataUser=[
                    'id'=>$admin->id,
                    'screen_ar'=>'المبيعات',
                    'screen_en'=>'Sales',
                    'explain_ar'=>request('Code'),
                    'explain_en'=>request('Code'),
                ];
                $this->UserCreateMoves($dataUser);

                DB::commit();

                return $this->returnSuccessMessage(trans('admin.Transfered'));

            }else{


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

                $NEWCODE=$this->ReturnCode(SalesOrder::class);

                SalesOrder::where('id',$id)->update(['Edit'=>1,'Edit_New_Code'=>$NEWCODE]);
                Event::where('Type_Code',$del->Code)->where('Type','امر البيع')->delete();
                Notifications::where('Type_Code',$del->Code)->where('Type','امر بيع')->delete();

                if($del->Hold_Qty == 1){


                    $service->RemoveHoldQties($id);


                }

                $Sale_Type='POS';

                $ID=$service->CreateNewSalesOrderApi($request->all(),$Sale_Type,$admin->id);

                //Event New Bill
                $result=SalesOrderEvent::dispatch($request->all(),$ID,$Sale_Type);


                if($result[0] == 5){
                    DB::rollBack();
                    return  $this->returnSuccessMessage(trans('admin.Not_Enough_Qty'));
                }


                $dataUser=[
                    'id'=>$admin->id,
                    'screen_ar'=>'امر بيع',
                    'screen_en'=>'Sales Order',
                    'explain_ar'=>request('Code'),
                    'explain_en'=>request('Code'),
                ];
                $this->UserCreateMoves($dataUser);


                DB::commit();

                return $this->returnSuccessMessage(trans('admin.Updated'));



            }



        }catch(\Exception $ex){

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch(\Error $ex){

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }





    }



//========================= End Sales  ==============================


//MyItinerary
    public function MyItinerary(Request $request){

        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }
        $admin=Admin::where('token',$x)->first();
        $items=Itinerary::where('Emp',$admin->emp)->where('Day',request('day'))->orderBy('Time','asc')->get();
        $data=ItineraryResources::collection($items);
        return $this->returnData('data', $data);
    }

    public function AcceptVisitItinerary(Request $request,SalesService $service){
        try {

            DB::beginTransaction();

            $header = $request->header('Authorization', '');
            if (Str::startsWith($header, 'Bearer ')) {
                $x=Str::substr($header, 7);
            }

            $admin=Admin::where('token',$x)->first();

            $Def=SalesDefaultData::orderBy('id','desc')->first();

            $data['Emp']=$admin->emp;
            $data['Day']=date('D');
            $data['Date']=date('Y-m-d');
            $data['Time']=now();
            $data['Status']=1;
            $data['Client']=request('Client');
            $data['Note']=null;
            ItineraryVisit::create($data);

            DB::commit();


$def=SalesDefaultData::latest('id')->first();
            $item = \App\Models\Customers::where('Account',request('Client'))->first();
            if($def->Location_Conditon == 1){

                $lat=request('lat');
$lng=request('lng');

                $open=$service->LocationCondition($item->id,$lat,$lng);

            }else{

                $open=1;
            }




            $data=CustomersResources::make($item);
            return $this->returnDataLocation('data', $data,trans('admin.Added_Successfully'),$open);

        } catch (\Exception $ex) {

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch (\Error $ex) {
            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());
        }





    }

    public function NegativeVisitItinerary(Request $request){
        try {

            DB::beginTransaction();

            $header = $request->header('Authorization', '');
            if (Str::startsWith($header, 'Bearer ')) {
                $x=Str::substr($header, 7);
            }

            $admin=Admin::where('token',$x)->first();

            $Def=SalesDefaultData::orderBy('id','desc')->first();

            $data['Emp']=$admin->emp;
            $data['Day']=date('D');
            $data['Date']=date('Y-m-d');
            $data['Time']=now();
            $data['Status']=2;
            $data['Client']=request('Client');
            $data['Note']=request('Note');
            ItineraryVisit::create($data);

            DB::commit();

        return $this->returnSuccessMessage(trans('admin.Added_Successfully'));

        } catch (\Exception $ex) {

            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());

        }catch (\Error $ex) {
            DB::rollback();
            return $this->returnError($ex->getMessage().' '.$ex->getLine());
        }





    }


//MyItineraryClients
    public function MyItineraryClients(Request $request){

        $header = $request->header('Authorization', '');
        if (Str::startsWith($header, 'Bearer ')) {
            $x=Str::substr($header, 7);
        }

        $admin=Admin::where('token',$x)->first();
        if(date('D') != 'Thr'){

            $Day=date('D');
        }else{

            $Day='Thu';
        }
        $items=Itinerary::where('Emp',$admin->emp)->where('Day',$Day)->get();
        $data=ItineraryClientResources::collection($items);
        return $this->returnData('data', $data);
    }







    //========================  End Delegate App =================================






//if Paginated=======
//$x=[
//'status'=>200,
//'msg'=>trans('admin.Success'),
//];
//
//return $data->additional($x) ;


}
