<?php

namespace App\Http\Controllers;

use App\Models\ProductsQty;
use App\Models\ProductUnits;
use Illuminate\Http\Request;
use App\Models\AcccountingManual;
use App\Models\UsersMoves;
use App\Models\CostCenter;
use App\Models\Coins;
use App\Models\GeneralDaily;
use App\Models\Admin;
use App\Models\Journalizing;
use App\Models\JournalizingDetails;
use App\Models\PaymentVoucher;
use App\Models\PaymentVoucherDetails;
use App\Models\ReciptVoucher;
use App\Models\ReciptVoucherDetails;
use App\Models\OpeningEntries;
use App\Models\OpeningEntriesDetails;
use App\Models\ChecksTypes;
use App\Models\ExportChecks;
use App\Models\IncomChecks;
use App\Models\InsurancePaper;
use App\Models\StartPeriods;
use App\Models\Inventory;
use App\Models\SafeTransfers;
use App\Models\StorsTransfers;
use App\Models\Purchases;
use App\Models\Sales;
use App\Models\ReturnSales;
use App\Models\ReciptMaintaince;
use App\Models\ReturnMaintainceBill;
use App\Models\SalesSubscribes;
use App\Models\Employess;
use App\Events\AssetsMonthlyEvent;

use App\Services\Average;
use App\Models\Assets;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use DB ;
use DateTime;
use function GuzzleHttp\json_decode;
use function GuzzleHttp\json_encode;

class AccountReportsController extends Controller
{

function __construct()
{

$this->middleware('permission:اليوميه العامه', ['only' => ['General_DailyPage']]);
$this->middleware('permission:ميزان المراجعه', ['only' => ['Trial_BalancePage']]);
$this->middleware('permission:دفتر الاستاذ', ['only' => ['LedgerPage']]);
$this->middleware('permission:ارصده الحسابات', ['only' => ['Account_BalancesPage']]);
$this->middleware('permission:كشف حساب خزنه، بنك', ['only' => ['Safe_Bank_StatementPage']]);
$this->middleware('permission:تقارير الشيكات', ['only' => ['Checks_ReportsPage']]);
$this->middleware('permission:كشف حساب موردين', ['only' => ['Vendor_Account_StatementPage']]);
$this->middleware('permission:كشف حساب عملاء', ['only' => ['Customer_Account_StatementPage']]);
$this->middleware('permission:ارصده العملاء', ['only' => ['Customer_BalancesPage']]);
$this->middleware('permission:تقارير مركز التكلفه', ['only' => ['Cost_Centers_ReportPage']]);
$this->middleware('permission:قائمه الدخل', ['only' => ['Incom_ListPage']]);
$this->middleware('permission:قائمه المركز المالي', ['only' => ['Financial_CenterPage']]);
$this->middleware('permission:ارصده الخزائن و البنوك', ['only' => ['Safes_BalancesPage']]);
$this->middleware('permission:تقرير وصلات الامانه', ['only' => ['InsurancePaperReport']]);
$this->middleware('permission:ارصده الخزائن و البنوك', ['only' => ['Safes_BalancesPage']]);
$this->middleware('permission:تقرير الاصول الثابته', ['only' => ['Fixed_Assets_Report']]);
$this->middleware('permission:تقرير اعمار ديون العملاء', ['only' => ['CustomerDebtRestructuring']]);
$this->middleware('permission:تقرير اعمار ديون الموردين', ['only' => ['VendorDebtRestructuring']]);
$this->middleware('permission:ارصدة الموردين', ['only' => ['VendorsBalancesReport']]);

}


    //General_Daily
      public function General_DailyPage(){
        $items=GeneralDaily::paginate(50);
        $Numbers=GeneralDaily::all()->count();
        $TotalD=GeneralDaily::all()->sum('Debitor');
        $TotalC=GeneralDaily::all()->sum('Creditor');
    $Types=GeneralDaily::select('Type','TypeEn')->distinct(['Type'])->get();
         return view('admin.AccountsReports.General_Daily',get_defined_vars());
    }

     function GenralDailyFilterBond(Request $request)
             {

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

    if($Code != '' and $Type != '')
    {


           $data =Journalizing::
            where('Code',$Code)
           ->where('Type',$Type)
          ->first();


                $details=JournalizingDetails::where('Joun_ID',$data->id)->get();
                $count=JournalizingDetails::where('Joun_ID',$data->id)->get()->count();


     }

      if(!empty($data))
      {

 if(!empty($data->Cost_Center))    {

                    if(app()->getLocale() == 'ar' ){
                      $x=$data->Cost_Center()->first()->Arabic_Name;

                   }else{
                         $x=$data->Cost_Center()->first()->English_Name;

                   }

           }else{

                 $x='';
             }


                  if(app()->getLocale() == 'ar' ){
                      $xCoin=$data->Coin()->first()->Arabic_Name;

                   }else{
                         $xCoin=$data->Coin()->first()->English_Name;

                   }


        $output .= '

                             <div class="col-md-3">'.trans('admin.Date').'</div>
                                            <div class="col-md-3">'.$data->Date.'</div>
                                            <div class="col-md-3">'.trans('admin.Code').'</div>
                                            <div class="col-md-3">'.$data->Code.'</div>
                                             <div class="col-md-3">'.trans('admin.Coin').'</div>
                                            <div class="col-md-3">'.$xCoin.'</div>
                                             <div class="col-md-3">'.trans('admin.Draw').'</div>
                                            <div class="col-md-3">'.$data->Draw.'</div>
                                             <div class="col-md-3"> '.trans('admin.Cost_Center').'</div>
                                            <div class="col-md-3">'.$x.'</div>


                     <table id="" class="table table-bordered table-hover table-striped w-100">
                            <thead>
                                <tr>
                                    <th>'.trans('admin.Debitor').' </th>
                                    <th>'.trans('admin.Creditor').' </th>
                                    <th> '.trans('admin.Account_Code').' </th>
                                    <th> '.trans('admin.Account_Name').' </th>
                                    <th>'.trans('admin.Statement').' </th>

                                </tr>
                            </thead>
                            <tbody>
                       ';

          foreach($details as $ded){
                    if(app()->getLocale() == 'ar' ){
                      $xAccount=$ded->Account()->first()->Name;

                   }else{
                         $xAccount=$ded->Account()->first()->NameEn;

                   }
              $output .= '
                                <tr>
                                    <td>'.$ded->Debitor.'</td>
                                    <td>'.$ded->Creditor.'</td>
                                    <td>'.$ded->Account()->first()->Code.'</td>
                                    <td>'.$xAccount.'</td>
                                    <td>'.$ded->Statement.'</td>
                                </tr>
                    ';
          }

          $output .= '

                            </tbody>
                        </table>
                        <table class="table table-bordered table-hover table-striped w-100 mt-4">
                            <tbody>
                                <tr>
                                    <td>'.trans('admin.Num').'</td>
                                    <td>'.$count.'</td>
                                    <td> '.trans('admin.Total_Debitor').'</td>
                                    <td>'.$data->Total_Debaitor.'</td>
                                    <td> '.trans('admin.Total_Creditor').'</td>
                                    <td>'.$data->Total_Creditor.'</td>
                                </tr>
                            </tbody>
                        </table>


        ';


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

    public function GeneralDailyFilterTwo(Request $request){

       $from = $request->get('From');
      $to = $request->get('To');
      $coin = $request->get('Coin');
      $account = $request->get('Account');
      $type = $request->get('Type');
      $cost = $request->get('Cost_Center');
      $user = $request->get('User');

           $items=GeneralDaily::paginate(50);

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

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

                })

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

                })


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

                })


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

                })

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

                })


          ->paginate(50);

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

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

                })

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

                })


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

                })


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

                })

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

                })


          ->count();


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

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

                })

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

                })


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

                })


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

                })

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

                })


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


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

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

                })

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

                })


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

                })


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

                })

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

                })


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


                $ProdsCount=0;

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

             $from = $request->get('From');
      $to = $request->get('To');
      $coin = $request->get('Coin');
      $account = $request->get('Account');
      $type = $request->get('Type');
      $cost = $request->get('Cost_Center');
      $user = $request->get('User');


             foreach($items as $row)
       {
             if(!empty($row->Cost_Center))    {


                   if(app()->getLocale() == 'ar' ){
                      $x=$row->Cost_Center()->first()->Arabic_Name;

                   }else{
                         $x=$row->Cost_Center()->first()->English_Name;

                   }


           }else{

                 $x='';
             }


                           if(app()->getLocale() == 'ar' ){
                      $ACCOUNT=$row->Account()->first()->Name;
                      $COOIN=$row->Coin()->first()->Arabic_Name;
                      $USSER=$row->userr()->first()->name;
                      $TYPEE=$row->Type;

                   }else{
                     $ACCOUNT=$row->Account()->first()->NameEn;
                      $COOIN=$row->Coin()->first()->English_Name;
                      $USSER=$row->userr()->first()->nameEn;
                              $TYPEE=$row->TypeEn;

                   }


        $output .= '
                                            <tr>
                                                    <td>'.$row->Date.'</td>
                                                    <td>'.$row->Code.'</td>
                                                    <td>'.$row->Code_Type.'</td>
                                                    <td>'.$TYPEE.'</td>
                                                    <td>'.$row->Debitor.'</td>
                                                    <td>'.$row->Creditor.'</td>
                                                    <td>'.$row->Statement.'</td>
                                                    <td>'.$row->Account()->first()->Code.'</td>
                                                    <td>'.$ACCOUNT.'</td>
                                                    <td>
                                                        '.$x.'
                                                    </td>
                                                    <td>
                                                   '.$COOIN.'
                                                    </td>
                                                       <td>'.$row->Draw.'</td>
                                                       <td>'.$row->Debitor_Coin.'</td>
                                                       <td>'.$row->Creditor_Coin.'</td>
                                                       <td>
                                    '.$USSER.'

                                                       </td>
                                                </tr>

        ';

       }




return   $output ;
          }

         return view('admin.AccountsReports.GeneralDailyFilterTwo',[
             'items'=>$items,
             'Numbers'=>$Numbers,
             'TotalD'=>$TotalD,
             'TotalC'=>$TotalC,
             'from'=>$from,
             'to'=>$to,
             'coin'=>$coin,
             'account'=>$account,
             'type'=>$type,
             'cost'=>$cost,
             'user'=>$user,

         ]);
    }



    //Trial_Balance

      public function Trial_BalancePage(){

         return view('admin.AccountsReports.Trial_Balance');
    }

        public function TrialBalanceFilterTwo(Request $request){

              $from = $request->get('From');
      $to = $request->get('To');
      $type = $request->get('Type');
      $zero = $request->get('Zero');

        $Accounts=AcccountingManual::orderBy('Code','asc')->where('Type',$type)
           ->paginate(50);



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

             $from = $request->get('From');
      $to = $request->get('To');
      $type = $request->get('Type');
      $zero = $request->get('Zero');
$DBBEFORE=0;
$CRBEFORE=0;
$DBTOTAL=0;
$CRTOTAL=0;
$DBBALANCE=0;
$CRBALANCE=0;
$SubDebBef=0;
$SubCredBef=0;
$SubTotalDeb=0;
$SubTotalCred=0;
     if($type == 1){
       foreach($Accounts as $row)
       {

           $apear=0;
           $DebBef =GeneralDaily::where('Account',$row->id)
            ->where('Date','<',$from)
          ->get()->sum('Debitor_Coin');


            $CredBef =GeneralDaily::where('Account',$row->id)
            ->where('Date','<',$from)
          ->get()->sum('Creditor_Coin');

               $TotalDeb =GeneralDaily::where('Account',$row->id)
          ->whereBetween('Date', [$from, $to])
          ->get()->sum('Debitor_Coin');


               $TotalCred =GeneralDaily::where('Account',$row->id)
          ->whereBetween('Date', [$from, $to])
          ->get()->sum('Creditor_Coin');


           $x=( $DebBef + $TotalDeb ) - ( $CredBef + $TotalCred ) ;


                      if($x < 0){

               $y=0;
               $z=abs($x);
           }else{

               $y=$x;
               $z=0;

           }

$DBBEFORE +=$DebBef;
$CRBEFORE +=$CredBef;
$DBTOTAL +=$TotalDeb;
$CRTOTAL +=$TotalCred;
$DBBALANCE +=$y;
$CRBALANCE +=$z;

    if($zero == 1) {
        if($DebBef == 0  and $CredBef == 0 and $TotalDeb == 0  and $TotalCred == 0 and $y == 0  and $z == 0 ){
        $apear=1;
        }
    }


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

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

                   }


        if($apear == 0){

        $output .= '
        <tr>
                                             <td>'.$row->Code.'</td>
                                                   <td> '.$xName.'</td>
                                                    <td><input type="hidden" class="DBBEFORE" value="'.$DebBef.'"> '.number_format((float)$DebBef, 2, '.', '').'</td>
                                                    <td><input type="hidden" class="CRBEFORE" value="'.$CredBef.'">'.number_format((float)$CredBef, 2, '.', '').'</td>
                                                    <td><input type="hidden" class="DBTOTAL" value="'.$TotalDeb.'">'.number_format((float)$TotalDeb, 2, '.', '').'</td>
                                                    <td><input type="hidden" class="CRTOTAL" value="'.$TotalCred.'">'.number_format((float)$TotalCred, 2, '.', '').'</td>
                                                    <td><input type="hidden" class="DBBALANCE" value="'.$y.'">'.number_format((float)$y, 2, '.', '').'</td>
                                                    <td><input type="hidden" class="CRBALANCE" value="'.$z.'">'.number_format((float)$z, 2, '.', '').'</td>
                                                </tr>

        ';


       }

       }


        }else{

         foreach($Accounts as $row){

$SubDebBef=0;
$SubCredBef=0;
$SubTotalDeb=0;
$SubTotalCred=0;
$suby=0;
$subz=0;
             $count=AcccountingManual::where('Parent',$row->id)->where('Type',1)->count();

          if($count != 0){

             $ASubs=AcccountingManual::where('Parent',$row->id)->where('Type',1)->get();


              foreach($ASubs as $a){

                    $SubDebBef +=GeneralDaily::where('Account',$a->id)
            ->where('Date','<',$from)
          ->get()->sum('Debitor_Coin');


            $SubCredBef +=GeneralDaily::where('Account',$a->id)
            ->where('Date','<',$from)
          ->get()->sum('Creditor_Coin');

               $SubTotalDeb +=GeneralDaily::where('Account',$a->id)
          ->whereBetween('Date', [$from, $to])
          ->get()->sum('Debitor_Coin');


               $SubTotalCred +=GeneralDaily::where('Account',$a->id)
          ->whereBetween('Date', [$from, $to])
          ->get()->sum('Creditor_Coin');

              }

            $x=( $SubDebBef + $SubTotalDeb ) - ( $SubCredBef + $SubTotalCred ) ;


                      if($x < 0){

               $suby =0;
               $subz =abs($x);
           }else{

               $suby =$x;
               $subz =0;

           }

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

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

                   }

$DBBEFORE +=$SubDebBef;
$CRBEFORE +=$SubCredBef;
$DBTOTAL +=$SubTotalDeb;
$CRTOTAL +=$SubTotalCred;
$DBBALANCE +=$suby;
$CRBALANCE +=$subz;

              $output .= '
                                       <tr>
                                             <td>'.$row->Code.'</td>
                                               <td> '.$xName.'</td>
                                                      <td><input type="hidden" class="DBBEFORE" value="'.$SubDebBef.'"> '.number_format((float)$SubDebBef, 2, '.', '').'</td>
                                                    <td><input type="hidden" class="CRBEFORE" value="'.$SubCredBef.'">'.number_format((float)$SubCredBef, 2, '.', '').'</td>
                                                    <td><input type="hidden" class="DBTOTAL" value="'.$SubTotalDeb.'">'.number_format((float)$SubTotalDeb, 2, '.', '').'</td>
                                                    <td><input type="hidden" class="CRTOTAL" value="'.$SubTotalCred.'">'.number_format((float)$SubTotalCred, 2, '.', '').'</td>
                                                    <td><input type="hidden" class="DBBALANCE" value="'.$suby.'">'.number_format((float)$suby, 2, '.', '').'</td>
                                                    <td><input type="hidden" class="CRBALANCE" value="'.$subz.'">'.number_format((float)$subz, 2, '.', '').'</td>
                                                </tr>

        ';



         }

         }


        }

              return   $output ;
          }
         return view('admin.AccountsReports.TrialBalanceFilterTwo',get_defined_vars());
    }

        //Account_Balances

      public function Account_BalancesPage(){

         return view('admin.AccountsReports.Account_Balances');
    }

      public function AccountBalancesFilterTwo(Request $request){

              $from = $request->get('From');
      $to = $request->get('To');
      $type = $request->get('Type');
      $zero = $request->get('Zero');

   $A=AcccountingManual::where('id',$type)->first();

        if($A->Parent == 0){

          $words=$A->Code.'0';

        }else{

           $words=$A->Code;

        }

 $Accounts = AcccountingManual::where('Code', 'like', $words.'%')
    ->where('Type', 1)
    ->paginate(100);

 $FilterAccounts = AcccountingManual::where('Code', 'like', $words.'%')
    ->where('Type', 1)
    ->get('id');



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

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

              })


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

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

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

              })


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


          $totalAllD=GeneralDaily::

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

              })


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

          $totalAllC=GeneralDaily::

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

              })


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



          $Credit=$totalD - $totalC;
          $CreditAll=$totalAllD - $totalAllC;







          $output = '';
          if($request->ajax())
     {
              $from = $request->get('From');
      $to = $request->get('To');
      $type = $request->get('Type');
      $zero = $request->get('Zero');
$DBBEFORE=0;
$CRBEFORE=0;
$DBTOTAL=0;
$CRTOTAL=0;
$DBBALANCE=0;
$CRBALANCE=0;



           foreach($Accounts as $row)
       {
           $apear=0;
           $DebBef =GeneralDaily::where('Account',$row->id)
            ->where('Date','<',$from)
          ->get()->sum('Debitor_Coin');


            $CredBef =GeneralDaily::where('Account',$row->id)
            ->where('Date','<',$from)
          ->get()->sum('Creditor_Coin');

               $TotalDeb =GeneralDaily::where('Account',$row->id)
          ->whereBetween('Date', [$from, $to])
          ->get()->sum('Debitor_Coin');


               $TotalCred =GeneralDaily::where('Account',$row->id)
          ->whereBetween('Date', [$from, $to])
          ->get()->sum('Creditor_Coin');


           $x=( $DebBef + $TotalDeb ) - ( $CredBef + $TotalCred ) ;


                      if($x < 0){

               $y=0;
               $z=abs($x);
           }else{

               $y=$x;
               $z=0;

           }

$DBBEFORE +=$DebBef;
$CRBEFORE +=$CredBef;
$DBTOTAL +=$TotalDeb;
$CRTOTAL +=$TotalCred;
$DBBALANCE +=$y;
$CRBALANCE +=$z;



    if($zero == 1) {
        if($DebBef == 0  and $CredBef == 0 and $TotalDeb == 0  and $TotalCred == 0 and $y == 0  and $z == 0 ){
        $apear=1;
        }
    }




        if($apear == 0){

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

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

                   }


        $output .= '
        <tr>
                                             <td>'.$row->Code.'</td>
                                                 <td> '.$xName.'</td>
                                                    <td><input type="hidden" class="DBBEFORE" value="'.$DebBef.'">'.$DebBef.'</td>
                                                    <td><input type="hidden" class="CRBEFORE" value="'.$CredBef.'">'.$CredBef.'</td>
                                                    <td><input type="hidden" class="DBTOTAL" value="'.$TotalDeb.'">'.$TotalDeb.'</td>
                                                    <td><input type="hidden" class="CRTOTAL" value="'.$TotalCred.'">'.$TotalCred.'</td>
                                                    <td><input type="hidden" class="DBBALANCE" value="'.$y.'">'.$y.'</td>
                                                    <td><input type="hidden" class="CRBALANCE" value="'.$z.'">'.$z.'</td>
                                                </tr>

        ';


       }

            $last_id = $row->id;
       }


    return   $output ;
          }

         return view('admin.AccountsReports.AccountBalancesFilterTwo',get_defined_vars());
    }



    //Ledger

     public function LedgerPage(){

             $Types=GeneralDaily::select('Type','TypeEn')->distinct(['Type'])->get();
         return view('admin.AccountsReports.Ledger',['Types'=>$Types]);
    }

      public function FilterPrintLedger(Request $request){

     $from = $request->get('from');
      $to = $request->get('to');
      $coin = $request->get('coin');
      $account = $request->get('account');
      $type = $request->get('type');
      $cost = $request->get('cost');
      $user = $request->get('user');
      $n=0;
      $p=0;


        if($from != '' and $account != null and $to != ''){




        if($coin != null and $type != '' and $cost != null and $user != null){



                                      $data =GeneralDaily::orderBy('id','asc')
              ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
                  ->where('Type', $type)
      ->where('Coin', $coin)
            ->where('Cost_Center', $cost)
            ->where('userr', $user)
          ->get();


          $totalD=GeneralDaily::orderBy('id','asc')
            ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
                  ->where('Type', $type)
      ->where('Coin', $coin)
            ->where('Cost_Center', $cost)
            ->where('userr', $user)
          ->get()->sum('Debitor_Coin');

             $totalC=GeneralDaily::orderBy('id','asc')
                 ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
                  ->where('Type', $type)
      ->where('Coin', $coin)
            ->where('Cost_Center', $cost)
            ->where('userr', $user)
          ->get()->sum('Creditor_Coin');

             $totalN=GeneralDaily::orderBy('id','asc')
           ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
                  ->where('Type', $type)
      ->where('Coin', $coin)
            ->where('Cost_Center', $cost)
            ->where('userr', $user)
          ->get()->count();


        }elseif($coin != null and $type == '' and $cost == null and $user == null){

                          $data =GeneralDaily::orderBy('id','asc')
              ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
 ->where('Coin', $coin)
          ->get();


          $totalD=GeneralDaily::orderBy('id','asc')
            ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
 ->where('Coin', $coin)
          ->get()->sum('Debitor_Coin');

             $totalC=GeneralDaily::orderBy('id','asc')
                 ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
 ->where('Coin', $coin)
          ->get()->sum('Creditor_Coin');

             $totalN=GeneralDaily::orderBy('id','asc')
           ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
  ->where('Coin', $coin)
          ->get()->count();

        }elseif($coin == null and $type != '' and $cost == null and $user == null){

                         $data =GeneralDaily::orderBy('id','asc')
              ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
    ->where('Type', $type)
          ->get();


          $totalD=GeneralDaily::orderBy('id','asc')
            ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
   ->where('Type', $type)
          ->get()->sum('Debitor_Coin');

             $totalC=GeneralDaily::orderBy('id','asc')
                 ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
   ->where('Type', $type)
          ->get()->sum('Creditor_Coin');

             $totalN=GeneralDaily::orderBy('id','asc')
           ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
     ->where('Type', $type)
          ->get()->count();


        }elseif($coin == null and $type == '' and $cost != null and $user == null){

                      $data =GeneralDaily::orderBy('id','asc')
              ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
  ->where('Cost_Center', $cost)
          ->get();


          $totalD=GeneralDaily::orderBy('id','asc')
            ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
  ->where('Cost_Center', $cost)
          ->get()->sum('Debitor_Coin');

             $totalC=GeneralDaily::orderBy('id','asc')
                 ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
     ->where('Cost_Center', $cost)
          ->get()->sum('Creditor_Coin');

             $totalN=GeneralDaily::orderBy('id','asc')
           ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
       ->where('Cost_Center', $cost)
          ->get()->count();


        }elseif($coin == null and $type == '' and $cost == null and $user != null){

                   $data =GeneralDaily::orderBy('id','asc')
              ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
     ->where('userr', $user)
          ->get();


          $totalD=GeneralDaily::orderBy('id','asc')
            ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
     ->where('userr', $user)
          ->get()->sum('Debitor_Coin');

             $totalC=GeneralDaily::orderBy('id','asc')
                 ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
     ->where('userr', $user)
          ->get()->sum('Creditor_Coin');

             $totalN=GeneralDaily::orderBy('id','asc')
           ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
      ->where('userr', $user)
          ->get()->count();


        }elseif($coin != null and $type != '' and $cost == null and $user == null){

                   $data =GeneralDaily::orderBy('id','asc')
              ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
->where('Coin', $coin)
       ->where('Type', $type)
          ->get();


          $totalD=GeneralDaily::orderBy('id','asc')
            ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
    ->where('Type', $type)
->where('Coin', $coin)
          ->get()->sum('Debitor_Coin');

             $totalC=GeneralDaily::orderBy('id','asc')
                 ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
->where('Coin', $coin)
       ->where('Type', $type)
          ->get()->sum('Creditor_Coin');

             $totalN=GeneralDaily::orderBy('id','asc')
           ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
      ->where('Type', $type)
->where('Coin', $coin)
          ->get()->count();



        }elseif($coin != null and $type == '' and $cost != null and $user == null){

                             $data =GeneralDaily::orderBy('id','asc')
              ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
->where('Coin', $coin)
     ->where('Cost_Center', $cost)
          ->get();


          $totalD=GeneralDaily::orderBy('id','asc')
            ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
     ->where('Cost_Center', $cost)
->where('Coin', $coin)
          ->get()->sum('Debitor_Coin');

             $totalC=GeneralDaily::orderBy('id','asc')
                 ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
->where('Coin', $coin)
     ->where('Cost_Center', $cost)
          ->get()->sum('Creditor_Coin');

             $totalN=GeneralDaily::orderBy('id','asc')
           ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
     ->where('Cost_Center', $cost)
->where('Coin', $coin)
          ->get()->count();


        }elseif($coin != null and $type == '' and $cost == null and $user != null){

                      $data =GeneralDaily::orderBy('id','asc')
              ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
->where('Coin', $coin)
 ->where('userr', $user)
          ->get();


          $totalD=GeneralDaily::orderBy('id','asc')
            ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
  ->where('userr', $user)
->where('Coin', $coin)
          ->get()->sum('Debitor_Coin');

             $totalC=GeneralDaily::orderBy('id','asc')
                 ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
->where('Coin', $coin)
 ->where('userr', $user)
          ->get()->sum('Creditor_Coin');

             $totalN=GeneralDaily::orderBy('id','asc')
           ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
 ->where('userr', $user)
->where('Coin', $coin)
          ->get()->count();

        }elseif($coin == null and $type != '' and $cost != null and $user == null){

                 $data =GeneralDaily::orderBy('id','asc')
              ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
    ->where('Cost_Center', $cost)
      ->where('Type', $type)
          ->get();


          $totalD=GeneralDaily::orderBy('id','asc')
            ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
    ->where('Cost_Center', $cost)
     ->where('Type', $type)
          ->get()->sum('Debitor_Coin');

             $totalC=GeneralDaily::orderBy('id','asc')
                 ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
    ->where('Cost_Center', $cost)
       ->where('Type', $type)
          ->get()->sum('Creditor_Coin');

             $totalN=GeneralDaily::orderBy('id','asc')
           ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
    ->where('Cost_Center', $cost)
       ->where('Type', $type)
          ->get()->count();


        }elseif($coin == null and $type != '' and $cost == null and $user != null){

               $data =GeneralDaily::orderBy('id','asc')
              ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)

  ->where('userr', $user)
      ->where('Type', $type)
          ->get();


          $totalD=GeneralDaily::orderBy('id','asc')
            ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)

      ->where('userr', $user)
     ->where('Type', $type)
          ->get()->sum('Debitor_Coin');

             $totalC=GeneralDaily::orderBy('id','asc')
                 ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)

    ->where('userr', $user)
       ->where('Type', $type)
          ->get()->sum('Creditor_Coin');

             $totalN=GeneralDaily::orderBy('id','asc')
           ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
    ->where('userr', $user)
       ->where('Type', $type)
          ->get()->count();

        }elseif($coin == null and $type == '' and $cost != null and $user != null){


                  $data =GeneralDaily::orderBy('id','asc')
              ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)

  ->where('userr', $user)
  ->where('Cost_Center', $cost)
          ->get();


          $totalD=GeneralDaily::orderBy('id','asc')
            ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)

      ->where('userr', $user)
  ->where('Cost_Center', $cost)
          ->get()->sum('Debitor_Coin');

             $totalC=GeneralDaily::orderBy('id','asc')
                 ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)

    ->where('userr', $user)
  ->where('Cost_Center', $cost)
          ->get()->sum('Creditor_Coin');

             $totalN=GeneralDaily::orderBy('id','asc')
           ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
    ->where('userr', $user)
  ->where('Cost_Center', $cost)
          ->get()->count();

        }elseif($coin != null and $type != '' and $cost != null and $user == null){

                  $data =GeneralDaily::orderBy('id','asc')
              ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
         ->where('Type', $type)
      ->where('Coin', $coin)
  ->where('Cost_Center', $cost)
          ->get();


          $totalD=GeneralDaily::orderBy('id','asc')
            ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
         ->where('Type', $type)
      ->where('Coin', $coin)
  ->where('Cost_Center', $cost)
          ->get()->sum('Debitor_Coin');

             $totalC=GeneralDaily::orderBy('id','asc')
                 ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
             ->where('Type', $type)
      ->where('Coin', $coin)
  ->where('Cost_Center', $cost)
          ->get()->sum('Creditor_Coin');

             $totalN=GeneralDaily::orderBy('id','asc')
           ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
         ->where('Type', $type)
      ->where('Coin', $coin)
  ->where('Cost_Center', $cost)
          ->get()->count();


        }elseif($coin != null and $type != '' and $cost == null and $user != null){

                 $data =GeneralDaily::orderBy('id','asc')
              ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
         ->where('Type', $type)
      ->where('Coin', $coin)
->where('userr', $user)
          ->get();


          $totalD=GeneralDaily::orderBy('id','asc')
            ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
         ->where('Type', $type)
      ->where('Coin', $coin)
->where('userr', $user)
          ->get()->sum('Debitor_Coin');

             $totalC=GeneralDaily::orderBy('id','asc')
                 ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
             ->where('Type', $type)
      ->where('Coin', $coin)
->where('userr', $user)
          ->get()->sum('Creditor_Coin');

             $totalN=GeneralDaily::orderBy('id','asc')
           ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
         ->where('Type', $type)
      ->where('Coin', $coin)
->where('userr', $user)
          ->get()->count();


        }elseif($coin == null and $type != '' and $cost != null and $user != null){

            $data =GeneralDaily::orderBy('id','asc')
              ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
         ->where('Type', $type)
->where('Cost_Center', $cost)
->where('userr', $user)
          ->get();


          $totalD=GeneralDaily::orderBy('id','asc')
            ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
         ->where('Type', $type)
->where('Cost_Center', $cost)
->where('userr', $user)
          ->get()->sum('Debitor_Coin');

             $totalC=GeneralDaily::orderBy('id','asc')
                 ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
             ->where('Type', $type)
->where('Cost_Center', $cost)
->where('userr', $user)
          ->get()->sum('Creditor_Coin');

             $totalN=GeneralDaily::orderBy('id','asc')
           ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
         ->where('Type', $type)
->where('Cost_Center', $cost)
->where('userr', $user)
          ->get()->count();

        }elseif($coin == null and $type == '' and $cost == null and $user == null){



        $data =GeneralDaily::orderBy('id','asc')
              ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
          ->get();


          $totalD=GeneralDaily::orderBy('id','asc')
            ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
          ->get()->sum('Debitor_Coin');

             $totalC=GeneralDaily::orderBy('id','asc')
                 ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
          ->get()->sum('Creditor_Coin');

             $totalN=GeneralDaily::orderBy('id','asc')
           ->whereBetween('Date', [$from, $to])
            ->where('Account', $account)
          ->get()->count();


        }





        }

                $Acc =AcccountingManual::where('id',$account)->first();


        $totalDAcc=GeneralDaily::where('Account', $Acc->id)
            ->where('Date','<',$from)
          ->get()->sum('Debitor_Coin');

             $totalCAcc=GeneralDaily::where('Account', $Acc->id)
            ->where('Date','<',$from)
          ->get()->sum('Creditor_Coin');

         return view('admin.AccountsReports.LedgerPrint',get_defined_vars());
    }


 public function LedgerFilterTwo(Request $request){

            $from = $request->get('from');
      $to = $request->get('to');
      $coin = $request->get('coin');
      $account = $request->get('account');
      $type = $request->get('type');
      $cost = $request->get('cost');
      $user = $request->get('user');


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

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

                })

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

                })


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

                })


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

                })

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

                })


          ->paginate(50);

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

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

                })

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

                })


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

                })


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

                })

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

                })


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

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

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

                })

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

                })


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

                })


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

                })

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

                })


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



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

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

                })

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

                })


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

                })


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

                })

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

                })


          ->count();


     $Credit=$totalD - $totalC;


      $output = '';
          if($request->ajax())
     {
             $from = $request->get('from');
      $to = $request->get('to');
      $coin = $request->get('coin');
      $account = $request->get('account');
      $type = $request->get('type');
      $cost = $request->get('cost');
      $user = $request->get('user');
     $n=0;
      $p=0;

       foreach($items as $row)
       {



           if($n == 0 and $p == 0){

               $n = $row->Creditor_Coin;
               $p =$row->Debitor_Coin;

           }else{


            if($row->Debitor_Coin == 0){

               if($n == 0){

                   $res=$p  -  $row->Creditor_Coin ;


                if($res < 0){

                  $n=abs($res);
                   $p=0;

                }else{

               $n=0;
                   $p=$res;

                }



               }elseif($p == 0){


                 $res=$n  +  $row->Creditor_Coin ;
                   $n=$res;
                   $p=0;

               }


            }elseif($row->Creditor_Coin == 0){


              if($n == 0){

                $res=$p  +  $row->Debitor_Coin ;

                  $n=0;
                  $p=$res;



               }elseif($p == 0){

                   $res=$n  -  $row->Debitor_Coin ;


                if($res < 0){

                  $n=0;
                   $p=abs($res);
                }else{

                    $n=$res;
                   $p=0;

                }


               }




            }



           }

             if(!empty($row->Cost_Center)){

                        if(app()->getLocale() == 'ar' ){
                      $x=$row->Cost_Center()->first()->Arabic_Name;

                   }else{
                         $x=$row->Cost_Center()->first()->English_Name;

                   }

           }else{

                 $x='';
             }

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

                      $COOIN=$row->Coin()->first()->Arabic_Name;
                      $USSER=$row->userr()->first()->name;
                              $TYPEE=$row->Type;
                   }else{

                      $COOIN=$row->Coin()->first()->English_Name;
                      $USSER=$row->userr()->first()->nameEn;
                              $TYPEE=$row->TypeEn;
                   }


        $output .= '
        <tr>

                                                    <td>'.$row->Date.'</td>
                                                    <td>'.$row->Code.'</td>
                                                    <td>'.$row->Code_Type.'</td>
                                                    <td>'.$TYPEE.'</td>
                                                      <td>'.$row->Statement.'</td>
                                                        <td>'.$row->Debitor_Coin.'</td>
                                                       <td>'.$row->Creditor_Coin.'</td>
                                                    <td>'.$p.'</td>
                                                    <td>'.$n.'</td>


                                             <td>
         '.$COOIN.'
                                            </td>
                                                    <td class="">

                                                    '.$x.'

                                                    </td>



                                                       <td class="">
                                           '.$USSER.'

                                                       </td>
                                                </tr>

        ';

       }



    return   $output ;
          }

         return view('admin.AccountsReports.LedgerFilterTwo',[

            'totalN'=>$totalN,
            'totalD'=>$totalD,
            'totalC'=>$totalC,
            'from'=>$from,
            'to'=>$to,
            'coin'=>$coin,
            'account'=>$account,
            'type'=>$type,
            'cost'=>$cost,
            'user'=>$user,
            'Credit'=>$Credit,
         ]);
    }

        //Safe_Bank_Statement

     public function Safe_Bank_StatementPage(){

            $Types=GeneralDaily::select('Type','TypeEn')->distinct(['Type'])->get();
         return view('admin.AccountsReports.Safe_Bank_Statement',get_defined_vars());
    }

       public function SafeBankStatementFilterTwo(Request $request){

              $from = $request->get('from');
      $to = $request->get('to');
      $coin = $request->get('coin');
      $account = $request->get('account');
      $type = $request->get('type');
      $cost = $request->get('cost');
      $user = $request->get('user');

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

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

                })

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

                })


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

                })


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

                })

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

                })


          ->paginate(50);

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

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

                })

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

                })


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

                })


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

                })

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

                })


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

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

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

                })

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

                })


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

                })


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

                })

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

                })


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

      $totalAllD =GeneralDaily::

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

                })


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

      $totalAllC =GeneralDaily::

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

                })





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



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

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

                })

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

                })


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

                })


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

                })

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

                })


          ->count();

                   $Credit=$totalD - $totalC;
                   $CreditAll=$totalAllD - $totalAllC;

      $output = '';
          if($request->ajax())
     {
      $from = $request->get('from');
      $to = $request->get('to');
      $coin = $request->get('coin');
      $account = $request->get('account');
      $type = $request->get('type');
      $cost = $request->get('cost');
      $user = $request->get('user');
     $n=0;
      $p=0;

       foreach($items as $row)
       {



           if($n == 0 and $p == 0){

               $n = $row->Creditor_Coin;
               $p =$row->Debitor_Coin;

           }else{


            if($row->Debitor_Coin == 0){

               if($n == 0){

                   $res=$p  -  $row->Creditor_Coin ;


                if($res < 0){

                  $n=abs($res);
                   $p=0;

                }else{

               $n=0;
                   $p=$res;

                }



               }elseif($p == 0){


                 $res=$n  +  $row->Creditor_Coin ;
                   $n=$res;
                   $p=0;

               }


            }elseif($row->Creditor_Coin == 0){


              if($n == 0){

                $res=$p  +  $row->Debitor_Coin ;

                  $n=0;
                  $p=$res;



               }elseif($p == 0){

                   $res=$n  -  $row->Debitor_Coin ;


                if($res < 0){

                  $n=0;
                   $p=abs($res);
                }else{

                    $n=$res;
                   $p=0;

                }


               }




            }



           }

             if(!empty($row->Cost_Center)){

                  if(app()->getLocale() == 'ar' ){
                      $x=$row->Cost_Center()->first()->Arabic_Name;

                   }else{
                         $x=$row->Cost_Center()->first()->English_Name;

                   }

           }else{

                 $x='';
             }

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

                      $COOIN=$row->Coin()->first()->Arabic_Name;
                      $USSER=$row->userr()->first()->name;
                       $TYPEE=$row->Type;
                   }else{

                      $COOIN=$row->Coin()->first()->English_Name;
                      $USSER=$row->userr()->first()->nameEn;
                           $TYPEE=$row->TypeEn;
                   }

        $output .= '
        <tr>

                                                    <td>'.$row->Date.'</td>
                                                    <td>'.$row->Code.'</td>
                                                    <td>'.$row->Code_Type.'</td>
                                                    <td>'.$TYPEE.'</td>
                                                      <td>'.$row->Statement.'</td>
                                                        <td>'.$row->Debitor_Coin.'</td>
                                                       <td>'.$row->Creditor_Coin.'</td>
                                                    <td>'.$p.'</td>
                                                    <td>'.$n.'</td>


                                             <td>
            '.$COOIN.'
                                            </td>
                                                    <td class="">

                                                    '.$x.'

                                                    </td>



                                                       <td class="">      '.$USSER.'    </td>
                                                </tr>

        ';

       }



    return   $output ;
          }

         return view('admin.AccountsReports.SafeBankStatementFilterTwo',get_defined_vars());
    }



            //Customer_Balances

      public function Customer_BalancesPage(){

         return view('admin.AccountsReports.Customer_Balances');
    }

   public function CustomerBalancesFilterTwo(Request $request){

      $from = $request->get('From');
      $to = $request->get('To');
      $zero = $request->get('Zero');


  $Accounts = AcccountingManual::where('Parent',24)
    ->where('Type', 1)
     ->orderBy('id', 'asc')
    ->paginate(100);

         $AccountsCount = AcccountingManual::where('Parent',24)
    ->where('Type', 1)
     ->orderBy('id', 'asc')
    ->count();

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

           ->whereRelation('Account','Parent',24)

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

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

           ->whereRelation('Account','Parent',24)

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

       $totalAllD=GeneralDaily::

           whereRelation('Account','Parent',24)

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

       $totalAllC=GeneralDaily::

       whereRelation('Account','Parent',24)


           ->get()->sum('Creditor_Coin');
       $Credit=$totalD - $totalC;
       $CreditAll=$totalAllD - $totalAllC;



       $output = '';
          if($request->ajax())
     {
$from = $request->get('From');
$to = $request->get('To');
$zero = $request->get('Zero');
$DBBEFORE=0;
$CRBEFORE=0;
$DBTOTAL=0;
$CRTOTAL=0;
$DBBALANCE=0;
$CRBALANCE=0;





         foreach($Accounts as $row)
       {
           $apear=0;
           $DebBef =GeneralDaily::where('Account',$row->id)
            ->where('Date','<',$from)
          ->get()->sum('Debitor_Coin');


            $CredBef =GeneralDaily::where('Account',$row->id)
            ->where('Date','<',$from)
          ->get()->sum('Creditor_Coin');

               $TotalDeb =GeneralDaily::where('Account',$row->id)
          ->whereBetween('Date', [$from, $to])
          ->get()->sum('Debitor_Coin');


               $TotalCred =GeneralDaily::where('Account',$row->id)
          ->whereBetween('Date', [$from, $to])
          ->get()->sum('Creditor_Coin');


           $x=( $DebBef + $TotalDeb ) - ( $CredBef + $TotalCred ) ;


                      if($x < 0){

               $y=0;
               $z=abs($x);
           }else{

               $y=$x;
               $z=0;

           }

$DBBEFORE +=$DebBef;
$CRBEFORE +=$CredBef;
$DBTOTAL +=$TotalDeb;
$CRTOTAL +=$TotalCred;
$DBBALANCE +=$y;
$CRBALANCE +=$z;



    if($zero == 1) {
        if($DebBef == 0  and $CredBef == 0 and $TotalDeb == 0  and $TotalCred == 0 and $y == 0  and $z == 0 ){
        $apear=1;
        }
    }

        if($apear == 0){

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

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

                   }

        $output .= '
        <tr>
                                             <td class="">'.$row->Code.'</td>
                                                       <td> '.$xName.'</td>
                                                     <td><input type="hidden" class="DBBEFORE" value="'.$DebBef.'"> '.$DebBef.'</td>
                                                    <td><input type="hidden" class="CRBEFORE" value="'.$CredBef.'">'.$CredBef.'</td>
                                                    <td><input type="hidden" class="DBTOTAL" value="'.$TotalDeb.'">'.$TotalDeb.'</td>
                                                    <td><input type="hidden" class="CRTOTAL" value="'.$TotalCred.'">'.$TotalCred.'</td>
                                                    <td><input type="hidden" class="DBBALANCE" value="'.$y.'">'.$y.'</td>
                                                    <td><input type="hidden" class="CRBALANCE" value="'.$z.'">'.$z.'</td>
                                                </tr>

        ';


       }

       }



    return   $output ;
          }

         return view('admin.AccountsReports.CustomerBalancesFilterTwo',get_defined_vars());
    }



            //Vendor_Account_Statement

     public function Vendor_Account_StatementPage(){
 $Types=GeneralDaily::select('Type','TypeEn')->distinct(['Type'])->get();

         return view('admin.AccountsReports.Vendor_Account_Statement',get_defined_vars());
    }

     public function VendorAccountStatementFilterTwo(Request $request){


             $from = $request->get('from');
      $to = $request->get('to');
      $coin = $request->get('coin');
      $account = $request->get('account');
      $type = $request->get('type');
      $cost = $request->get('cost');
      $user = $request->get('user');
      $n=0;
      $p=0;

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

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

                })

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

                })

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

                })

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

                })

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

                })

          ->paginate(100);


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

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

                })

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

                })

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

                })

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

                })

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

                })

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

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

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

                })

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

                })

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

                })

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

                })

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

                })

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


         $totalAllD=GeneralDaily::

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

         })

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

             })

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

             })

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

             })

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

             })

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

         $totalAllC=GeneralDaily::

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

         })

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

             })

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

             })

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

             })

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

             })

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

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

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

             })

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

             })

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

             })

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

             })

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

             })

             ->get()->count();


         $Credit=$totalD - $totalC;
         $CreditAll=$totalAllD - $totalAllC;


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


    foreach($data as $row)
       {



           if($n == 0 and $p == 0){

               $n = $row->Creditor_Coin;
               $p =$row->Debitor_Coin;

           }else{


            if($row->Debitor_Coin == 0){

               if($n == 0){

                   $res=$p  -  $row->Creditor_Coin ;


                if($res < 0){

                  $n=abs($res);
                   $p=0;

                }else{

               $n=0;
                   $p=$res;

                }



               }elseif($p == 0){


                 $res=$n  +  $row->Creditor_Coin ;
                   $n=$res;
                   $p=0;

               }


            }elseif($row->Creditor_Coin == 0){


              if($n == 0){

                $res=$p  +  $row->Debitor_Coin ;

                  $n=0;
                  $p=$res;



               }elseif($p == 0){

                   $res=$n  -  $row->Debitor_Coin ;


                if($res < 0){

                  $n=0;
                   $p=abs($res);
                }else{

                    $n=$res;
                   $p=0;

                }


               }




            }



           }

             if(!empty($row->Cost_Center)){

                if(app()->getLocale() == 'ar' ){
                      $x=$row->Cost_Center()->first()->Arabic_Name;

                   }else{
                         $x=$row->Cost_Center()->first()->English_Name;

                   }

           }else{

                 $x='';
             }


             if($row->Type == 'القيود اليومية'){

                $Journalizing=Journalizing::where('Code',$row->Code_Type)->orderBy('id','desc')->first();

                 $Action= '<a href='.url("JournalizingPrint/".$Journalizing->id."").'><i class="fal fa-print"></i></a>' ;
                 $code_bill='';
           }elseif($row->Type == 'سند قبض'){


                   $ReciptVoucher=ReciptVoucher::where('Code',$row->Code_Type)->orderBy('id','desc')->first();

                 $Action= '<a href='.url("Receipt_VoucherPrint/".$ReciptVoucher->id."").'><i class="fal fa-print"></i></a>' ;
                 $code_bill='';
             }elseif($row->Type == 'سند صرف'){


                      $PaymentVoucher=PaymentVoucher::where('Code',$row->Code_Type)->orderBy('id','desc')->first();

                 $Action= '<a href='.url("Payment_VoucherPrint/".$PaymentVoucher->id."").'><i class="fal fa-print"></i></a>' ;
                 $code_bill='';
             }elseif($row->Type == 'القيد الإفتتاحي'){

                      $OpeningEntries=OpeningEntries::where('Code',$row->Code_Type)->orderBy('id','desc')->first();

                 $Action= '<a href='.url("Opening_EntriesPrint/".$OpeningEntries->id."").'><i class="fal fa-print"></i></a>' ;
                 $code_bill='';
             }elseif($row->Type == 'الشيكات الصادرة'){

                     $ExportChecks=ExportChecks::where('Code',$row->Code_Type)->orderBy('id','desc')->first();

                 $Action= '<a href='.url("PrintOutcomChecks/".$ExportChecks->id."").'><i class="fal fa-print"></i></a>' ;
                 $code_bill='';
             }elseif($row->Type == 'الشيكات الواردة'){

                    $IncomChecks=IncomChecks::where('Code',$row->Code_Type)->orderBy('id','desc')->first();

                 $Action= '<a href='.url("PrintIncomChecks/".$IncomChecks->id."").'><i class="fal fa-print"></i></a>' ;
                 $code_bill='';
             }elseif($row->Type == 'اصناف بداية فترة'){

                     $StartPeriods=StartPeriods::where('Code',$row->Code_Type)->orderBy('id','desc')->first();

                 $Action= '<a href='.url("StartPeriodPrint/".$StartPeriods->id."").'><i class="fal fa-print"></i></a>' ;
                 $code_bill='';
             }elseif($row->Type == 'تسوية بالعجز'){


                   $Inventory=Inventory::where('Code',$row->Code_Type)->orderBy('id','desc')->first();
                 $Action= '<a href='.url("InventoryPrint/".$Inventory->id."").'><i class="fal fa-print"></i></a>' ;
                 $code_bill='';
             }elseif($row->Type == 'تسوية بالزيادة"'){


                   $Inventory=Inventory::where('Code',$row->Code_Type)->orderBy('id','desc')->first();
                 $Action= '<a href='.url("InventoryPrint/".$Inventory->id."").'><i class="fal fa-print"></i></a>' ;
                 $code_bill='';
             }elseif($row->Type == 'تحويلات الخزائن'){


                       $SafeTransfers=SafeTransfers::where('Code',$row->Code_Type)->orderBy('id','desc')->first();
                 $Action= '<a href='.url("TransSafePrint/".$SafeTransfers->id."").'><i class="fal fa-print"></i></a>' ;
                 $code_bill='';
             }elseif($row->Type == 'تحويلات المخازن'){

                       $StorsTransfers=StorsTransfers::where('Code',$row->Code_Type)->orderBy('id','desc')->first();

                 $Action= '<a href='.url("StoresTransferPrint/".$StorsTransfers->id."").'><i class="fal fa-print"></i></a>' ;
                 $code_bill='';
             }elseif($row->Type == 'المشتريات'){

                  $Purchases=Purchases::where('Code',$row->Code_Type)->orderBy('id','desc')->first();

                 $Action= '<a href='.url("PurchPrint/".$Purchases->id."").'><i class="fal fa-print"></i></a>' ;
                 $code_bill=trans('admin.'.$Purchases->Payment_Method);
             }elseif($row->Type == 'مرتجع المشتريات'){

                 $Action= '' ;
                 $code_bill='';
             }elseif($row->Type == 'المبيعات'){

                  $Sales=Sales::where('Code',$row->Code_Type)->orderBy('id','desc')->first();

                 $Action= '<a href='.url("SalesPrint/".$Sales->id."").'><i class="fal fa-print"></i></a>' ;
                 $code_bill=trans('admin.'.$Sales->Payment_Method);
             }elseif($row->Type == 'مرتجع مبيعات'){

                  $ReturnSales=ReturnSales::where('Code',$row->Code_Type)->orderBy('id','desc')->first();

                 $Action= '<a href='.url("ReturnSalesPrint/".$ReturnSales->id."").'><i class="fal fa-print"></i></a>' ;
                 $code_bill='';
             }elseif($row->Type == 'سلفة موظف'){

                 $Action= '' ;
                 $code_bill='';
             }elseif($row->Type == 'قرض موظف'){

                 $Action= '' ;
                 $code_bill='';
             }elseif($row->Type == 'صرف راتب'){

                 $Action= '' ;
                 $code_bill='';
             }elseif($row->Type == 'شراء أصل'){

                 $Action= '' ;
                 $code_bill='';
             }elseif($row->Type == 'وصل أمانة'){

                 $Action= '' ;
                 $code_bill='';
             }elseif($row->Type == 'استلام وصل أمانة'){

                 $Action= '' ;
                 $code_bill='';
             }elseif($row->Type == 'الهالك'){

                 $Action= '' ;
                 $code_bill='';
             }elseif($row->Type == 'مصاريف الأصول'){

                 $Action= '' ;
                 $code_bill='';
             }elseif($row->Type == 'صرف بضاعة'){

                 $Action= '' ;
                 $code_bill='';
             }elseif($row->Type == 'استلام بضاعة'){

                 $Action= '' ;
                 $code_bill='';
             }elseif($row->Type == 'صرف ارباح'){

                 $Action= '' ;
                 $code_bill='';
             }elseif($row->Type == 'بيع اصل'){

                 $Action= '' ;
                 $code_bill='';
             }elseif($row->Type == 'الصيانة'){
                         $ReciptMaintaince=ReciptMaintaince::where('Code',$row->Code_Type)->orderBy('id','desc')->first();
                 $Action= '<a href='.url("ReciptMaintaincePrint/".$ReciptMaintaince->id."").'><i class="fal fa-print"></i></a>' ;
                 $code_bill='';
             }elseif($row->Type == 'مرتجع فاتورة الصيانة'){
                         $ReturnMaintainceBill=ReturnMaintainceBill::where('Code',$row->Code_Type)->orderBy('id','desc')->first();
                 $Action= '<a href='.url("ReturnMaintaincePrint/".$ReturnMaintainceBill->id."").'><i class="fal fa-print"></i></a>' ;
                 $code_bill='';
             }elseif($row->Type == 'صرف عمولات'){

                 $Action= '' ;
                 $code_bill='';
             }elseif($row->Type == 'التصنيع'){

                 $Action= '' ;
                 $code_bill='';
             }elseif($row->Type == 'اشتراكات'){
                         $SalesSubscribes=SalesSubscribes::where('Code',$row->Code_Type)->orderBy('id','desc')->first();
                 $Action= '<a href='.url("SalesSubscribesPrint/".$SalesSubscribes->id."").'><i class="fal fa-print"></i></a>' ;
                 $code_bill='';
             }else{

                   $Action= '' ;
                 $code_bill='';
            }

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

                      $COOIN=$row->Coin()->first()->Arabic_Name;
                      $USSER=$row->userr()->first()->name;
                   $TYPEE=$row->Type;
                   }else{

                      $COOIN=$row->Coin()->first()->English_Name;
                      $USSER=$row->userr()->first()->nameEn;
                          $TYPEE=$row->TypeEn;
                   }

        $output .= '
        <tr>

                                                    <td>'.$row->Date.'</td>
                                                    <td>'.$row->Code.'</td>
                                                    <td>'.$row->Code_Type.'</td>
                                                    <td style="width:180px">'.$TYPEE.' ('.$code_bill.')</td>
                                                      <td class="" >'.$row->Statement.'</td>
                                                        <td>'.$row->Debitor_Coin.'</td>
                                                       <td>'.$row->Creditor_Coin.'</td>
                                                    <td style="width:40px">'.$p.'</td>
                                                    <td style="width:40px">'.$n.'</td>



                                             <td class="">
         '.$COOIN.'
                                            </td>
                                                    <td class="">

                                                    '.$x.'

                                                    </td>



                                                       <td class="">
                                                '.$USSER.'

                                                       </td>
                                                           <td style="width:40px">'.$Action.'</td>
                                                </tr>

        ';

    $last_id = $row->id;
       }

    return   $output ;
          }

         return view('admin.AccountsReports.VendorAccountStatementFilterTwo',get_defined_vars());
    }



            //Customer_Account_Statement

     public function Customer_Account_StatementPage(){
 $Types=GeneralDaily::select('Type','TypeEn')->distinct(['Type'])->get();

         return view('admin.AccountsReports.Customer_Account_Statement',get_defined_vars());
    }

         public function CustomerAccountStatementFilterTwo(Request $request){

             $from = $request->get('from');
             $to = $request->get('to');
             $coin = $request->get('coin');
             $account = $request->get('account');
             $type = $request->get('type');
             $cost = $request->get('cost');
             $user = $request->get('user');
             $n=0;
             $p=0;

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

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

                 })

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

                 })

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

                 })

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

                 })

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

                 })

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

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

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

                 })

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

                 })

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

                 })

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

                 })

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

                 })

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

             $totalAllD=GeneralDaily::

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

             })

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

                 })

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

                 })

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

                 })

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

                 })

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

             $totalAllC=GeneralDaily::

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

             })

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

                 })

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

                 })

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

                 })

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

                 })

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

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

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

                 })

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

                 })

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

                 })

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

                 })

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

                 })

                 ->get()->count();


             $Credit=$totalD - $totalC;
             $CreditAll=$totalAllD - $totalAllC;


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

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

                 })

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

                 })


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

                 })


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

                 })

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

                 })


                 ->paginate(50);

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

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

                 })

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

                 })


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

                 })


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

                 })

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

                 })


                 ->count();


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

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

                 })

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

                 })


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

                 })


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

                 })

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

                 })


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


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

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

                 })

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

                 })


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

                 })


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

                 })

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

                 })


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


             $ProdsCount=0;


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

       foreach($data as $row)
       {



           if($n == 0 and $p == 0){

               $n = $row->Creditor_Coin;
               $p =$row->Debitor_Coin;

           }else{


            if($row->Debitor_Coin == 0){

               if($n == 0){

                   $res=$p  -  $row->Creditor_Coin ;


                if($res < 0){

                  $n=abs($res);
                   $p=0;

                }else{

               $n=0;
                   $p=$res;

                }



               }elseif($p == 0){


                 $res=$n  +  $row->Creditor_Coin ;
                   $n=$res;
                   $p=0;

               }


            }elseif($row->Creditor_Coin == 0){


              if($n == 0){

                $res=$p  +  $row->Debitor_Coin ;

                  $n=0;
                  $p=$res;



               }elseif($p == 0){

                   $res=$n  -  $row->Debitor_Coin ;


                if($res < 0){

                  $n=0;
                   $p=abs($res);
                }else{

                    $n=$res;
                   $p=0;

                }


               }




            }



           }

             if(!empty($row->Cost_Center)){

                    if(app()->getLocale() == 'ar' ){
                      $x=$row->Cost_Center()->first()->Arabic_Name;

                   }else{
                         $x=$row->Cost_Center()->first()->English_Name;

                   }

           }else{

                 $x='';
             }


            if($row->Type == 'القيود اليومية'){

                $Journalizing=Journalizing::where('Code',$row->Code_Type)->orderBy('id','desc')->first();

                 $Action= '<a href='.url("JournalizingPrint/".$Journalizing->id."").'><i class="fal fa-print"></i></a>' ;

                 $code_bill='';
           }elseif($row->Type == 'سند قبض'){


                   $ReciptVoucher=ReciptVoucher::where('Code',$row->Code_Type)->orderBy('id','desc')->first();

                if(!empty($ReciptVoucher)){

                    $Action= '<a href='.url("Receipt_VoucherPrint/".$ReciptVoucher->id."").'><i class="fal fa-print"></i></a>' ;
                }else{

                    $Action='';
                }
                $code_bill='';
             }elseif($row->Type == 'سند صرف'){


                      $PaymentVoucher=PaymentVoucher::where('Code',$row->Code_Type)->orderBy('id','desc')->first();

                 $Action= '<a href='.url("Payment_VoucherPrint/".$PaymentVoucher->id."").'><i class="fal fa-print"></i></a>' ;
                $code_bill='';
             }elseif($row->Type == 'القيد الإفتتاحي'){

                      $OpeningEntries=OpeningEntries::where('Code',$row->Code_Type)->orderBy('id','desc')->first();

                 $Action= '<a href='.url("Opening_EntriesPrint/".$OpeningEntries->id."").'><i class="fal fa-print"></i></a>' ;
                $code_bill='';
             }elseif($row->Type == 'الشيكات الصادرة'){

                     $ExportChecks=ExportChecks::where('Code',$row->Code_Type)->orderBy('id','desc')->first();

                 $Action= '<a href='.url("PrintOutcomChecks/".$ExportChecks->id."").'><i class="fal fa-print"></i></a>' ;
                $code_bill='';
             }elseif($row->Type == 'الشيكات الواردة'){

                    $IncomChecks=IncomChecks::where('Code',$row->Code_Type)->orderBy('id','desc')->first();

                 $Action= '<a href='.url("PrintIncomChecks/".$IncomChecks->id."").'><i class="fal fa-print"></i></a>' ;
                $code_bill='';
             }elseif($row->Type == 'اصناف بداية فترة'){

                     $StartPeriods=StartPeriods::where('Code',$row->Code_Type)->orderBy('id','desc')->first();

                 $Action= '<a href='.url("StartPeriodPrint/".$StartPeriods->id."").'><i class="fal fa-print"></i></a>' ;
                $code_bill='';
             }elseif($row->Type == 'تسوية بالعجز'){


                   $Inventory=Inventory::where('Code',$row->Code_Type)->orderBy('id','desc')->first();
                 $Action= '<a href='.url("InventoryPrint/".$Inventory->id."").'><i class="fal fa-print"></i></a>' ;
                $code_bill='';
             }elseif($row->Type == 'تسوية بالزيادة"'){


                   $Inventory=Inventory::where('Code',$row->Code_Type)->orderBy('id','desc')->first();
                 $Action= '<a href='.url("InventoryPrint/".$Inventory->id."").'><i class="fal fa-print"></i></a>' ;
                $code_bill='';
             }elseif($row->Type == 'تحويلات الخزائن'){


                       $SafeTransfers=SafeTransfers::where('Code',$row->Code_Type)->orderBy('id','desc')->first();
                 $Action= '<a href='.url("TransSafePrint/".$SafeTransfers->id."").'><i class="fal fa-print"></i></a>' ;
                $code_bill='';
             }elseif($row->Type == 'تحويلات المخازن'){

                       $StorsTransfers=StorsTransfers::where('Code',$row->Code_Type)->orderBy('id','desc')->first();

                 $Action= '<a href='.url("StoresTransferPrint/".$StorsTransfers->id."").'><i class="fal fa-print"></i></a>' ;
                $code_bill='';
             }elseif($row->Type == 'المشتريات'){

                  $Purchases=Purchases::where('Code',$row->Code_Type)->orderBy('id','desc')->first();

                 $Action= '<a href='.url("PurchPrint/".$Purchases->id."").'><i class="fal fa-print"></i></a>' ;

                $code_bill=trans('admin.'.$Purchases->Payment_Method);
             }elseif($row->Type == 'مرتجع المشتريات'){

                 $Action= '' ;

             }elseif($row->Type == 'المبيعات'){

                  $Sales=Sales::where('Code',$row->Code_Type)->orderBy('id','desc')->first();

                 $Action= '<a href='.url("SalesPrint/".$Sales->id."").'><i class="fal fa-print"></i></a>' ;


                $code_bill=trans('admin.'.$Sales->Payment_Method);
             }elseif($row->Type == 'مرتجع مبيعات'){

                  $ReturnSales=ReturnSales::where('Code',$row->Code_Type)->orderBy('id','desc')->first();

                 $Action= '<a href='.url("ReturnSalesPrint/".$ReturnSales->id."").'><i class="fal fa-print"></i></a>' ;
                $code_bill='';
             }elseif($row->Type == 'سلفة موظف'){

                 $Action= '' ;
                $code_bill='';
             }elseif($row->Type == 'قرض موظف'){

                 $Action= '' ;
                $code_bill='';
             }elseif($row->Type == 'صرف راتب'){

                 $Action= '' ;
                $code_bill='';
             }elseif($row->Type == 'شراء أصل'){

                 $Action= '' ;
                $code_bill='';
             }elseif($row->Type == 'وصل أمانة'){

                 $Action= '' ;
                $code_bill='';
             }elseif($row->Type == 'استلام وصل أمانة'){

                 $Action= '' ;
                $code_bill='';
             }elseif($row->Type == 'الهالك'){

                 $Action= '' ;
                $code_bill='';
             }elseif($row->Type == 'مصاريف الأصول'){

                 $Action= '' ;
                $code_bill='';
             }elseif($row->Type == 'صرف بضاعة'){

                 $Action= '' ;
                $code_bill='';
             }elseif($row->Type == 'استلام بضاعة'){

                 $Action= '' ;
                $code_bill='';
             }elseif($row->Type == 'صرف ارباح'){

                 $Action= '' ;
                $code_bill='';
             }elseif($row->Type == 'بيع اصل'){

                 $Action= '' ;
                $code_bill='';
             }elseif($row->Type == 'الصيانة'){
                         $ReciptMaintaince=ReciptMaintaince::where('Code',$row->Code_Type)->orderBy('id','desc')->first();
                 $Action= '<a href='.url("ReciptMaintaincePrint/".$ReciptMaintaince->id."").'><i class="fal fa-print"></i></a>' ;
                $code_bill='';
             }elseif($row->Type == 'مرتجع فاتورة الصيانة'){
                         $ReturnMaintainceBill=ReturnMaintainceBill::where('Code',$row->Code_Type)->orderBy('id','desc')->first();
                 $Action= '<a href='.url("ReturnMaintaincePrint/".$ReturnMaintainceBill->id."").'><i class="fal fa-print"></i></a>' ;
                $code_bill='';
             }elseif($row->Type == 'صرف عمولات'){

                 $Action= '' ;
                $code_bill='';
             }elseif($row->Type == 'التصنيع'){

                 $Action= '' ;
                $code_bill='';
             }elseif($row->Type == 'اشتراكات'){
                         $SalesSubscribes=SalesSubscribes::where('Code',$row->Code_Type)->orderBy('id','desc')->first();
                 $Action= '<a href='.url("SalesSubscribesPrint/".$SalesSubscribes->id."").'><i class="fal fa-print"></i></a>' ;
                $code_bill='';
             }else{

                   $Action= '' ;
                $code_bill='';
            }


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

                      $COOIN=$row->Coin()->first()->Arabic_Name;
                      $USSER=$row->userr()->first()->name;
                    $TYPEE=$row->Type;
                   }else{

                      $COOIN=$row->Coin()->first()->English_Name;
                      $USSER=$row->userr()->first()->nameEn;
                         $TYPEE=$row->TypeEn;
                   }

        $output .= '
        <tr>

                                                    <td>'.$row->Date.'</td>
                                                    <td>'.$row->Code.'</td>
                                                    <td>'.$row->Code_Type.' </td>
                                                    <td style="width:250px">'.$TYPEE.' ('.$code_bill.')</td>
                                                      <td>'.$row->Statement.'</td>
                                                        <td>'.$row->Debitor_Coin.'</td>
                                                       <td>'.$row->Creditor_Coin.'</td>
                                                    <td style="width:40px">'.$p.'</td>
                                                    <td style="width:40px">'.$n.'</td>



                                             <td>
          '.$COOIN.'
                                            </td>
                                                    <td>

                                                    '.$x.'

                                                    </td>



                                                       <td>   '.$USSER.'  </td>
                                                         <td style="width:40px">'.$Action.'</td>
                                                </tr>

        ';

    $last_id = $row->id;
       }

    return   $output ;
          }

         return view('admin.AccountsReports.CustomerAccountStatementFilterTwo',get_defined_vars());
    }


        //Cost_Centers_Report

      public function Cost_Centers_ReportPage(){
         return view('admin.AccountsReports.Cost_Centers_Report');
    }

     function Cost_Centers_ReportFilter(Request $request)
             {

     if($request->ajax())
     {
      $output = '';
      $from = $request->get('from');
      $to = $request->get('to');
      $coin = $request->get('coin');
      $account = $request->get('account');
      $type = $request->get('type');
      $cost = $request->get('cost');
      $user = $request->get('user');



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

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

                })

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

                })


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

                })


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

                })

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

                })


          ->get();


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

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

                })

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

                })


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

                })


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

                })

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

                })


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



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

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

                })

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

                })


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

                })


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

                })

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

                })


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


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

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

                })

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

                })


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

                })


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

                })

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

                })


          ->get()->count();




         $dif=  $totalC  - $totalD;


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


       foreach($data as $row)
       {
             if(!empty($row->Cost_Center))    {

                 if(app()->getLocale() == 'ar' ){
                      $x=$row->Cost_Center()->first()->Arabic_Name;

                   }else{
                         $x=$row->Cost_Center()->first()->English_Name;

                   }

           }else{

                 $x='';
             }
                                  if(app()->getLocale() == 'ar' ){

                      $Account=$row->Account()->first()->Name;
                      $COOIN=$row->Coin()->first()->Arabic_Name;
                      $USSER=$row->userr()->first()->name;
                      $TYPEE=$row->Type;
                   }else{

                      $Account=$row->Account()->first()->NameEn;
                      $COOIN=$row->Coin()->first()->English_Name;
                      $USSER=$row->userr()->first()->nameEn;
                         $TYPEE=$row->TypeEn;
                   }
        $output .= '
        <tr>

                                                    <td>'.$row->Date.'</td>
                                                    <td>'.$row->Code.'</td>
                                                    <td>'.$row->Code_Type.'</td>
                                                    <td>'.$TYPEE.'</td>
                                                    <td>'.$row->Debitor.'</td>
                                                    <td>'.$row->Creditor.'</td>
                                                    <td class="">'.$row->Statement.'</td>
                                                    <td class="">'.$row->Account()->first()->Code.'</td>
                                                    <td style="width:200px">
                            '.$Account.'
                                                    </td>
                                                    <td>

   '.$x.'

                                                    </td>
                                                    <td class="">
          '.$COOIN.'
          </td>
                                                       <td class="">'.$row->Draw.'</td>
                                                       <td>'.$row->Debitor_Coin.'</td>
                                                       <td>'.$row->Creditor_Coin.'</td>
                                                       <td class="">   '.$USSER.'  </td>
                                                </tr>

        ';



       }


      }
      else
      {
       $output = '
       <tr>
        <td align="center" colspan="5">No Data Found</td>
       </tr>
       ';
      }
      $data = array(
       'table_data'  => $output,
       'totalD'  => $totalD,
       'totalC'  => $totalC,
       'totalN'  => $totalN,
       'dif'  => $dif,
      );
      echo json_encode($data);
     }
    }


            //Checks_Reports

       public function Checks_ReportsPage(){
              $ChecksTypes=ChecksTypes::all();
         return view('admin.AccountsReports.Checks_Reports',get_defined_vars());
    }

      public function ChecksReportsFilterTwo(Request $request){

           $from = $request->get('from');
      $to = $request->get('to');
      $coin = $request->get('coin');
      $account = $request->get('account');
      $type = $request->get('type');
      $cost = $request->get('cost');
      $user = $request->get('user');
      $CheckStatus = $request->get('CheckStatus');
      $CheckType = $request->get('CheckType');
      $Bank = $request->get('Bank');




             $ChecksTypes=ChecksTypes::all();
  $items =GeneralDaily::whereBetween('Date', [$from, $to])

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

                })

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

                })


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

                })


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

                })

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

                })


          ->paginate(50);

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

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

                })

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

                })


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

                })


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

                })

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

                })


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

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

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

                })

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

                })


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

                })


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

                })

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

                })


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



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

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

                })

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

                })


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

                })


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

                })

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

                })


          ->count();


      $output = '';
          if($request->ajax())
     {
             $from = $request->get('from');
      $to = $request->get('to');
      $coin = $request->get('coin');
      $account = $request->get('account');
      $type = $request->get('type');
      $cost = $request->get('cost');
      $user = $request->get('user');
      $CheckStatus = $request->get('CheckStatus');
      $CheckType = $request->get('CheckType');
      $Bank = $request->get('Bank');


             foreach($items as $row)
       {
             if(!empty($row->Cost_Center))    {

                    if(app()->getLocale() == 'ar' ){
                      $x=$row->Cost_Center()->first()->Arabic_Name;

                   }else{
                         $x=$row->Cost_Center()->first()->English_Name;

                   }

           }else{

                 $x='';
             }


            if($row->Type == 'الشيكات الواردة' or $row->Type == 'الشيكات الصادرة'){

              if($row->Type == 'الشيكات الواردة'){

                  $TYPEE='الشيكات الواردة';

                $Incom=IncomChecks::where('Code',$row->Code_Type)->first();

                       if(app()->getLocale() == 'ar' ){
                      $bnk=$Incom->Bank()->first()->Name;
                           $ACCOUNT=$row->Account()->first()->Name;
                      $sor=$Incom->Check_Type()->first()->Arabic_Name;
      $COOIN=$row->Coin()->first()->Arabic_Name;
              $USSER=$row->userr()->first()->name;
                   }else{
                          $bnk=$Incom->Bank()->first()->NameEn;
                      $sor=$Incom->Check_Type()->first()->English_Name;
                           $ACCOUNT=$row->Account()->first()->NameEn;
    $COOIN=$row->Coin()->first()->English_Name;
          $USSER=$row->userr()->first()->nameEn;
                   }



             if($Incom->Status == 0){

                 $sta=trans('admin.Waiting');

             }elseif($Incom->Status == 1){

                      $sta=trans('admin.Refused');

             }elseif($Incom->Status == 2){

                      $sta=trans('admin.Transfered');

             }elseif($Incom->Status == 3){

                      $sta=trans('admin.Check_Payed');

             }


                                   if(app()->getLocale() == 'ar' ){
                      $ACCOUNT=$row->Account()->first()->Name;
                      $COOIN=$row->Coin()->first()->Arabic_Name;
                      $USSER=$row->userr()->first()->name;
                     $TYPEE=$row->Type;
                   }else{
                     $ACCOUNT=$row->Account()->first()->NameEn;
                      $COOIN=$row->Coin()->first()->English_Name;
                      $USSER=$row->userr()->first()->nameEn;
                      $TYPEE=$row->TypeEn;
                   }


                if($Bank != null and $CheckStatus != '' and $CheckType != ''){

                if($Incom->Bank == $Bank and $Incom->Check_Type == $CheckType and  $Incom->Status == $CheckStatus){
                    $output .= '
                                               <tr>

                                                    <td>'.$row->Date.'</td>
                                                    <td>'.$row->Code.'</td>
                                                    <td>'.$row->Code_Type.'</td>
                                                    <td>'.$TYPEE.'</td>
                                                    <td>'.$row->Debitor.'</td>
                                                    <td>'.$row->Creditor.'</td>
                                                    <td class="">'.$row->Statement.'</td>
                                                    <td class="">'.$row->Account()->first()->Code.'</td>
                                                    <td>
                                                 '.$ACCOUNT.'
                                                    </td>
                                                    <td>'.$bnk.'</td>
                                                    <td>'.$sor.'</td>
                                                    <td>'.$sta.'</td>
                                                    <td>

                                                    '.$x.'

                                                    </td>
                                                    <td>
                                                 '.$COOIN.'
                                                        </td>
                                                       <td>'.$row->Draw.'</td>
                                                       <td>'.$row->Debitor_Coin.'</td>
                                                       <td>'.$row->Creditor_Coin.'</td>
                                                       <td>   '.$USSER.'  </td>
                                                    </tr>

        ';

            $last_id = $row->id;
                }


                }elseif($Bank != null and $CheckStatus == '' and $CheckType == ''){

               if($Incom->Bank == $Bank){
                    $output .= '
                                               <tr>

                                                    <td>'.$row->Date.'</td>
                                                    <td>'.$row->Code.'</td>
                                                    <td>'.$row->Code_Type.'</td>
                                                    <td>'.$TYPEE.'</td>
                                                    <td>'.$row->Debitor.'</td>
                                                    <td>'.$row->Creditor.'</td>
                                                    <td class="">'.$row->Statement.'</td>
                                                    <td class="">'.$row->Account()->first()->Code.'</td>
                                                          <td>
                                                 '.$ACCOUNT.'
                                                    </td>
                                                    <td>'.$bnk.'</td>
                                                    <td>'.$sor.'</td>
                                                    <td>'.$sta.'</td>
                                                    <td>

                                                    '.$x.'

                                                    </td>
                                                       <td>
                                                 '.$COOIN.'
                                                        </td>
                                                       <td>'.$row->Draw.'</td>
                                                       <td>'.$row->Debitor_Coin.'</td>
                                                       <td>'.$row->Creditor_Coin.'</td>
                                                <td>   '.$USSER.'  </td>
                                                    </tr>

        ';
          $last_id = $row->id;

                }

                }elseif($Bank == null and $CheckStatus != '' and $CheckType == ''){

            if( $Incom->Status == $CheckStatus){
                    $output .= '
                                               <tr>

                                                    <td>'.$row->Date.'</td>
                                                    <td>'.$row->Code.'</td>
                                                    <td>'.$row->Code_Type.'</td>
                                                    <td>'.$TYPEE.'</td>
                                                    <td>'.$row->Debitor.'</td>
                                                    <td>'.$row->Creditor.'</td>
                                                    <td class="">'.$row->Statement.'</td>
                                                    <td class="">'.$row->Account()->first()->Code.'</td>
                                                        <td>
                                                 '.$ACCOUNT.'
                                                    </td>
                                                    <td>'.$bnk.'</td>
                                                    <td>'.$sor.'</td>
                                                    <td>'.$sta.'</td>
                                                    <td>

                                                    '.$x.'

                                                    </td>
                                              <td>
                                                 '.$COOIN.'
                                                        </td>
                                                       <td>'.$row->Draw.'</td>
                                                       <td>'.$row->Debitor_Coin.'</td>
                                                       <td>'.$row->Creditor_Coin.'</td>
                                                        <td>   '.$USSER.'  </td>
                                                    </tr>

        ';

           $last_id = $row->id;
                }

                }elseif($Bank == null and $CheckStatus == '' and $CheckType != ''){

           if($Incom->Check_Type == $CheckType){
                    $output .= '
                                               <tr>

                                                    <td>'.$row->Date.'</td>
                                                    <td>'.$row->Code.'</td>
                                                    <td>'.$row->Code_Type.'</td>
                                                    <td>'.$TYPEE.'</td>
                                                    <td>'.$row->Debitor.'</td>
                                                    <td>'.$row->Creditor.'</td>
                                                    <td class="">'.$row->Statement.'</td>
                                                    <td class="">'.$row->Account()->first()->Code.'</td>
                                                     <td>
                                                 '.$ACCOUNT.'
                                                    </td>
                                                    <td>'.$bnk.'</td>
                                                    <td>'.$sor.'</td>
                                                    <td>'.$sta.'</td>
                                                    <td>

                                                    '.$x.'

                                                    </td>
                                         <td>
                                                 '.$COOIN.'
                                                        </td>
                                                       <td>'.$row->Draw.'</td>
                                                       <td>'.$row->Debitor_Coin.'</td>
                                                       <td>'.$row->Creditor_Coin.'</td>
                                                    <td>   '.$USSER.'  </td>
                                                    </tr>

        ';

         $last_id = $row->id;
                }

                }elseif($Bank != null and $CheckStatus != '' and $CheckType == ''){

           if($Incom->Bank == $Bank  and  $Incom->Status == $CheckStatus){
                    $output .= '
                                               <tr>

                                                    <td>'.$row->Date.'</td>
                                                    <td>'.$row->Code.'</td>
                                                    <td>'.$row->Code_Type.'</td>
                                                    <td>'.$TYPEE.'</td>
                                                    <td>'.$row->Debitor.'</td>
                                                    <td>'.$row->Creditor.'</td>
                                                    <td class="">'.$row->Statement.'</td>
                                                    <td class="">'.$row->Account()->first()->Code.'</td>
                                                         <td>
                                                 '.$ACCOUNT.'
                                                    </td>
                                                    <td>'.$bnk.'</td>
                                                    <td>'.$sor.'</td>
                                                    <td>'.$sta.'</td>
                                                    <td>

                                                    '.$x.'

                                                    </td>
                                        <td>
                                                 '.$COOIN.'
                                                        </td>
                                                       <td>'.$row->Draw.'</td>
                                                       <td>'.$row->Debitor_Coin.'</td>
                                                       <td>'.$row->Creditor_Coin.'</td>
                                                       <td>   '.$USSER.'  </td>
                                                    </tr>

        ';
            $last_id = $row->id;

                }

                }elseif($Bank != null and $CheckStatus == '' and $CheckType != ''){

          if($Incom->Bank == $Bank and $Incom->Check_Type == $CheckType){
                    $output .= '
                                               <tr>

                                                    <td>'.$row->Date.'</td>
                                                    <td>'.$row->Code.'</td>
                                                    <td>'.$row->Code_Type.'</td>
                                                    <td>'.$TYPEE.'</td>
                                                    <td>'.$row->Debitor.'</td>
                                                    <td>'.$row->Creditor.'</td>
                                                    <td class="">'.$row->Statement.'</td>
                                                    <td class="">'.$row->Account()->first()->Code.'</td>
                                                      <td>
                                                 '.$ACCOUNT.'
                                                    </td>
                                                    <td>'.$bnk.'</td>
                                                    <td>'.$sor.'</td>
                                                    <td>'.$sta.'</td>
                                                    <td>

                                                    '.$x.'

                                                    </td>
                                        <td>
                                                 '.$COOIN.'
                                                        </td>
                                                       <td>'.$row->Draw.'</td>
                                                       <td>'.$row->Debitor_Coin.'</td>
                                                       <td>'.$row->Creditor_Coin.'</td>
                                                          <td>   '.$USSER.'  </td>
                                                    </tr>

        ';
            $last_id = $row->id;

                }

                }elseif($Bank == null and $CheckStatus != '' and $CheckType != ''){

             if($Incom->Check_Type == $CheckType and  $Incom->Status == $CheckStatus){
                    $output .= '
                                               <tr>

                                                    <td>'.$row->Date.'</td>
                                                    <td>'.$row->Code.'</td>
                                                    <td>'.$row->Code_Type.'</td>
                                                    <td>'.$TYPEE.'</td>
                                                    <td>'.$row->Debitor.'</td>
                                                    <td>'.$row->Creditor.'</td>
                                                    <td class="">'.$row->Statement.'</td>
                                                    <td class="">'.$row->Account()->first()->Code.'</td>
                                                <td>
                                                 '.$ACCOUNT.'
                                                    </td>
                                                    <td>'.$bnk.'</td>
                                                    <td>'.$sor.'</td>
                                                    <td>'.$sta.'</td>
                                                    <td>

                                                    '.$x.'

                                                    </td>
                                      <td>
                                                 '.$COOIN.'
                                                        </td>
                                                       <td>'.$row->Draw.'</td>
                                                       <td>'.$row->Debitor_Coin.'</td>
                                                       <td>'.$row->Creditor_Coin.'</td>
                                                   <td>   '.$USSER.'  </td>
                                                    </tr>

        ';

            $last_id = $row->id;
                }

                }elseif($Bank == null and $CheckStatus == '' and $CheckType == ''){


                    $output .= '
                                               <tr>

                                                    <td>'.$row->Date.'</td>
                                                    <td>'.$row->Code.'</td>
                                                    <td>'.$row->Code_Type.'</td>
                                                    <td>'.$TYPEE.'</td>
                                                    <td>'.$row->Debitor.'</td>
                                                    <td>'.$row->Creditor.'</td>
                                                    <td class="">'.$row->Statement.'</td>
                                                    <td class="">'.$row->Account()->first()->Code.'</td>
                                                     <td>
                                                 '.$ACCOUNT.'
                                                    </td>
                                                    <td>'.$bnk.'</td>
                                                    <td>'.$sor.'</td>
                                                    <td>'.$sta.'</td>
                                                    <td>

                                                    '.$x.'

                                                    </td>
                                          <td>
                                                 '.$COOIN.'
                                                        </td>
                                                       <td>'.$row->Draw.'</td>
                                                       <td>'.$row->Debitor_Coin.'</td>
                                                       <td>'.$row->Creditor_Coin.'</td>
                                                               <td>   '.$USSER.'  </td>
                                                    </tr>

        ';


          $last_id = $row->id;

                }


            }elseif($row->Type == 'الشيكات الصادرة'){

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

                      $ACCOUNT=$row->Account()->first()->Name;
                      $COOIN=$row->Coin()->first()->Arabic_Name;
                      $USSER=$row->userr()->first()->name;


                  }else{

                      $ACCOUNT=$row->Account()->first()->NameEn;
                      $COOIN=$row->Coin()->first()->English_Name;
                      $USSER=$row->userr()->first()->nameEn;

                  }


                  $TYPEE='الشيكات الصادرة';

                $Incom=ExportChecks::where('Code',$row->Code_Type)->first();

                $bnk=$Incom->Bank()->first()->Name;
                $sor=$Incom->Check_Type()->first()->Arabic_Name;

             if($Incom->Status == 0){

                 $sta=trans('admin.Waiting');

             }elseif($Incom->Status == 1){

                      $sta=trans('admin.Refused');

             }elseif($Incom->Status == 2){

                      $sta=trans('admin.Transfered');

             }elseif($Incom->Status == 3){

                      $sta=trans('admin.Check_Payed');

             }


                if($Bank != null and $CheckStatus != '' and $CheckType != ''){

                if($Incom->Bank == $Bank and $Incom->Check_Type == $CheckType and  $Incom->Status == $CheckStatus){
                    $output .= '
                                               <tr>

                                                    <td>'.$row->Date.'</td>
                                                    <td>'.$row->Code.'</td>
                                                    <td>'.$row->Code_Type.'</td>
                                                    <td>'.$TYPEE.'</td>
                                                    <td>'.$row->Debitor.'</td>
                                                    <td>'.$row->Creditor.'</td>
                                                    <td class="">'.$row->Statement.'</td>
                                                    <td class="">'.$row->Account()->first()->Code.'</td>
                                                     <td>
                                                 '.$ACCOUNT.'
                                                    </td>
                                                    <td>'.$bnk.'</td>
                                                    <td>'.$sor.'</td>
                                                    <td>'.$sta.'</td>
                                                    <td>

                                                    '.$x.'

                                                    </td>
                                          <td>
                                                 '.$COOIN.'
                                                        </td>
                                                       <td>'.$row->Draw.'</td>
                                                       <td>'.$row->Debitor_Coin.'</td>
                                                       <td>'.$row->Creditor_Coin.'</td>
                                                        <td>   '.$USSER.'  </td>
                                                    </tr>

        ';

             $last_id = $row->id;
                }


                }elseif($Bank != null and $CheckStatus == '' and $CheckType == ''){

               if($Incom->Bank == $Bank){
                    $output .= '
                                               <tr>

                                                    <td>'.$row->Date.'</td>
                                                    <td>'.$row->Code.'</td>
                                                    <td>'.$row->Code_Type.'</td>
                                                    <td>'.$TYPEE.'</td>
                                                    <td>'.$row->Debitor.'</td>
                                                    <td>'.$row->Creditor.'</td>
                                                    <td class="">'.$row->Statement.'</td>
                                                    <td class="">'.$row->Account()->first()->Code.'</td>
                                                 <td>
                                                 '.$ACCOUNT.'
                                                    </td>
                                                    <td>'.$bnk.'</td>
                                                    <td>'.$sor.'</td>
                                                    <td>'.$sta.'</td>
                                                    <td>

                                                    '.$x.'

                                                    </td>
                                              <td>
                                                 '.$COOIN.'
                                                        </td>
                                                       <td>'.$row->Draw.'</td>
                                                       <td>'.$row->Debitor_Coin.'</td>
                                                       <td>'.$row->Creditor_Coin.'</td>
                                                          <td>   '.$USSER.'  </td>
                                                    </tr>

        ';

         $last_id = $row->id;
                }

                }elseif($Bank == null and $CheckStatus != '' and $CheckType == ''){

            if( $Incom->Status == $CheckStatus){
                    $output .= '
                                               <tr>

                                                    <td>'.$row->Date.'</td>
                                                    <td>'.$row->Code.'</td>
                                                    <td>'.$row->Code_Type.'</td>
                                                    <td>'.$TYPEE.'</td>
                                                    <td>'.$row->Debitor.'</td>
                                                    <td>'.$row->Creditor.'</td>
                                                    <td class="">'.$row->Statement.'</td>
                                                    <td class="">'.$row->Account()->first()->Code.'</td>
                                                     <td>
                                                 '.$ACCOUNT.'
                                                    </td>
                                                    <td>'.$bnk.'</td>
                                                    <td>'.$sor.'</td>
                                                    <td>'.$sta.'</td>
                                                    <td>

                                                    '.$x.'

                                                    </td>
                                            <td>
                                                 '.$COOIN.'
                                                        </td>
                                                       <td>'.$row->Draw.'</td>
                                                       <td>'.$row->Debitor_Coin.'</td>
                                                       <td>'.$row->Creditor_Coin.'</td>
                                                           <td>   '.$USSER.'  </td>
                                                    </tr>

        ';

         $last_id = $row->id;
                }

                }elseif($Bank == null and $CheckStatus == '' and $CheckType != ''){

           if($Incom->Check_Type == $CheckType){
                    $output .= '
                                               <tr>

                                                    <td>'.$row->Date.'</td>
                                                    <td>'.$row->Code.'</td>
                                                    <td>'.$row->Code_Type.'</td>
                                                    <td>'.$TYPEE.'</td>
                                                    <td>'.$row->Debitor.'</td>
                                                    <td>'.$row->Creditor.'</td>
                                                    <td class="">'.$row->Statement.'</td>
                                                    <td class="">'.$row->Account()->first()->Code.'</td>
                                                 <td>
                                                 '.$ACCOUNT.'
                                                    </td>
                                                    <td>'.$bnk.'</td>
                                                    <td>'.$sor.'</td>
                                                    <td>'.$sta.'</td>
                                                    <td>

                                                    '.$x.'

                                                    </td>
                                       <td>
                                                 '.$COOIN.'
                                                        </td>
                                                       <td>'.$row->Draw.'</td>
                                                       <td>'.$row->Debitor_Coin.'</td>
                                                       <td>'.$row->Creditor_Coin.'</td>
                                                            <td>   '.$USSER.'  </td>
                                                    </tr>

        ';

            $last_id = $row->id;
                }

                }elseif($Bank != null and $CheckStatus != '' and $CheckType == ''){

           if($Incom->Bank == $Bank  and  $Incom->Status == $CheckStatus){
                    $output .= '
                                               <tr>

                                                    <td>'.$row->Date.'</td>
                                                    <td>'.$row->Code.'</td>
                                                    <td>'.$row->Code_Type.'</td>
                                                    <td>'.$TYPEE.'</td>
                                                    <td>'.$row->Debitor.'</td>
                                                    <td>'.$row->Creditor.'</td>
                                                    <td class="">'.$row->Statement.'</td>
                                                    <td class="">'.$row->Account()->first()->Code.'</td>
                                                      <td>
                                                 '.$ACCOUNT.'
                                                    </td>
                                                    <td>'.$bnk.'</td>
                                                    <td>'.$sor.'</td>
                                                    <td>'.$sta.'</td>
                                                    <td>

                                                    '.$x.'

                                                    </td>
                                               <td>
                                                 '.$COOIN.'
                                                        </td>
                                                       <td>'.$row->Draw.'</td>
                                                       <td>'.$row->Debitor_Coin.'</td>
                                                       <td>'.$row->Creditor_Coin.'</td>
                                                            <td>   '.$USSER.'  </td>
                                                    </tr>

        ';

                $last_id = $row->id;
                }

                }elseif($Bank != null and $CheckStatus == '' and $CheckType != ''){

          if($Incom->Bank == $Bank and $Incom->Check_Type == $CheckType){
                    $output .= '
                                               <tr>

                                                    <td>'.$row->Date.'</td>
                                                    <td>'.$row->Code.'</td>
                                                    <td>'.$row->Code_Type.'</td>
                                                    <td>'.$TYPEE.'</td>
                                                    <td>'.$row->Debitor.'</td>
                                                    <td>'.$row->Creditor.'</td>
                                                    <td class="">'.$row->Statement.'</td>
                                                    <td class="">'.$row->Account()->first()->Code.'</td>
                                                      <td>
                                                 '.$ACCOUNT.'
                                                    </td>
                                                    <td>'.$bnk.'</td>
                                                    <td>'.$sor.'</td>
                                                    <td>'.$sta.'</td>
                                                    <td>

                                                    '.$x.'

                                                    </td>
                                        <td>
                                                 '.$COOIN.'
                                                        </td>
                                                       <td>'.$row->Draw.'</td>
                                                       <td>'.$row->Debitor_Coin.'</td>
                                                       <td>'.$row->Creditor_Coin.'</td>
                                                      <td>   '.$USSER.'  </td>
                                                    </tr>

        ';

                $last_id = $row->id;
                }

                }elseif($Bank == null and $CheckStatus != '' and $CheckType != ''){

             if($Incom->Check_Type == $CheckType and  $Incom->Status == $CheckStatus){
                    $output .= '
                                               <tr>

                                                    <td>'.$row->Date.'</td>
                                                    <td>'.$row->Code.'</td>
                                                    <td>'.$row->Code_Type.'</td>
                                                    <td>'.$TYPEE.'</td>
                                                    <td>'.$row->Debitor.'</td>
                                                    <td>'.$row->Creditor.'</td>
                                                    <td class="">'.$row->Statement.'</td>
                                                    <td class="">'.$row->Account()->first()->Code.'</td>
                                          <td>
                                                 '.$ACCOUNT.'
                                                    </td>
                                                    <td>'.$bnk.'</td>
                                                    <td>'.$sor.'</td>
                                                    <td>'.$sta.'</td>
                                                    <td>

                                                    '.$x.'

                                                    </td>
                                          <td>
                                                 '.$COOIN.'
                                                        </td>
                                                       <td>'.$row->Draw.'</td>
                                                       <td>'.$row->Debitor_Coin.'</td>
                                                       <td>'.$row->Creditor_Coin.'</td>
                                                       <td>   '.$USSER.'  </td>
                                                    </tr>

        ';
               $last_id = $row->id;

                }

                }elseif($Bank == null and $CheckStatus == '' and $CheckType == ''){


                    $output .= '
                                               <tr>

                                                    <td>'.$row->Date.'</td>
                                                    <td>'.$row->Code.'</td>
                                                    <td>'.$row->Code_Type.'</td>
                                                    <td>'.$TYPEE.'</td>
                                                    <td>'.$row->Debitor.'</td>
                                                    <td>'.$row->Creditor.'</td>
                                                    <td class="">'.$row->Statement.'</td>
                                                    <td class="">'.$row->Account()->first()->Code.'</td>
                                                    <td>
                                                 '.$ACCOUNT.'
                                                    </td>
                                                    <td>'.$bnk.'</td>
                                                    <td>'.$sor.'</td>
                                                    <td>'.$sta.'</td>
                                                    <td>

                                                    '.$x.'

                                                    </td>
                                             <td>
                                                 '.$COOIN.'
                                                        </td>
                                                       <td>'.$row->Draw.'</td>
                                                       <td>'.$row->Debitor_Coin.'</td>
                                                       <td>'.$row->Creditor_Coin.'</td>
                                                           <td>   '.$USSER.'  </td>
                                                    </tr>

        ';


               $last_id = $row->id;

                }




            }

            }

           $last_id=$row->id;
       }


    return   $output ;
          }

         return view('admin.AccountsReports.ChecksReportsFilterTwo',get_defined_vars());
    }



    //InsurancePaperReport
         public function InsurancePaperReport(){
         return view('admin.AccountsReports.InsurancePaperReport');
    }


      public function InsurancePaperReportFilter(Request $request){

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

  $items =InsurancePaper::whereBetween('Date', [$from, $to])

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

                })

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

                })

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

                })

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

                })


          ->paginate(50);



      $total =InsurancePaper::whereBetween('Date', [$from, $to])

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

                })

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

                })

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

                })

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

                })

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





      $Counter =InsurancePaper::whereBetween('Date', [$from, $to])

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

                })

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

                })

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

                })

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

                })

          ->count();


      $output = '';
          if($request->ajax())
     {
      $from = $request->get('from');
      $to = $request->get('to');
      $coin = $request->get('coin');
      $account = $request->get('account');
      $user = $request->get('user');
      $Bank = $request->get('Bank');



              foreach($items as $row){


                                   if(app()->getLocale() == 'ar' ){
                      $ACCOUNT=$row->Account()->first()->Name;
                      $COOIN=$row->Coin()->first()->Arabic_Name;
                      $USSER=$row->User()->first()->name;

                   }else{
                     $ACCOUNT=$row->Account()->first()->NameEn;
                      $COOIN=$row->Coin()->first()->English_Name;
                      $USSER=$row->User()->first()->nameEn;

                   }

                   $output .= '
                                               <tr>

                                                    <td>'.$row->Code.'</td>
                                                    <td>'.$row->Date.'</td>
                                                           <td>
                                                 '.$ACCOUNT.'
                                                    </td>
                                                    <td>'.$row->From.'</td>
                                                    <td>'.$row->To.'</td>
                                                    <td>'.$row->Due_Date.'</td>
                                                    <td>'.$row->Amount.'</td>
                                                              <td>
                                                 '.$COOIN.'
                                                        </td>
                                                    <td>'.$row->Draw.'</td>
                                                    <td>'.$row->Draw * $row->Amount.'</td>
                                                  <td>'.$row->Note.'</td>
                                                 <td>   '.$USSER.'  </td>
                                                    </tr>

        ';


              }

    return   $output ;
          }

         return view('admin.AccountsReports.InsurancePaperReportFilter',get_defined_vars());
    }


            //Incom_List




          public function Incom_ListPage(){
         return view('admin.AccountsReports.Incom_ListNew');
    }

      function FilterIncom_ListNew(Request $request){

    if($request->ajax())
     {
      $output = '';
      $from = $request->get('From');
      $to = $request->get('To');
      $type = $request->get('Type');
      $coin = $request->get('Coin');


        if($from != '' and  $to != null and $type != ''){


               //   =============  Erydaat   ===========
               $AEryd=AcccountingManual::where('id',18)->first();


        if($AEryd->Parent == 0){

          $words=$AEryd->Code.'0';
          $wordsX=$AEryd->Code.'1';

        }else{

           $words=$AEryd->Code;
           $wordsX=$AEryd->Code;

        }


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

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

                   }


         $output .= '
     <tr class="Erydat">
     <td> '.$xName.' </td>
     <td>
     <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#ErydDet" onclick="DetailsEryd()">'.trans("admin.Details").'</button>
     </td>
     <td>  </td>
    </tr>
     ';



        $egmalymby3atDa2n=GeneralDaily::where('Account',48)
         ->whereBetween('Date', [$from, $to])
        ->get()->sum('Creditor_Coin');
$egmalymby3atMadeen=GeneralDaily::where('Account',48)
     ->whereBetween('Date', [$from, $to])
    ->get()->sum('Debitor_Coin');

$egmalymrdodatDa2n=GeneralDaily::where('Account',49)
     ->whereBetween('Date', [$from, $to])
    ->get()->sum('Creditor_Coin');

$egmalymrdodatMadeen=GeneralDaily::where('Account',49)
     ->whereBetween('Date', [$from, $to])
    ->get()->sum('Debitor_Coin');

        $safy = abs($egmalymby3atDa2n - $egmalymby3atMadeen) -  abs($egmalymrdodatDa2n - $egmalymrdodatMadeen);



          $output .= '
   <tr class="SafyMbe3at">
     <td>  '.trans('admin.Sales_Net').' </td>
<td style="border: none;text-align: end;">'.number_format((float)$safy, 2, '.', '').'</td>
<td style="border: none;text-align: end;"></td>
   </tr>
     ';




        $TotalDebErydat = DB::table('acccounting_manuals')
            ->join('general_dailies', function ($join) {

                  $to = request('To');
                 $from = request('From');
            $join->on('acccounting_manuals.id', '=', 'general_dailies.Account')
                 ->whereBetween('general_dailies.Date',[$from,$to]);
        })

          ->where('acccounting_manuals.Code', 'like', $words.'%')
          ->orWhere('acccounting_manuals.Code', 'like', $wordsX.'%')
                 ->where('acccounting_manuals.Type',  '=',1)
            ->get()->sum('Debitor_Coin');



        $TotalCredErydat = DB::table('acccounting_manuals')
            ->join('general_dailies', function ($join) {

                 $to = request('To');
                 $from = request('From');
            $join->on('acccounting_manuals.id', '=', 'general_dailies.Account')
                 ->whereBetween('general_dailies.Date',[$from,$to]);
        })

          ->where('acccounting_manuals.Code', 'like', $words.'%')
                   ->orWhere('acccounting_manuals.Code', 'like', $wordsX.'%')
                 ->where('acccounting_manuals.Type',  '=',1)
            ->get()->sum('Creditor_Coin');



            $EgmalyErydaat=  $TotalCredErydat -  $TotalDebErydat ;


    if($EgmalyErydaat < 0){
          $output .= '
   <tr class="Erydat">
     <td> '.trans('admin.Total_Revenue').'</td>
<td>'.number_format((float)$EgmalyErydaat, 2, '.', '').'</td>
<td>0</td>
   </tr>
     ';
    }else{

                $output .= '
   <tr class="Erydat">
     <td> '.trans('admin.Total_Revenue').'</td>
<td>0</td>
<td>'.number_format((float)$EgmalyErydaat, 2, '.', '').'</td>
   </tr>
     ';

    }

            //   End Erydat ====================================






            //  Taklfa  =========================


   $ATaklfa=AcccountingManual::where('id',19)->first();

        if($ATaklfa->Parent == 0){

          $wordss=$ATaklfa->Code.'0';
          $wordssX=$ATaklfa->Code.'1';

        }else{

           $wordss=$ATaklfa->Code;
           $wordssX=$ATaklfa->Code;

        }


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

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

                   }

$output .= '
     <tr class="Taklfa" >
     <td> '.$xxName.' </td>
    <td>
     <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#TaklfaDet" onclick="DetailsTaklfa()">'.trans("admin.Details").'</button>
     </td>
     <td>  </td>
    </tr>
     ';


            $TotalDebTaklfa = DB::table('acccounting_manuals')
            ->join('general_dailies', function ($join) {

                  $to = request('To');
                 $from = request('From');
            $join->on('acccounting_manuals.id', '=', 'general_dailies.Account')
                 ->whereBetween('general_dailies.Date',[$from,$to]);
        })

          ->where('acccounting_manuals.Code', 'like', $wordss.'%')
          ->orWhere('acccounting_manuals.Code', 'like', $wordssX.'%')
                 ->where('acccounting_manuals.Type',  '=',1)
            ->get()->sum('Debitor_Coin');



        $TotalCredTaklfa = DB::table('acccounting_manuals')
            ->join('general_dailies', function ($join) {

                 $to = request('To');
                 $from = request('From');
            $join->on('acccounting_manuals.id', '=', 'general_dailies.Account')
                 ->whereBetween('general_dailies.Date',[$from,$to]);
        })

          ->where('acccounting_manuals.Code', 'like', $wordss.'%')
             ->orWhere('acccounting_manuals.Code', 'like', $wordssX.'%')
                 ->where('acccounting_manuals.Type',  '=',1)
            ->get()->sum('Creditor_Coin');



            $EgmalyTaklfa=  $TotalDebTaklfa -  $TotalCredTaklfa ;

      if($EgmalyTaklfa < 0){
          $output .= '
   <tr class="Taklfa">
 <td>  '.trans('admin.Total_Sales_Cost').'</td>
<td>0</td>
<td>'.number_format((float)$EgmalyTaklfa, 2, '.', '').'</td>
   </tr>
     ';
    }else{

          $output .= '
   <tr class="Taklfa">
 <td>'.trans('admin.Total_Sales_Cost').'</td>
<td>'.number_format((float)$EgmalyTaklfa, 2, '.', '').'</td>
<td>0</td>
   </tr>
     ';

    }





              // End  Taklfa  =========================


              // Mogmml Rab7 w khsara   =========================


              $Mogml = $EgmalyErydaat   -  $EgmalyTaklfa   ;


         if($Mogml < 0){
          $output .= '
   <tr class="Mogmaal">
 <td>'.trans('admin.Total_Profit_Loss').'</td>
<td>'.number_format((float)$Mogml, 2, '.', '').'</td>
<td>0</td>
   </tr>
     ';
    }else{

          $output .= '
   <tr class="Mogmaal">
 <td> '.trans('admin.Total_Profit_Loss').' </td>
<td>0</td>
<td>'.number_format((float)$Mogml, 2, '.', '').'</td>
   </tr>
     ';

    }
            // End  Mogmml Rab7 w khsara   =========================


        // Masrofat ============================

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

        if($AMsrfoat->Parent == 0){

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

        }else{

           $wordsss=$AMsrfoat->Code;
           $wordsssX=$AMsrfoat->Code;


        }



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

                   }else{
                         $xxxName=$AMsrfoat->NameEn;

                   }

$output .= '
     <tr class="Masrofat">
     <td> '.$xxxName.' </td>
        <td>
     <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#MasrofatDet" onclick="DetailsMasrofat()">'.trans("admin.Details").'</button>
     </td>
     <td>  </td>
    </tr>
     ';


             $TotalDebMasrofat = DB::table('acccounting_manuals')
            ->join('general_dailies', function ($join) {

                  $to = request('To');
                 $from = request('From');
            $join->on('acccounting_manuals.id', '=', 'general_dailies.Account')
                 ->whereBetween('general_dailies.Date',[$from,$to]);
        })

          ->where('acccounting_manuals.Code', 'like', $wordsss.'%')
          ->orWhere('acccounting_manuals.Code', 'like', $wordsssX.'%')
                 ->where('acccounting_manuals.Type',  '=',1)
            ->get()->sum('Debitor_Coin');



        $TotalCredMasrofat = DB::table('acccounting_manuals')
            ->join('general_dailies', function ($join) {

                 $to = request('To');
                 $from = request('From');
            $join->on('acccounting_manuals.id', '=', 'general_dailies.Account')
                 ->whereBetween('general_dailies.Date',[$from,$to]);
        })

          ->where('acccounting_manuals.Code', 'like', $wordsss.'%')
           ->orWhere('acccounting_manuals.Code', 'like', $wordsssX.'%')
                 ->where('acccounting_manuals.Type',  '=',1)
            ->get()->sum('Creditor_Coin');



            $EgmalyMasrofat=  $TotalDebMasrofat -  $TotalCredMasrofat ;

              if($EgmalyMasrofat < 0){
          $output .= '
   <tr class="Masrofat">
   <td>  '.trans('admin.Total_Expenses').'</td>
<td>0</td>
<td>'.number_format((float)$EgmalyMasrofat, 2, '.', '').'</td>
   </tr>
     ';
    }else{

          $output .= '
   <tr class="Masrofat">
   <td>  '.trans('admin.Total_Expenses').'</td>
<td>'.number_format((float)$EgmalyMasrofat, 2, '.', '').'</td>
<td>0</td>
   </tr>
     ';

    }

            //End Masrofat  ==================
            //Safy Rab7 w Khsara ==================




        $fg= $EgmalyTaklfa + $EgmalyMasrofat;
        if($EgmalyErydaat >  $fg){
         if($fg  <  0 ){

            $SafyRab7 =$EgmalyErydaat + ($EgmalyTaklfa  +   $EgmalyMasrofat)  ;
        }else{

              $SafyRab7 = $EgmalyErydaat -  ($EgmalyTaklfa  +   $EgmalyMasrofat)  ;

        }
        }elseif($EgmalyErydaat <  $fg){

        if($fg  <  0 ){

            $SafyRab7 =$EgmalyErydaat + ($EgmalyTaklfa  +   $EgmalyMasrofat)  ;
        }else{

              $SafyRab7 = $EgmalyErydaat -  ($EgmalyTaklfa  +   $EgmalyMasrofat)  ;

        }


        }elseif($EgmalyErydaat ==  $fg){

           $SafyRab7 = $EgmalyErydaat -  ($EgmalyTaklfa  +   $EgmalyMasrofat)  ;

        }

          $output .= '
   <tr class="SafyRb7">
     <td>  '.trans('admin.Net_Profit_Loss').'</td>
<td style="border: none;text-align: end;">'.number_format((float)($SafyRab7), 2, '.', '').'</td>
<td style="border: none;text-align: end;"></td>
   </tr>
     ';


            //End Safy Rab7 w Khsara ==================



     $data = array(
       'table_data'  => $output,
      );
      echo json_encode($data);

        }
      }
      }

        function FilterIncom_ListErydat(Request $request){

    if($request->ajax())
     {
      $output = '';
      $to = $request->get('To');
      $from = $request->get('From');
      $type = $request->get('Type');
        if($to != null and $to != null and $type != ''){


             if($type == 1){
                                     $x=0;
                   $y=0;
    $TotalErydatD = 0;
$TotalErydatC = 0;

       $AEryd=AcccountingManual::where('id',18)->first();

        if($AEryd->Parent == 0){

          $words=$AEryd->Code.'0';
          $wordsX=$AEryd->Code.'1';

        }else{

           $words=$AEryd->Code;
           $wordsX=$AEryd->Code;

        }

$AccountsErydat = AcccountingManual::
                 where('Code', 'like', $words.'%')
                     ->orWhere('Code', 'like', $wordsX.'%')

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



       foreach($AccountsErydat as $row)
       {


               $TotalDeb =GeneralDaily::where('Account',$row->id)
          ->whereBetween('Date', [$from, $to])
          ->get()->sum('Debitor_Coin');


               $TotalCred =GeneralDaily::where('Account',$row->id)
          ->whereBetween('Date', [$from, $to])
          ->get()->sum('Creditor_Coin');


           $z=$TotalDeb - $TotalCred ;

           if($z == 0){

                    $x=0;
                   $y=0;
    $TotalErydatD += 0;
$TotalErydatC += 0;
           }elseif($z < 0){

                $x=0;
                   $y=abs($z);
$TotalErydatD += 0;
$TotalErydatC += abs($z);

           }elseif($z > 0){

                $x=$z;
                   $y=0;
    $TotalErydatD += $z;
$TotalErydatC += 0;

           }

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

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

                   }
        $output .= '
      <tr class="Erydat">
                                                  <td>'.$xName.'</td>
                                                    <td>'.number_format((float)$x, 2, '.', '').'</td>
                                                    <td>'.number_format((float)$y, 2, '.', '').'</td>

    </tr>
        ';




       }




             }else{

                 $wf=40;
                 $wfx=41;
  $Accounts=AcccountingManual::orderBy('Code','asc')
      ->where('Code','like', $wf.'%')
            ->orWhere('Code','like', $wfx.'%')
      ->where('Type',$type)->get();

               foreach($Accounts as $row){

$SubTotalDeb=0;
$SubTotalCred=0;
$suby=0;
$subz=0;
             $count=AcccountingManual::where('Parent',$row->id)->where('Type',1)->count();

          if($count != 0){

             $ASubs=AcccountingManual::where('Parent',$row->id)->where('Type',1)->get();


              foreach($ASubs as $a){

               $SubTotalDeb +=GeneralDaily::where('Account',$a->id)
          ->whereBetween('Date', [$from, $to])
          ->get()->sum('Debitor_Coin');


               $SubTotalCred +=GeneralDaily::where('Account',$a->id)
          ->whereBetween('Date', [$from, $to])
          ->get()->sum('Creditor_Coin');

              }

            $x= $SubTotalDeb  -  $SubTotalCred  ;


                      if($x < 0){

               $suby =0;
               $subz =abs($x);

           }else{

               $suby =$x;
               $subz =0;


           }

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

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

                   }

              $output .= '
                                       <tr class="Erydat">
                                             <td>'.$xName.'</td>
                                               <td>'.number_format((float)$suby, 2, '.', '').'</td>
                                               <td>'.number_format((float)$subz, 2, '.', '').'</td>

                                                </tr>

        ';



         }
         }


             }



             $data = array(
       'table_data'  => $output,

      );
      echo json_encode($data);

        }

    }

      }


        function FilterIncom_ListTaklfa(Request $request){

    if($request->ajax())
     {
      $output = '';
      $to = $request->get('To');
      $from = $request->get('From');
      $type = $request->get('Type');
        if($to != null and $to != null and $type != ''){


             if($type == 1){

                            $xT=0;
                   $yT=0;
    $TotalTakloftD = 0;
$TotalTakloftC = 0;

  $ATaklfa=AcccountingManual::where('id',19)->first();

        if($ATaklfa->Parent == 0){

          $wordss=$ATaklfa->Code.'0';
          $wordssX=$ATaklfa->Code.'1';

        }else{

           $wordss=$ATaklfa->Code;
           $wordssX=$ATaklfa->Code;

        }

$AccountsTakolfat = AcccountingManual::
                 where('Code', 'like', $wordss.'%')
                 ->orWhere('Code', 'like', $wordssX.'%')
    ->where('Type', 1)
    ->get();


       foreach($AccountsTakolfat as $rowT)
       {


               $TotalDeb =GeneralDaily::where('Account',$rowT->id)
          ->whereBetween('Date', [$from, $to])
          ->get()->sum('Debitor_Coin');


               $TotalCred =GeneralDaily::where('Account',$rowT->id)
          ->whereBetween('Date', [$from, $to])
          ->get()->sum('Creditor_Coin');


           $zT=$TotalDeb - $TotalCred ;

           if($zT == 0){

                    $xT=0;
                   $yT=0;
    $TotalTakloftD += 0;
$TotalTakloftC += 0;
           }elseif($zT < 0){

                $xT=0;
                   $yT=abs($zT);
$TotalTakloftD += 0;
$TotalTakloftC += abs($zT);

           }elseif($zT > 0){

                $xT=$zT;
                   $yT=0;
    $TotalTakloftD += $zT;
$TotalTakloftC += 0;

           }

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

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

                   }

        $output .= '
      <tr class="Taklfa">
                                                  <td>'.$xName.'</td>
                                                    <td>'.number_format((float)abs($xT), 2, '.', '').'</td>
                                                    <td>'.number_format((float)abs($yT), 2, '.', '').'</td>

    </tr>
        ';




       }




             }else{


                           $wff=50;
                           $wffx=51;


  $AccountsT=AcccountingManual::orderBy('Code','asc')
      ->where('Code','like', $wff.'%')
      ->orWhere('Code','like', $wffx.'%')
      ->where('Type',$type)->get();


     foreach($AccountsT as $row){

$SubTotalDeb=0;
$SubTotalCred=0;
$suby=0;
$subz=0;
             $count=AcccountingManual::where('Parent',$row->id)->where('Type',1)->count();

          if($count != 0){

             $ASubs=AcccountingManual::where('Parent',$row->id)->where('Type',1)->get();


              foreach($ASubs as $a){

               $SubTotalDeb +=GeneralDaily::where('Account',$a->id)
        ->whereBetween('Date', [$from, $to])
          ->get()->sum('Debitor_Coin');


               $SubTotalCred +=GeneralDaily::where('Account',$a->id)
         ->whereBetween('Date', [$from, $to])
          ->get()->sum('Creditor_Coin');

              }

            $x= $SubTotalDeb  -  $SubTotalCred  ;


                      if($x < 0){

               $suby =0;
               $subz =abs($x);

           }else{

               $suby =$x;
               $subz =0;


           }


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

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

                   }
              $output .= '
                                       <tr class="Taklfa">
                                             <td>'.$xName.'</td>
                                               <td>'.number_format((float)abs($suby), 2, '.', '').'</td>
                                               <td>'.number_format((float)abs($subz), 2, '.', '').'</td>

                                                </tr>

        ';



         }
         }

             }



             $data = array(
       'table_data'  => $output,

      );
      echo json_encode($data);

        }

    }

      }


         function FilterIncom_ListMasrofat(Request $request){

    if($request->ajax())
     {
      $output = '';
      $to = $request->get('To');
      $from = $request->get('From');
      $type = $request->get('Type');
        if($to != null and $to != null and $type != ''){


             if($type == 1){

                    $xM=0;
                   $yM=0;
    $TotalMsrofatD = 0;
$TotalMsrofatC = 0;

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

        if($AMsrfoat->Parent == 0){

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

        }else{

           $wordsss=$AMsrfoat->Code;
           $wordsssX=$AMsrfoat->Code;

        }

$AccountsMasrofat = AcccountingManual::
                 where('Code', 'like', $wordsss.'%')
                 ->orWhere('Code', 'like', $wordsssX.'%')
    ->where('Type', 1)
    ->get();



  foreach($AccountsMasrofat as $rowM)
       {


               $TotalDeb =GeneralDaily::where('Account',$rowM->id)
          ->whereBetween('Date', [$from, $to])
          ->get()->sum('Debitor_Coin');


               $TotalCred =GeneralDaily::where('Account',$rowM->id)
          ->whereBetween('Date', [$from, $to])
          ->get()->sum('Creditor_Coin');


           $zM=$TotalDeb - $TotalCred ;

           if($zM == 0){

                    $xM=0;
                   $yM=0;
    $TotalMsrofatD += 0;
$TotalMsrofatC += 0;
           }elseif($zM < 0){

                $xM=0;
                   $yM=abs($zM);
$TotalMsrofatD += 0;
$TotalMsrofatC += abs($zM);

           }elseif($zM > 0){

                $xM=$zM;
                   $yM=0;
    $TotalMsrofatD += $zM;
$TotalMsrofatC += 0;

           }

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

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

                   }
        $output .= '
      <tr class="Masrofat">
                                                  <td>'.$xName.'</td>
                                                    <td>'.number_format((float)abs($xM), 2, '.', '').'</td>
                                                    <td>'.number_format((float)abs($yM), 2, '.', '').'</td>

    </tr>
        ';




       }




             }else{

                               $wfff=60;
                               $wfffX=61;

  $AccountsF=AcccountingManual::orderBy('Code','asc')
      ->where('Code','like', $wfff.'%')
      ->orWhere('Code','like', $wfffX.'%')
      ->where('Type',$type)->get();


   foreach($AccountsF as $row){

$SubTotalDeb=0;
$SubTotalCred=0;
$suby=0;
$subz=0;
             $count=AcccountingManual::where('Parent',$row->id)->where('Type',1)->count();

          if($count != 0){

             $ASubs=AcccountingManual::where('Parent',$row->id)->where('Type',1)->get();


              foreach($ASubs as $a){

               $SubTotalDeb +=GeneralDaily::where('Account',$a->id)
       ->whereBetween('Date', [$from, $to])
          ->get()->sum('Debitor_Coin');


               $SubTotalCred +=GeneralDaily::where('Account',$a->id)
           ->whereBetween('Date', [$from, $to])
          ->get()->sum('Creditor_Coin');

              }

            $x= $SubTotalDeb  -  $SubTotalCred  ;


                      if($x < 0){

               $suby =0;
               $subz =abs($x);

           }else{

               $suby =$x;
               $subz =0;


           }

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

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

                   }

              $output .= '
                                       <tr class="Masrofat">
                                             <td>'.$xName.'</td>
                                               <td>'.number_format((float)abs($suby), 2, '.', '').'</td>
                                               <td>'.number_format((float)abs($subz), 2, '.', '').'</td>

                                                </tr>

        ';



         }
         }



             }



             $data = array(
       'table_data'  => $output,

      );
      echo json_encode($data);

        }

    }

      }


             //Financial_Center

         public function Financial_CenterPage(){
         return view('admin.AccountsReports.Financial_CenterNew');
    }


      function FilterFinancial_CenterNew(Request $request){

    if($request->ajax())
     {
      $output = '';
      $from = $request->get('From');
      $to = $request->get('To');
      $type = $request->get('Type');
      $coin = $request->get('Coin');


        if( $to != null and $type != ''){

            $AEryd=AcccountingManual::where('id',15)->first();

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

                   }else{
                         $AsName=$AEryd->NameEn;

                   }


         $output .= '
     <tr class="Asoul">
     <td> '.$AsName.' </td>
     <td>
     <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#AsoulDet" onclick="DetailsAsoul()">'.trans("admin.Details").'</button>
     </td>
     <td>  </td>
    </tr>
     ';

        //   =============  Asoul Sabta   ===========
         $ASabta=AcccountingManual::where('id',21)->first();
        if($ASabta->Parent == 0){

          $wordsSabta=$ASabta->Code.'0';

        }else{

           $wordsSabta=$ASabta->Code;

        }

        $TotalDebAsoulSabta = DB::table('acccounting_manuals')
            ->join('general_dailies', function ($join) {

                  $to = request('To');
            $join->on('acccounting_manuals.id', '=', 'general_dailies.Account')
                 ->where('general_dailies.Date', '<=', $to);
        })

          ->where('acccounting_manuals.Code', 'like', $wordsSabta.'%')
                 ->where('acccounting_manuals.Type',  '=',1)
            ->get()->sum('Debitor_Coin');



        $TotalCredAsoulSabta = DB::table('acccounting_manuals')
            ->join('general_dailies', function ($join) {

                 $to = request('To');
            $join->on('acccounting_manuals.id', '=', 'general_dailies.Account')
                 ->where('general_dailies.Date', '<=', $to);
        })

          ->where('acccounting_manuals.Code', 'like', $wordsSabta.'%')
                 ->where('acccounting_manuals.Type',  '=',1)
            ->get()->sum('Creditor_Coin');



           $EgmalyAsoulSabta=$TotalDebAsoulSabta - $TotalCredAsoulSabta ;

            if($EgmalyAsoulSabta < 0){
          $output .= '
   <tr class="Asoul">
   <td>  '.trans('admin.Total_Fixed_Assets').'</td>
<td>0</td>
<td>'.number_format((float)abs($EgmalyAsoulSabta), 2, '.', '').'</td>

   </tr>
     ';
    }else{

                $output .= '
   <tr class="Asoul">
    <td>'.trans('admin.Total_Fixed_Assets').'</td>
<td>'.number_format((float)abs($EgmalyAsoulSabta), 2, '.', '').'</td>
<td>0</td>

   </tr>
     ';

    }

            //   End Asoul Sabta ====================================


              //   =============  Asoul Mtdawla   ===========

                 $Amtdawla=AcccountingManual::where('id',22)->first();

        if($Amtdawla->Parent == 0){

          $wordsMtdawla=$Amtdawla->Code.'0';

        }else{

           $wordsMtdawla=$Amtdawla->Code;

        }

              $TotalDebAsoulMtadawla = DB::table('acccounting_manuals')
            ->join('general_dailies', function ($join) {

                  $to = request('To');
            $join->on('acccounting_manuals.id', '=', 'general_dailies.Account')
                 ->where('general_dailies.Date', '<=', $to);
        })

          ->where('acccounting_manuals.Code', 'like', $wordsMtdawla.'%')
                 ->where('acccounting_manuals.Type',  '=',1)
            ->get()->sum('Debitor_Coin');



        $TotalCredAsoulMtadawla = DB::table('acccounting_manuals')
            ->join('general_dailies', function ($join) {

                 $to = request('To');
            $join->on('acccounting_manuals.id', '=', 'general_dailies.Account')
                 ->where('general_dailies.Date', '<=', $to);
        })

          ->where('acccounting_manuals.Code', 'like', $wordsMtdawla.'%')
                 ->where('acccounting_manuals.Type',  '=',1)
            ->get()->sum('Creditor_Coin');



           $EgmalyAsoulMtadawla=$TotalDebAsoulMtadawla - $TotalCredAsoulMtadawla ;


   if($EgmalyAsoulMtadawla < 0){
          $output .= '
   <tr class="Asoul">
   <td>   '.trans('admin.Total_Current_Assets').'</td>
<td>0</td>
<td>'.number_format((float)abs($EgmalyAsoulMtadawla), 2, '.', '').'</td>

   </tr>
     ';
    }else{

                $output .= '
   <tr class="Asoul">
    <td>  '.trans('admin.Total_Current_Assets').'</td>
<td>'.number_format((float)abs($EgmalyAsoulMtadawla), 2, '.', '').'</td>
<td>0</td>

   </tr>
     ';

    }


              //   End Asoul Mtdawla  ====================================


              //   =============  Asoul Okhra   ===========

                    $AOther=AcccountingManual::where('id',147)->first();

        if($AOther->Parent == 0){

          $wordsOther=$AOther->Code.'0';

        }else{

           $wordsOther=$AOther->Code;

        }


                $TotalDebAsoulOkhraa = DB::table('acccounting_manuals')
            ->join('general_dailies', function ($join) {

                  $to = request('To');
            $join->on('acccounting_manuals.id', '=', 'general_dailies.Account')
                 ->where('general_dailies.Date', '<=', $to);
        })

          ->where('acccounting_manuals.Code', 'like', $wordsOther.'%')
                 ->where('acccounting_manuals.Type',  '=',1)
            ->get()->sum('Debitor_Coin');



        $TotalCredAsoulOkhraa = DB::table('acccounting_manuals')
            ->join('general_dailies', function ($join) {

                 $to = request('To');
            $join->on('acccounting_manuals.id', '=', 'general_dailies.Account')
                 ->where('general_dailies.Date', '<=', $to);
        })

          ->where('acccounting_manuals.Code', 'like', $wordsOther.'%')
                 ->where('acccounting_manuals.Type',  '=',1)
            ->get()->sum('Creditor_Coin');



           $EgmalyAsoulOkhraa=$TotalDebAsoulOkhraa - $TotalCredAsoulOkhraa ;

   if($EgmalyAsoulOkhraa < 0){
          $output .= '
   <tr class="Asoul">
   <td>  '.trans('admin.Total_Other_Assets').'</td>
<td>0</td>
<td>'.number_format((float)abs($EgmalyAsoulOkhraa), 2, '.', '').'</td>

   </tr>
     ';
    }else{

                $output .= '
   <tr class="Asoul">
    <td>  '.trans('admin.Total_Other_Assets').'</td>
<td>'.number_format((float)abs($EgmalyAsoulOkhraa), 2, '.', '').'</td>
<td>0</td>

   </tr>
     ';

    }

             //   End Asoul Okhra  ====================================

             //  Asoul  ======================================
                $EgmalyAsoul=$EgmalyAsoulSabta + $EgmalyAsoulMtadawla + $EgmalyAsoulOkhraa ;
      if($EgmalyAsoul < 0){
          $output .= '
   <tr class="Asoul">
   <td> '.trans('admin.Total_Assets').'</td>
<td>0</td>
<td>'.number_format((float)abs($EgmalyAsoul), 2, '.', '').'</td>

   </tr>
     ';
    }else{

                $output .= '
   <tr class="Asoul">
    <td> '.trans('admin.Total_Assets').'</td>
<td>'.number_format((float)abs($EgmalyAsoul), 2, '.', '').'</td>
<td>0</td>

   </tr>
     ';

    }

    //  Asoul End ======================================


            //  Khsoum  =========================


$ATaklfa=AcccountingManual::where('id',16)->first();

        if($ATaklfa->Parent == 0){

          $wordss=$ATaklfa->Code.'0';

        }else{

           $wordss=$ATaklfa->Code;

        }

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

                   }else{
                         $KhsoumName=$ATaklfa->NameEn;

                   }

$output .= '
     <tr class="Khsoum" >
     <td> '.$KhsoumName.' </td>
    <td>
     <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#KhsoumDet" onclick="DetailsKhsoum()">'.trans("admin.Details").'</button>
     </td>
     <td>  </td>
    </tr>
     ';


               $TotalDebKhsoum = DB::table('acccounting_manuals')
            ->join('general_dailies', function ($join) {

                  $to = request('To');
            $join->on('acccounting_manuals.id', '=', 'general_dailies.Account')
                 ->where('general_dailies.Date', '<=', $to);
        })

          ->where('acccounting_manuals.Code', 'like', $wordss.'%')
                 ->where('acccounting_manuals.Type',  '=',1)
            ->get()->sum('Debitor_Coin');



        $TotalCredKhsoum = DB::table('acccounting_manuals')
            ->join('general_dailies', function ($join) {

                 $to = request('To');
            $join->on('acccounting_manuals.id', '=', 'general_dailies.Account')
                 ->where('general_dailies.Date', '<=', $to);
        })

          ->where('acccounting_manuals.Code', 'like', $wordss.'%')
                 ->where('acccounting_manuals.Type',  '=',1)
            ->get()->sum('Creditor_Coin');



           $EgmalyKhsoum= $TotalCredKhsoum  - $TotalDebKhsoum ;

    if($EgmalyKhsoum < 0){
          $output .= '
   <tr class="Khsoum">
    <td>  '.trans('admin.Total_Liabilities').'</td>
<td>'.number_format((float)abs($EgmalyKhsoum), 2, '.', '').'</td>
<td>0</td>
   </tr>
     ';
    }else{

                $output .= '
   <tr class="Khsoum">
  <td>  '.trans('admin.Total_Liabilities').'</td>
<td>0</td>
<td>'.number_format((float)abs($EgmalyKhsoum), 2, '.', '').'</td>
   </tr>
     ';

    }


              // End  Khsoum  =========================


               //  Khsoum Tawela  =========================

                    $ATaklfaTweel=AcccountingManual::where('id',148)->first();

        if($ATaklfaTweel->Parent == 0){

          $wordssTweel=$ATaklfaTweel->Code.'0';

        }else{

           $wordssTweel=$ATaklfaTweel->Code;

        }


                $TotalDebKhsoumTweel = DB::table('acccounting_manuals')
            ->join('general_dailies', function ($join) {

                  $to = request('To');
            $join->on('acccounting_manuals.id', '=', 'general_dailies.Account')
                 ->where('general_dailies.Date', '<=', $to);
        })

          ->where('acccounting_manuals.Code', 'like', $wordssTweel.'%')
                 ->where('acccounting_manuals.Type',  '=',1)
            ->get()->sum('Debitor_Coin');



        $TotalCredKhsoumTweel = DB::table('acccounting_manuals')
            ->join('general_dailies', function ($join) {

                 $to = request('To');
            $join->on('acccounting_manuals.id', '=', 'general_dailies.Account')
                 ->where('general_dailies.Date', '<=', $to);
        })

          ->where('acccounting_manuals.Code', 'like', $wordssTweel.'%')
                 ->where('acccounting_manuals.Type',  '=',1)
            ->get()->sum('Creditor_Coin');



           $EgmalyKhsoumTweel= $TotalCredKhsoumTweel  - $TotalDebKhsoumTweel ;



             if($EgmalyKhsoumTweel < 0){
          $output .= '
   <tr class="Khsoum">
    <td>    '.trans('admin.Total_longterm_liabilities').'</td>
<td>'.number_format((float)abs($EgmalyKhsoumTweel), 2, '.', '').'</td>
<td>0</td>
   </tr>
     ';
    }else{

                $output .= '
   <tr class="Khsoum">
  <td>  '.trans('admin.Total_longterm_liabilities').'</td>
<td>0</td>
<td>'.number_format((float)abs($EgmalyKhsoumTweel), 2, '.', '').'</td>
   </tr>
     ';

    }

                  //  End Khsoum Tweel ========================

                  //   Khsoum Qaserr ========================

  $EgmalyKhsoumQaserr= $EgmalyKhsoum -  $EgmalyKhsoumTweel;

    if($EgmalyKhsoumQaserr < 0){
          $output .= '
   <tr class="Khsoum">
    <td> '.trans('admin.Total_shortterm_liabilities').'</td>
<td>'.number_format((float)abs($EgmalyKhsoumQaserr), 2, '.', '').'</td>
<td>0</td>
   </tr>
     ';
    }else{

                $output .= '
   <tr class="Khsoum">
  <td>  '.trans('admin.Total_shortterm_liabilities').'</td>
<td>0</td>
<td>'.number_format((float)abs($EgmalyKhsoumQaserr), 2, '.', '').'</td>
   </tr>
     ';

    }

                  //  End Khsoum Qaserr ========================

              //  Ras Mal #aml + Estsmar ========================

                        $RasMal3aml=$EgmalyAsoulMtadawla - $EgmalyKhsoumQaserr;

                          $output .= '
   <tr class="gray">
     <td>'.trans('admin.Working_Capital').'</td>
<td style="border: none;text-align: end;">'.number_format((float)abs($RasMal3aml), 2, '.', '').'</td>
<td style="border: none;text-align: end;"></td>
   </tr>
     ';
           $Estsmar=$RasMal3aml + $EgmalyAsoulSabta + $EgmalyAsoulOkhraa ;

    $output .= '
   <tr class="gray">
     <td> '.trans('admin.Total_Investment').'</td>
<td style="border: none;text-align: end;">'. number_format((float)abs($Estsmar), 2, '.', '') .'</td>
<td style="border: none;text-align: end;"></td>
   </tr>
     ';

   // End  Ras Mal #aml + Estsmar ========================



        // Hkook Malkya ============================




    $AMsrfoat=AcccountingManual::where('id',17)->first();

        if($AMsrfoat->Parent == 0){

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

        }else{

           $wordsss=$AMsrfoat->Code;

        }


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

                   }else{
$MName=$AMsrfoat->NameEn;

                   }

$output .= '
     <tr class="Hkook">
     <td> '.$MName.' </td>
        <td>
     <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#HkookDet" onclick="DetailsHkook()">'.trans("admin.Details").'</button>
     </td>
     <td>  </td>
    </tr>
     ';


            //Safy Rab7 w Khsara ==================


       $AErydaaat=AcccountingManual::where('id',18)->first();

        if($AErydaaat->Parent == 0){

          $wordsX=$AErydaaat->Code.'0';

        }else{

           $wordsX=$AEryd->Code;

        }


    $ATaklfaaat=AcccountingManual::where('id',19)->first();

        if($ATaklfaaat->Parent == 0){

          $wordssX=$ATaklfaaat->Code.'0';

        }else{

           $wordssX=$ATaklfaaat->Code;

        }


        $AMasroffffffffat=AcccountingManual::where('id',20)->first();

        if($AMasroffffffffat->Parent == 0){

          $wordsssX=$AMasroffffffffat->Code.'0';

        }else{

           $wordsssX=$AMasroffffffffat->Code;

        }


              $TotalDebErydat = DB::table('acccounting_manuals')
            ->join('general_dailies', function ($join) {

                  $to = request('To');
            $join->on('acccounting_manuals.id', '=', 'general_dailies.Account')
                 ->where('general_dailies.Date', '<=', $to);
        })

          ->where('acccounting_manuals.Code', 'like', $wordsX.'%')
                 ->where('acccounting_manuals.Type',  '=',1)
            ->get()->sum('Debitor_Coin');



        $TotalCredErydat = DB::table('acccounting_manuals')
            ->join('general_dailies', function ($join) {

                 $to = request('To');
            $join->on('acccounting_manuals.id', '=', 'general_dailies.Account')
                 ->where('general_dailies.Date', '<=', $to);
        })

          ->where('acccounting_manuals.Code', 'like', $wordsX.'%')
                 ->where('acccounting_manuals.Type',  '=',1)
            ->get()->sum('Creditor_Coin');

        $EgmalyErydat=$TotalCredErydat - $TotalDebErydat  ;




              $TotalDebTaklfaat = DB::table('acccounting_manuals')
            ->join('general_dailies', function ($join) {

                  $to = request('To');
            $join->on('acccounting_manuals.id', '=', 'general_dailies.Account')
                 ->where('general_dailies.Date', '<=', $to);
        })

          ->where('acccounting_manuals.Code', 'like', $wordssX.'%')
                 ->where('acccounting_manuals.Type',  '=',1)
            ->get()->sum('Debitor_Coin');



        $TotalCredTaklfaat = DB::table('acccounting_manuals')
            ->join('general_dailies', function ($join) {

                 $to = request('To');
            $join->on('acccounting_manuals.id', '=', 'general_dailies.Account')
                 ->where('general_dailies.Date', '<=', $to);
        })

          ->where('acccounting_manuals.Code', 'like', $wordssX.'%')
                 ->where('acccounting_manuals.Type',  '=',1)
            ->get()->sum('Creditor_Coin');

        $EgmalyTaklfaat=$TotalDebTaklfaat - $TotalCredTaklfaat  ;


           $TotalDebMasrofaat = DB::table('acccounting_manuals')
            ->join('general_dailies', function ($join) {

                  $to = request('To');
            $join->on('acccounting_manuals.id', '=', 'general_dailies.Account')
                 ->where('general_dailies.Date', '<=', $to);
        })

          ->where('acccounting_manuals.Code', 'like', $wordsssX.'%')
                 ->where('acccounting_manuals.Type',  '=',1)
            ->get()->sum('Debitor_Coin');



        $TotalCredMasrofaat = DB::table('acccounting_manuals')
            ->join('general_dailies', function ($join) {

                 $to = request('To');
            $join->on('acccounting_manuals.id', '=', 'general_dailies.Account')
                 ->where('general_dailies.Date', '<=', $to);
        })

          ->where('acccounting_manuals.Code', 'like', $wordsssX.'%')
                 ->where('acccounting_manuals.Type',  '=',1)
            ->get()->sum('Creditor_Coin');

        $EgmalyMasrofaat=$TotalDebMasrofaat - $TotalCredMasrofaat  ;


        $fg= $EgmalyTaklfaat + $EgmalyMasrofaat;
        if($EgmalyErydat >  $fg){
         if($fg  <  0 ){

            $SafyRab7 =$EgmalyErydat + ($EgmalyTaklfaat  +   $EgmalyMasrofaat)  ;
        }else{

              $SafyRab7 = $EgmalyErydat -  ($EgmalyTaklfaat  +   $EgmalyMasrofaat)  ;

        }
        }elseif($EgmalyErydat <  $fg){

        if($fg  <  0 ){

            $SafyRab7 =$EgmalyErydat + ($EgmalyTaklfaat  +   $EgmalyMasrofaat)  ;
        }else{

              $SafyRab7 = $EgmalyErydat -  ($EgmalyTaklfaat  +   $EgmalyMasrofaat)  ;

        }


        }elseif($EgmalyErydat ==  $fg){

           $SafyRab7 = $EgmalyErydat -  ($EgmalyTaklfaat  +   $EgmalyMasrofaat)  ;

        }

          $output .= '
   <tr class="Hkook">
     <td>'.trans('admin.Net_Profit_Loss').'</td>
<td style="border: none;text-align: end;">'.number_format((float)($SafyRab7), 2, '.', '').'</td>
<td style="border: none;text-align: end;"></td>
   </tr>
     ';


            //End Safy Rab7 w Khsara ==================


               $TotalDebHkook = DB::table('acccounting_manuals')
            ->join('general_dailies', function ($join) {

                  $to = request('To');
            $join->on('acccounting_manuals.id', '=', 'general_dailies.Account')
                 ->where('general_dailies.Date', '<=', $to);
        })

          ->where('acccounting_manuals.Code', 'like', $wordsss.'%')
                 ->where('acccounting_manuals.Type',  '=',1)
            ->get()->sum('Debitor_Coin');



        $TotalCredHkook = DB::table('acccounting_manuals')
            ->join('general_dailies', function ($join) {

                 $to = request('To');
            $join->on('acccounting_manuals.id', '=', 'general_dailies.Account')
                 ->where('general_dailies.Date', '<=', $to);
        })

          ->where('acccounting_manuals.Code', 'like', $wordsss.'%')
                 ->where('acccounting_manuals.Type',  '=',1)
            ->get()->sum('Creditor_Coin');




      $EgmalyHkook=($TotalCredHkook - $TotalDebHkook) + $SafyRab7 ;

      if($EgmalyHkook < 0){
          $output .= '
   <tr class="Hkook">
      <td>'.trans('admin.Total_Rights').'</td>
<td>'.number_format((float)abs($EgmalyHkook), 2, '.', '').'</td>
<td>0</td>
   </tr>
     ';
    }else{

                $output .= '
   <tr class="Hkook">
      <td> '.trans('admin.Total_Rights').'</td>
<td>0</td>
<td>'.number_format((float)abs($EgmalyHkook), 2, '.', '').'</td>
   </tr>
     ';

    }




        // End Hkook Malkya ============================

            $xv= $EgmalyKhsoumTweel + $EgmalyHkook;


              $output .= '
   <tr class="Fark">
     <td>  '.trans('admin.Total_Rights_longterm').'</td>
<td style="border: none;text-align: end;">'.number_format((float)abs($xv), 2, '.', '').'</td>
<td style="border: none;text-align: end;"></td>
   </tr>
     ';

 $Result = $EgmalyAsoul - ($EgmalyKhsoum + $EgmalyHkook);

             $output .= '
   <tr class="DIFFERENECE">
     <td>     '.trans('admin.Dif_Between_Them').' </td>
<td style="border: none;text-align: end;">'.number_format((float)abs($Result), 2, '.', '').'</td>
<td style="border: none;text-align: end;"></td>
   </tr>
     ';



     $data = array(
       'table_data'  => $output,
      );
      echo json_encode($data);

        }
      }
      }


      function FilterFinancial_CenterAsoul(Request $request){

    if($request->ajax())
     {
      $output = '';
      $to = $request->get('To');
      $type = $request->get('Type');
        if( $to != null and $type != ''){
                $AEryd=AcccountingManual::where('id',15)->first();

        if($AEryd->Parent == 0){

          $words=$AEryd->Code.'0';

        }else{

           $words=$AEryd->Code;

        }

        $AccountsErydat = AcccountingManual::where('Code', 'like', $words.'%')
    ->where('Type', 1)
    ->get();

             if($type == 1){

                              $x=0;
                   $y=0;
    $TotalErydatD = 0;
$TotalErydatC = 0;

  foreach($AccountsErydat as $row)
       {


               $TotalDeb =GeneralDaily::where('Account',$row->id)
            ->where('Date','<=' , $to)
          ->get()->sum('Debitor_Coin');


               $TotalCred =GeneralDaily::where('Account',$row->id)
          ->where('Date','<=' , $to)
          ->get()->sum('Creditor_Coin');


           $z=$TotalDeb - $TotalCred ;

           if($z == 0){

                    $x=0;
                   $y=0;
    $TotalErydatD += 0;
$TotalErydatC += 0;
           }elseif($z < 0){

                $x=0;
                   $y=abs($z);
$TotalErydatD += 0;
$TotalErydatC += abs($z);

           }elseif($z > 0){

                $x=$z;
                   $y=0;
    $TotalErydatD += $z;
$TotalErydatC += 0;

           }

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

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

                   }


        $output .= '
      <tr class="Asoul">
                                                  <td>'.$xName.'</td>
                                                    <td>'.number_format((float)abs($x), 2, '.', '').'</td>
                                                    <td>'.number_format((float)abs($y), 2, '.', '').'</td>


    </tr>
        ';


       }


             }else{
                  $wx=1010;
        $wxx=1020;
        $wxxx=1030;
      $AccountsX=AcccountingManual::orderBy('Code','asc')->where('Code','like', $wx.'%')->where('Type',$type)->get();
  $AccountsXX=AcccountingManual::orderBy('Code','asc')->where('Code','like', $wxx.'%')->where('Type',$type)->get();
  $AccountsXXX=AcccountingManual::orderBy('Code','asc')->where('Code','like', $wxxx.'%')->where('Type',$type)->get();


             $output .= '
     <tr class="AlAsoulSabta">
     <td>  '.trans('admin.Fixed_Assets').' </td>
     <td>  </td>
     <td>  </td>
    </tr>
     ';

          foreach($AccountsX as $row){

$SubTotalDeb=0;
$SubTotalCred=0;
$suby=0;
$subz=0;
             $count=AcccountingManual::where('Parent',$row->id)->where('Type',1)->count();

          if($count != 0){

             $ASubs=AcccountingManual::where('Parent',$row->id)->where('Type',1)->get();


              foreach($ASubs as $a){

               $SubTotalDeb +=GeneralDaily::where('Account',$a->id)
           ->where('Date','<=' , $to)
          ->get()->sum('Debitor_Coin');


               $SubTotalCred +=GeneralDaily::where('Account',$a->id)
           ->where('Date','<=' , $to)
          ->get()->sum('Creditor_Coin');

              }

            $x= $SubTotalDeb  -  $SubTotalCred  ;


                      if($x < 0){

               $suby =0;
               $subz =abs($x);

           }else{

               $suby =$x;
               $subz =0;


           }

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

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

                   }


              $output .= '
                                       <tr class="AlAsoulSabta">
                                             <td>'.$xName.'</td>
                                               <td>'.number_format((float)abs($suby), 2, '.', '').'</td>
                                               <td>'.number_format((float)abs($subz), 2, '.', '').'</td>

                                                </tr>

        ';



         }
         }


                 $output .= '
     <tr class="AlAsoulMtdawla">
     <td>  '.trans('admin.Traded_Assets').' </td>
     <td>  </td>
     <td>  </td>
    </tr>
     ';

      foreach($AccountsXX as $row){

$SubTotalDeb=0;
$SubTotalCred=0;
$suby=0;
$subz=0;
             $count=AcccountingManual::where('Parent',$row->id)->where('Type',1)->count();

          if($count != 0){

             $ASubs=AcccountingManual::where('Parent',$row->id)->where('Type',1)->get();


              foreach($ASubs as $a){

               $SubTotalDeb +=GeneralDaily::where('Account',$a->id)
           ->where('Date','<=' , $to)
          ->get()->sum('Debitor_Coin');


               $SubTotalCred +=GeneralDaily::where('Account',$a->id)
           ->where('Date','<=' , $to)
          ->get()->sum('Creditor_Coin');

              }

            $x= $SubTotalDeb  -  $SubTotalCred  ;


                      if($x < 0){

               $suby =0;
               $subz =abs($x);

           }else{

               $suby =$x;
               $subz =0;


           }


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

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

                   }

              $output .= '
                                       <tr class="AlAsoulMtdawla">
                                             <td>'.$xName.'</td>
                                               <td>'.number_format((float)abs($suby), 2, '.', '').'</td>
                                               <td>'.number_format((float)abs($subz), 2, '.', '').'</td>

                                                </tr>

        ';



         }
         }

                      $output .= '
     <tr class="AlAsoulOkhra">
     <td>   '.trans('admin.Other_Assets').' </td>
     <td>  </td>
     <td>  </td>
    </tr>
     ';

          foreach($AccountsXXX as $row){

$SubTotalDeb=0;
$SubTotalCred=0;
$suby=0;
$subz=0;
             $count=AcccountingManual::where('Parent',$row->id)->where('Type',1)->count();

          if($count != 0){

             $ASubs=AcccountingManual::where('Parent',$row->id)->where('Type',1)->get();


              foreach($ASubs as $a){

               $SubTotalDeb +=GeneralDaily::where('Account',$a->id)
           ->where('Date','<=' , $to)
          ->get()->sum('Debitor_Coin');


               $SubTotalCred +=GeneralDaily::where('Account',$a->id)
           ->where('Date','<=' , $to)
          ->get()->sum('Creditor_Coin');

              }

            $x= $SubTotalDeb  -  $SubTotalCred  ;


                      if($x < 0){

               $suby =0;
               $subz =abs($x);

           }else{

               $suby =$x;
               $subz =0;


           }


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

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

                   }
              $output .= '
                                       <tr class="AlAsoulOkhra">
                                             <td>'.$xName.'</td>
                                               <td>'.number_format((float)abs($suby), 2, '.', '').'</td>
                                               <td>'.number_format((float)abs($subz), 2, '.', '').'</td>

                                                </tr>

        ';



         }
         }



             }



             $data = array(
       'table_data'  => $output,

      );
      echo json_encode($data);

        }

    }

      }


          function FilterFinancial_CenterKhsoum(Request $request){

    if($request->ajax())
     {
      $output = '';
      $to = $request->get('To');
      $type = $request->get('Type');
        if( $to != null and $type != ''){

             if($type == 1){
                        $xT=0;
                   $yT=0;
    $TotalTakloftD = 0;
$TotalTakloftC = 0;
    $ATaklfa=AcccountingManual::where('id',16)->first();

        if($ATaklfa->Parent == 0){

          $wordss=$ATaklfa->Code.'0';

        }else{

           $wordss=$ATaklfa->Code;

        }

$AccountsTakolfat = AcccountingManual::where('Code', 'like', $wordss.'%')
    ->where('Type', 1)
    ->get();


      foreach($AccountsTakolfat as $rowT)
       {


               $TotalDeb =GeneralDaily::where('Account',$rowT->id)
         ->where('Date','<=' , $to)
          ->get()->sum('Debitor_Coin');


               $TotalCred =GeneralDaily::where('Account',$rowT->id)
         ->where('Date','<=' , $to)
          ->get()->sum('Creditor_Coin');


           $zT=$TotalDeb - $TotalCred ;

           if($zT == 0){

                    $xT=0;
                   $yT=0;
    $TotalTakloftD += 0;
$TotalTakloftC += 0;
           }elseif($zT < 0){

                $xT=0;
                   $yT=abs($zT);
$TotalTakloftD += 0;
$TotalTakloftC += abs($zT);

           }elseif($zT > 0){

                $xT=$zT;
                   $yT=0;
    $TotalTakloftD += $zT;
$TotalTakloftC += 0;

           }

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

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

                   }

        $output .= '
      <tr class="Khsoum">
                                                  <td>'.$xName.'</td>
                                                    <td>'.number_format((float)abs($xT), 2, '.', '').'</td>
                                                    <td>'.number_format((float)abs($yT), 2, '.', '').'</td>

    </tr>
        ';




       }


             }else{

           $wff=20;
        $wffx=2070;

  $AccountsT=AcccountingManual::orderBy('Code','asc')->where('Code','like', $wff.'%')->where('Type',$type)->get();
  $AccountsTT=AcccountingManual::orderBy('Code','asc')->where('Code','like', $wffx.'%')->where('Type',$type)->get();


                      $output .= '
     <tr>
     <td> '.trans('admin.shortterm_opponents').'</td>
     <td>  </td>
     <td>  </td>
    </tr>
     ';

      foreach($AccountsT as $row){

$SubTotalDeb=0;
$SubTotalCred=0;
$suby=0;
$subz=0;
             $count=AcccountingManual::where('Parent',$row->id)->where('Type',1)->count();

          if($count != 0){

             $ASubs=AcccountingManual::where('Parent',$row->id)->where('Type',1)->get();


              foreach($ASubs as $a){

               $SubTotalDeb +=GeneralDaily::where('Account',$a->id)
           ->where('Date','<=' , $to)
          ->get()->sum('Debitor_Coin');


               $SubTotalCred +=GeneralDaily::where('Account',$a->id)
           ->where('Date','<=' , $to)
          ->get()->sum('Creditor_Coin');

              }

            $x= $SubTotalDeb  -  $SubTotalCred  ;


                      if($x < 0){

               $suby =0;
               $subz =abs($x);

           }else{

               $suby =$x;
               $subz =0;


           }

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

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

                   }

              $output .= '
                                       <tr>
                                             <td>'.$xName.'</td>
                                               <td>'.number_format((float)abs($suby), 2, '.', '').'</td>
                                               <td>'.number_format((float)abs($subz), 2, '.', '').'</td>

                                                </tr>

        ';



         }
         }


            foreach($AccountsTT as $row){

$SubTotalDeb=0;
$SubTotalCred=0;
$suby=0;
$subz=0;
             $count=AcccountingManual::where('Parent',$row->id)->where('Type',1)->count();

          if($count != 0){

             $ASubs=AcccountingManual::where('Parent',$row->id)->where('Type',1)->get();


              foreach($ASubs as $a){

               $SubTotalDeb +=GeneralDaily::where('Account',$a->id)
           ->where('Date','<=' , $to)
          ->get()->sum('Debitor_Coin');


               $SubTotalCred +=GeneralDaily::where('Account',$a->id)
           ->where('Date','<=' , $to)
          ->get()->sum('Creditor_Coin');

              }

            $x= $SubTotalDeb  -  $SubTotalCred  ;


                      if($x < 0){

               $suby =0;
               $subz =abs($x);

           }else{

               $suby =$x;
               $subz =0;


           }


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

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

                   }

              $output .= '
                                       <tr>
                                             <td>'.$xName.'</td>
                                               <td>'.number_format((float)abs($suby), 2, '.', '').'</td>
                                               <td>'.number_format((float)abs($subz), 2, '.', '').'</td>

                                                </tr>

        ';



         }
         }



             }



             $data = array(
       'table_data'  => $output,

      );
      echo json_encode($data);

        }

    }

      }


          function FilterFinancial_CenterHkook(Request $request){

    if($request->ajax())
     {
      $output = '';
      $to = $request->get('To');
      $type = $request->get('Type');
        if( $to != null and $type != ''){

             if($type == 1){
               $xM=0;
                   $yM=0;
    $TotalMsrofatD = 0;
$TotalMsrofatC = 0;
    $AMsrfoat=AcccountingManual::where('id',17)->first();

        if($AMsrfoat->Parent == 0){

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

        }else{

           $wordsss=$AMsrfoat->Code;

        }

$AccountsMasrofat = AcccountingManual::where('Code', 'like', $wordsss.'%')
    ->where('Type', 1)
    ->get();

       foreach($AccountsMasrofat as $rowM)
       {


               $TotalDeb =GeneralDaily::where('Account',$rowM->id)
          ->where('Date','<=' , $to)
          ->get()->sum('Debitor_Coin');


               $TotalCred =GeneralDaily::where('Account',$rowM->id)
           ->where('Date','<=' , $to)
          ->get()->sum('Creditor_Coin');


           $zM=$TotalDeb - $TotalCred ;

           if($zM == 0){

                    $xM=0;
                   $yM=0;
    $TotalMsrofatD += 0;
$TotalMsrofatC += 0;
           }elseif($zM < 0){

                $xM=0;
                   $yM=abs($zM);
$TotalMsrofatD += 0;
$TotalMsrofatC += abs($zM);

           }elseif($zM > 0){

                $xM=$zM;
                   $yM=0;
    $TotalMsrofatD += $zM;
$TotalMsrofatC += 0;

           }

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

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

                   }


        $output .= '
      <tr class="Hkook">
                                                  <td>'.$xName.'</td>
                                                    <td>'.number_format((float)abs($xM), 2, '.', '').'</td>
                                                    <td>'.number_format((float)abs($yM), 2, '.', '').'</td>

    </tr>
        ';




       }


             }else{
       $wfff=30;
       $wfffx=31;
  $AccountsF=AcccountingManual::orderBy('Code','asc')
      ->where('Code','like', $wfff.'%')
            ->orWhere('Code','like', $wfffx.'%')
      ->where('Type',$type)->get();


               foreach($AccountsF as $row){

$SubTotalDeb=0;
$SubTotalCred=0;
$suby=0;
$subz=0;
             $count=AcccountingManual::where('Parent',$row->id)->where('Type',1)->count();



          if($count != 0){

             $ASubs=AcccountingManual::where('Parent',$row->id)->where('Type',1)->get();

              foreach($ASubs as $a){


               $SubTotalDeb +=GeneralDaily::where('Account',$a->id)
           ->where('Date','<=' , $to)
          ->get()->sum('Debitor_Coin');


               $SubTotalCred +=GeneralDaily::where('Account',$a->id)
           ->where('Date','<=' , $to)
          ->get()->sum('Creditor_Coin');

              }



            $x= $SubTotalDeb  -  $SubTotalCred  ;


                      if($x < 0){

               $suby =0;
               $subz =abs($x);

           }else{

               $suby =$x;
               $subz =0;


           }

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

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

                   }

              $output .= '
                                       <tr class="HkokMlkya">
                                             <td>'.$xName.'</td>
                                               <td>'.$suby.'</td>
                                               <td>'.$subz.'</td>

                                                </tr>

        ';



         }
         }

             }



             $data = array(
       'table_data'  => $output,

      );
      echo json_encode($data);

        }

    }

      }


    //Safes_BalancesPage
       public function Safes_BalancesPage(){

        $Safes = AcccountingManual::
             where('Type',1)
              ->where('Parent',28)
              ->orWhere('Parent',29)
              ->get();

           $Coins=Coins::all();
         return view('admin.AccountsReports.Safes_Balances',get_defined_vars());
    }


    function FilterSafes_Balances(Request $request)
    {
     if($request->ajax())
     {
      $output = '';
       $from = $request->get('From');
       $to = $request->get('To');
       $safe = $request->get('Safe');
       $Coin = $request->get('Coin');

              $Safes = AcccountingManual::
             where('Type',1)
              ->where('Parent',28)
              ->orWhere('Parent',29)
              ->get();

     if(!empty($Coin)){
       $co=Coins::find($Coin);
     }else{
        $co=Coins::find(1);
     }


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

          foreach($Safes as $safet){

        if($safe != ''){

            if($from != '' and $to != ''){

                  if($safet->id == $safe){

              $debt=GeneralDaily::
                      whereBetween('Date',[$from,$to])
                      ->where('Account',$safet->id)->get()->sum('Debitor');
           $crdt=GeneralDaily::
                      whereBetween('Date',[$from,$to])
                      ->where('Account',$safet->id)->get()->sum('Creditor');

            $dif=$debt - $crdt ;
               $nun=number_format((float)abs($dif), 2, '.', '');
                if($dif > 0){


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

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

                   }


                        $output .= '

               <tr>
               <td class="right-color">'.$xName.'</td>
               <td class="left-color">'.$nun.'
               <input class="AMOUNT" type="hidden" value="'.$nun.'">
                <input class="AMOUNTMinus" type="hidden" value="0">
               </td>
                        <td>
               '.$nun / $co->Draw .'
               </td>
               <tr>
               ';

                }else{

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

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

                   }

                    $output .= '

               <tr>
               <td class="right-color">'.$xName.'</td>
               <td class="left-color">('.$nun.')
              <input class="AMOUNTMinus" type="hidden" value="'.$nun.'">
             <input class="AMOUNT" type="hidden" value="0">
               </td>
               <td>
               ('.$nun / $co->Draw.')
               </td>
               <tr>
               ';
                }



            }


            }else{

            if($safet->id == $safe){

              $debt=GeneralDaily::where('Account',$safet->id)->get()->sum('Debitor');
           $crdt=GeneralDaily::where('Account',$safet->id)->get()->sum('Creditor');

            $dif=$debt - $crdt ;
              $nun=number_format((float)abs($dif), 2, '.', '');

               if($dif > 0){


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

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

                   }

                            $output .= '

               <tr>
               <td class="right-color">'.$xName.'</td>
               <td class="left-color">'.$nun.'
                      <input class="AMOUNT" type="hidden" value="'.$nun.'">
                <input class="AMOUNTMinus" type="hidden" value="0">
               </td>
                         <td>
               '.$nun / $co->Draw .'
               </td>
               <tr>
               ';

               }else{

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

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

                   }

                               $output .= '

               <tr>
               <td class="right-color">'.$xName.'</td>
               <td class="left-color">('.$nun.')
                    <input class="AMOUNTMinus" type="hidden" value="'.$nun.'">
             <input class="AMOUNT" type="hidden" value="0">
               </td>
           <td>
               ('.$nun / $co->Draw.')
               </td>
               <tr>
               ';

               }


            }
            }

        }else{

                 if($from != '' and $to != ''){

                           $debt=GeneralDaily::
                      whereBetween('Date',[$from,$to])
                     ->where('Account',$safet->id)->get()->sum('Debitor');
           $crdt=GeneralDaily::
                      whereBetween('Date',[$from,$to])
                     ->where('Account',$safet->id)->get()->sum('Creditor');

            $dif=$debt - $crdt ;

                $nun=number_format((float)abs($dif), 2, '.', '');

               if($dif > 0){
                                if(app()->getLocale() == 'ar' ){
                      $xName=$safet->Name;

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

                   }
                            $output .= '

               <tr>
               <td class="right-color">'.$xName.'</td>
               <td class="left-color">'.$nun.'
                 <input class="AMOUNT" type="hidden" value="'.$nun.'">
                <input class="AMOUNTMinus" type="hidden" value="0">
               </td>
                            <td>
               '.$nun / $co->Draw .'
               </td>
               <tr>
               ';

               }else{
                                   if(app()->getLocale() == 'ar' ){
                      $xName=$safet->Name;

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

                   }
                               $output .= '

               <tr>
               <td class="right-color">'.$xName.'</td>
               <td class="left-color">('.$nun.')
            <input class="AMOUNTMinus" type="hidden" value="'.$nun.'">
             <input class="AMOUNT" type="hidden" value="0">
               </td>
                   <td>
               ('.$nun / $co->Draw.')
               </td>
               <tr>
               ';

               }

                 }else{

              $debt=GeneralDaily::where('Account',$safet->id)->get()->sum('Debitor');
           $crdt=GeneralDaily::where('Account',$safet->id)->get()->sum('Creditor');

            $dif=$debt - $crdt ;

                 $nun=number_format((float)abs($dif), 2, '.', '');

               if($dif > 0){
                                         if(app()->getLocale() == 'ar' ){
                      $xName=$safet->Name;

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

                   }
                            $output .= '

               <tr>
               <td class="right-color">'.$xName.'</td>
               <td class="left-color">'.$nun.'
                        <input class="AMOUNT" type="hidden" value="'.$nun.'">
                <input class="AMOUNTMinus" type="hidden" value="0">
               </td>
                     <td>
               '.$nun / $co->Draw .'
               </td>
               <tr>
               ';

               }else{
                                             if(app()->getLocale() == 'ar' ){
                      $xName=$safet->Name;

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

                   }
                               $output .= '

               <tr>
               <td class="right-color">'.$xName.'</td>
               <td class="left-color">('.$nun.')
                   <input class="AMOUNTMinus" type="hidden" value="'.$nun.'">
             <input class="AMOUNT" type="hidden" value="0">
               </td>
              <td>
               ('.$nun / $co->Draw.')
               </td>
               <tr>
               ';

               }


        }
        }


          }

      }
      else
      {
       $output = '
       <tr>
        <td align="center" colspan="5">No Data Found</td>
       </tr>
       ';
      }


      $data = array(
       'table_data'  => $output,

      );
      echo json_encode($data);
     }
    }


    //Fixed_Assets_Report
           public function Fixed_Assets_Report(){

       // Assets Monthly Event

      AssetsMonthlyEvent::dispatch();

         return view('admin.AccountsReports.Fixed_Assets_Report');
    }

          public function Fixed_Assets_ReportFilterTwo(Request $request){

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

    $items =Assets::whereBetween('Operation_Date', [$from, $to])

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

                })


->where('Delete',null)
          ->paginate(50);

       $TotalCost =Assets::whereBetween('Operation_Date', [$from, $to])

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

                })

           ->where('Delete',null)

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


          $TotalNet =Assets::whereBetween('Operation_Date', [$from, $to])

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

                })


              ->where('Delete',null)
          ->get()->sum('Asset_Net');


          $TotalEhlak =Assets::whereBetween('Operation_Date', [$from, $to])

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

                })

              ->where('Delete',null)

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



      $output = '';
          if($request->ajax())
     {
      $from = $request->get('From');
      $to = $request->get('To');
      $account = $request->get('Main_Account');


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

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

                   }
        $output .= '
        <tr>

                                                    <td>'.$row->Code.'</td>
                                                    <td>'.$xName.'</td>
                                                    <td>'.$row->Operation_Date.'</td>
                                                    <td>'.number_format($row->Cost, 2, '.', '').'</td>
                                                    <td>'.number_format($row->Previous_Depreciation, 2, '.', '').'</td>
                                                      <td>'.number_format($row->Asset_Net, 2, '.', '').'</td>
                                                        <td>'.number_format($row->Life_Span, 2, '.', '').'</td>

                                                </tr>

        ';


       }

    return   $output ;
          }

         return view('admin.AccountsReports.Fixed_Assets_ReportFilterTwo',get_defined_vars());
    }


    //TotalCollectorDepaitor

     public function TotalCollectorDepaitor(){



         if(auth()->guard('admin')->user()->emp == 0){
              $Emps = Employess::type()->get();
         }else{

              $Emps = Employess::where('id',auth()->guard('admin')->user()->emp)->get();
         }

         return view('admin.AccountsReports.TotalCollectorDepaitor',get_defined_vars());
    }


    public function TotalCollectorDepaitorFilterTwo(Request $request){

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




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

    return $query->whereBetween('Date',  [$from, $to])->where('Collector',$Collector)->where('Edit',null)->where('Delete',null);
})


        ->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)->where('Edit',null)->where('Delete',null);
})


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

                })





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



                $ProdsCount=0;

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

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


             foreach($items as $row)
       {


           if(!empty($row->RV_ID()->first()->Sales_Bill)){

               $code=$row->RV_ID()->first()->Sales_Bill;
           }else{
               $code='';
           }
                           if(app()->getLocale() == 'ar' ){
                      $ACCOUNT=$row->Account()->first()->Name;


                   }else{
                     $ACCOUNT=$row->Account()->first()->NameEn;


                   }


        $output .= '
                                            <tr>
                                                    <td>'.$row->RV_ID()->first()->Date.'</td>
                                                    <td>'.$row->RV_ID()->first()->Code.'</td>
                                                    <td>'.$row->Creditor.'</td>
                                                        <td>'.$ACCOUNT.'</td>
                                                    <td>'.$row->Statement.'</td>
                                                    <td>'.$code.'</td>


                                                </tr>

        ';

       }




return   $output ;
          }

         return view('admin.AccountsReports.TotalCollectorDepaitorFilterTwo',get_defined_vars());
    }


//CustomerDebtRestructuring
    public function CustomerDebtRestructuring(){
$Clients=AcccountingManual::where('Type',1)->whereIn('Parent',[24,37])->get();
        return view('admin.AccountsReports.CustomerDebtRestructuring',get_defined_vars());
    }


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

        $Clients=AcccountingManual::where('Type',1)->whereIn('Parent',[24,37])->get();
        $account = $request->get('account');
        $Date_Type = $request->get('Date_Type');

        if($Date_Type == 1){
            $type='Date';
        }else{
            $type='Later_Due';
        }


        $items=AcccountingManual::

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

        })

           ->paginate(30);



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


            $account = $request->get('account');
            $Date_Type = $request->get('Date_Type');

            if($Date_Type == 1){
                $type='Date';
            }else{
                $type='Later_Due';
            }

            $newID=0;
            foreach($items as $row)
            {


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


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


                }


                $date7=date("Y-m-d", strtotime("-6 days", strtotime(date('Y-m-d'))));
                $date7Minus=date("Y-m-d", strtotime("-7 days", strtotime(date('Y-m-d'))));
                $date14=date("Y-m-d", strtotime("-13 days", strtotime(date('Y-m-d'))));
                $date14Minus=date("Y-m-d", strtotime("-14 days", strtotime(date('Y-m-d'))));
                $date21=date("Y-m-d", strtotime("-20 days", strtotime(date('Y-m-d'))));
                $date21Minus=date("Y-m-d", strtotime("-21 days", strtotime(date('Y-m-d'))));
                $date31=date("Y-m-d", strtotime("-30 days", strtotime(date('Y-m-d'))));
                $date31Minus=date("Y-m-d", strtotime("-31 days", strtotime(date('Y-m-d'))));
                $date3M=date("Y-m-d", strtotime("-89 days", strtotime(date('Y-m-d'))));
                $date3MMinus=date("Y-m-d", strtotime("-90 days", strtotime(date('Y-m-d'))));
                $date6M=date("Y-m-d", strtotime("-179 days", strtotime(date('Y-m-d'))));
                $date6MMinus=date("Y-m-d", strtotime("-180 days", strtotime(date('Y-m-d'))));
                $date9M=date("Y-m-d", strtotime("-269 days", strtotime(date('Y-m-d'))));
                $date9MMinus=date("Y-m-d", strtotime("-270 days", strtotime(date('Y-m-d'))));
                $date12M=date("Y-m-d", strtotime("-360 days", strtotime(date('Y-m-d'))));
                $date12MMinus=date("Y-m-d", strtotime("-361 days", strtotime(date('Y-m-d'))));
                $dateY=date("Y-m-d", strtotime("-1000 days", strtotime(date('Y-m-d'))));
                $dateYMinus=date("Y-m-d", strtotime("-1000 days", strtotime(date('Y-m-d'))));



                $Count7=Sales::
                where('Client',$row->id)
                    ->where('Payment_Method','Later')
                    ->where('Later_Collection',0)
                    ->whereBetween($type,[$date7,date('Y-m-d')])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->count();

                $Count14=Sales::
                where('Client',$row->id)
                    ->where('Payment_Method','Later')
                    ->where('Later_Collection',0)
                    ->whereBetween($type,[$date14,$date7Minus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->count();

                $Count21=Sales::
                where('Client',$row->id)
                    ->where('Payment_Method','Later')
                    ->where('Later_Collection',0)
                    ->whereBetween($type,[$date21,$date14Minus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->count();

                $Count31=Sales::
                where('Client',$row->id)
                    ->where('Payment_Method','Later')
                    ->where('Later_Collection',0)
                    ->whereBetween($type,[$date31,$date21Minus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->count();

                $Count3M=Sales::
                where('Client',$row->id)
                    ->where('Payment_Method','Later')
                    ->where('Later_Collection',0)
                    ->whereBetween($type,[$date3M,$date31Minus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->count();

                $Count6M=Sales::
                where('Client',$row->id)
                    ->where('Payment_Method','Later')
                    ->where('Later_Collection',0)
                    ->whereBetween($type,[$date6M,$date3MMinus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->count();

                $Count9M=Sales::
                where('Client',$row->id)
                    ->where('Payment_Method','Later')
                    ->where('Later_Collection',0)
                    ->whereBetween($type,[$date9M,$date6MMinus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->count();

                $Count12M=Sales::
                where('Client',$row->id)
                    ->where('Payment_Method','Later')
                    ->where('Later_Collection',0)
                    ->whereBetween($type,[$date12M,$date9MMinus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->count();

                $CountY=Sales::
                where('Client',$row->id)
                    ->where('Payment_Method','Later')
                    ->where('Later_Collection',0)
                    ->whereBetween($type,[$dateY,$date12MMinus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->count();

                $Total7=Sales::
                where('Client',$row->id)
                    ->where('Payment_Method','Later')
                    ->where('Later_Collection',0)
                    ->whereBetween($type,[$date7,date('Y-m-d')])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get()->sum('Total_Net');

                $Total14=Sales::
                where('Client',$row->id)
                    ->where('Payment_Method','Later')
                    ->where('Later_Collection',0)
                ->whereBetween($type,[$date14,$date7Minus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get()->sum('Total_Net');

                $Total21=Sales::
                where('Client',$row->id)
                    ->where('Payment_Method','Later')
                    ->where('Later_Collection',0)
                  ->whereBetween($type,[$date21,$date14Minus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get()->sum('Total_Net');

                $Total31=Sales::
                where('Client',$row->id)
                    ->where('Payment_Method','Later')
                    ->where('Later_Collection',0)
                ->whereBetween($type,[$date31,$date21Minus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get()->sum('Total_Net');

                $Total3M=Sales::
                where('Client',$row->id)
                    ->where('Payment_Method','Later')
                    ->where('Later_Collection',0)
                 ->whereBetween($type,[$date3M,$date31Minus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get()->sum('Total_Net');

                $Total6M=Sales::
                where('Client',$row->id)
                    ->where('Payment_Method','Later')
                    ->where('Later_Collection',0)
             ->whereBetween($type,[$date6M,$date3MMinus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get()->sum('Total_Net');

                $Total9M=Sales::
                where('Client',$row->id)
                    ->where('Payment_Method','Later')
                    ->where('Later_Collection',0)
                    ->whereBetween($type,[$date9M,$date6MMinus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get()->sum('Total_Net');

                $Total12M=Sales::
                where('Client',$row->id)
                    ->where('Payment_Method','Later')
                    ->where('Later_Collection',0)
                     ->whereBetween($type,[$date12M,$date9MMinus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get()->sum('Total_Net');

                $TotalY=Sales::
                where('Client',$row->id)
                    ->where('Payment_Method','Later')
                    ->where('Later_Collection',0)
               ->whereBetween($type,[$dateY,$date12MMinus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get()->sum('Total_Net');



                $Get7=Sales::
                where('Client',$row->id)
                    ->where('Payment_Method','Later')
                    ->where('Later_Collection',0)
                    ->whereBetween($type,[$date7,date('Y-m-d')])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get('Code');

                $Get14=Sales::
                where('Client',$row->id)
                    ->where('Payment_Method','Later')
                    ->where('Later_Collection',0)
                   ->whereBetween($type,[$date14,$date7Minus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get('Code');

                $Get21=Sales::
                where('Client',$row->id)
                    ->where('Payment_Method','Later')
                    ->where('Later_Collection',0)
                      ->whereBetween($type,[$date21,$date14Minus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get('Code');

                $Get31=Sales::
                where('Client',$row->id)
                    ->where('Payment_Method','Later')
                    ->where('Later_Collection',0)
              ->whereBetween($type,[$date31,$date21Minus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get('Code');

                $Get3M=Sales::
                where('Client',$row->id)
                    ->where('Payment_Method','Later')
                    ->where('Later_Collection',0)
               ->whereBetween($type,[$date3M,$date31Minus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get('Code');

                $Get6M=Sales::
                where('Client',$row->id)
                    ->where('Payment_Method','Later')
                    ->where('Later_Collection',0)
                ->whereBetween($type,[$date6M,$date3MMinus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get('Code');

                $Get9M=Sales::
                where('Client',$row->id)
                    ->where('Payment_Method','Later')
                    ->where('Later_Collection',0)
               ->whereBetween($type,[$date9M,$date6MMinus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get('Code');

                $Get12M=Sales::
                where('Client',$row->id)
                    ->where('Payment_Method','Later')
                    ->where('Later_Collection',0)
             ->whereBetween($type,[$date12M,$date9MMinus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get('Code');

                $GetY=Sales::
                where('Client',$row->id)
                    ->where('Payment_Method','Later')
                    ->where('Later_Collection',0)
                 ->whereBetween($type,[$dateY,$date12MMinus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get('Code');

                   $new7=[];
                   for($i=0 ; $i < count($Get7) ; $i++){

                       array_push($new7,$Get7[$i]['Code']);

                   }
                $Totrecipt7=ReciptVoucherDetails::whereRelation('RV_ID','Status',1)->whereRelation('RV_ID','Delete',null)->whereRelation('RV_ID','Edit',null)->whereIn('Bill_Num',$new7)->get()->sum('Creditor');


                   $new14=[];
                   for($i=0 ; $i < count($Get14) ; $i++){

                       array_push($new14,$Get14[$i]['Code']);

                   }
                $Totrecipt14=ReciptVoucherDetails::whereRelation('RV_ID','Status',1)->whereRelation('RV_ID','Delete',null)->whereRelation('RV_ID','Edit',null)->whereIn('Bill_Num',$new14)->get()->sum('Creditor');


                   $new21=[];
                   for($i=0 ; $i < count($Get21) ; $i++){

                       array_push($new21,$Get21[$i]['Code']);

                   }
                $Totrecipt21=ReciptVoucherDetails::whereRelation('RV_ID','Status',1)->whereRelation('RV_ID','Delete',null)->whereRelation('RV_ID','Edit',null)->whereIn('Bill_Num',$new21)->get()->sum('Creditor');


                   $new31=[];
                   for($i=0 ; $i < count($Get31) ; $i++){

                       array_push($new31,$Get31[$i]['Code']);

                   }
                $Totrecipt31=ReciptVoucherDetails::whereRelation('RV_ID','Status',1)->whereRelation('RV_ID','Delete',null)->whereRelation('RV_ID','Edit',null)->whereIn('Bill_Num',$new31)->get()->sum('Creditor');


                   $new3M=[];
                   for($i=0 ; $i < count($Get3M) ; $i++){

                       array_push($new3M,$Get3M[$i]['Code']);

                   }
                $Totrecipt3M=ReciptVoucherDetails::whereRelation('RV_ID','Status',1)->whereRelation('RV_ID','Delete',null)->whereRelation('RV_ID','Edit',null)->whereIn('Bill_Num',$new3M)->get()->sum('Creditor');


                   $new6M=[];
                   for($i=0 ; $i < count($Get6M) ; $i++){

                       array_push($new6M,$Get6M[$i]['Code']);

                   }
                $Totrecipt6M=ReciptVoucherDetails::whereRelation('RV_ID','Status',1)->whereRelation('RV_ID','Delete',null)->whereRelation('RV_ID','Edit',null)->whereIn('Bill_Num',$new6M)->get()->sum('Creditor');


                   $new9M=[];
                   for($i=0 ; $i < count($Get9M) ; $i++){

                       array_push($new9M,$Get9M[$i]['Code']);

                   }
                $Totrecipt9M=ReciptVoucherDetails::whereRelation('RV_ID','Status',1)->whereRelation('RV_ID','Delete',null)->whereRelation('RV_ID','Edit',null)->whereIn('Bill_Num',$new9M)->get()->sum('Creditor');


                   $new12M=[];
                   for($i=0 ; $i < count($Get12M) ; $i++){

                       array_push($new12M,$Get12M[$i]['Code']);

                   }
                $Totrecipt12M=ReciptVoucherDetails::whereRelation('RV_ID','Status',1)->whereRelation('RV_ID','Delete',null)->whereRelation('RV_ID','Edit',null)->whereIn('Bill_Num',$new12M)->get()->sum('Creditor');


                   $newY=[];
                   for($i=0 ; $i < count($GetY) ; $i++){

                       array_push($newY,$GetY[$i]['Code']);

                   }
                $TotreciptY=ReciptVoucherDetails::whereRelation('RV_ID','Status',1)->whereRelation('RV_ID','Delete',null)->whereRelation('RV_ID','Edit',null)->whereIn('Bill_Num',$newY)->get()->sum('Creditor');



                    $output .= '
                                            <tr>
                                                    <td>' . $Name . '</td>

                                                    <td>' . $Count7 . '</td>
                                                    <td>' .$Total7 - $Totrecipt7. '</td>


                                                    <td>' . $Count14 . '</td>
                                                    <td>' .$Total14 - $Totrecipt14. '</td>

                                                    <td>' . $Count21 . '</td>
                                                    <td>' .$Total21 - $Totrecipt21. '</td>

                                                    <td>' . $Count31 . '</td>
                                                    <td>' .$Total31 - $Totrecipt31. '</td>

                                                    <td>' . $Count3M . '</td>
                                                    <td>' .$Total3M - $Totrecipt3M. '</td>

                                                    <td>' . $Count6M . '</td>
                                                    <td>' .$Total6M - $Totrecipt6M. '</td>

                                                    <td>' . $Count9M . '</td>
                                                    <td>' .$Total9M - $Totrecipt9M. '</td>

                                                    <td>' . $Count12M . '</td>
                                                    <td>' .$Total12M - $Totrecipt12M. '</td>

                                                    <td>' . $CountY . '</td>
                                                    <td>' .$TotalY - $TotreciptY. '</td>


                                                </tr>

                                    ';



            }




            return   $output ;
        }

        return view('admin.AccountsReports.CustomerDebtRestructuringFilter',get_defined_vars());
    }



//VendorDebtRestructuring
    public function VendorDebtRestructuring(){
        $Clients=AcccountingManual::where('Type',1)->whereIn('Parent',[37])->get();
        return view('admin.AccountsReports.VendorDebtRestructuring',get_defined_vars());
    }


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

        $Clients=AcccountingManual::where('Type',1)->whereIn('Parent',[24,37])->get();
        $account = $request->get('account');
        $Date_Type = $request->get('Date_Type');

        if($Date_Type == 1){
            $type='Date';
        }else{
            $type='Later_Due';
        }


        $items=AcccountingManual::

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

        })

            ->paginate(30);



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


            $account = $request->get('account');
            $Date_Type = $request->get('Date_Type');

            if($Date_Type == 1){
                $type='Date';
            }else{
                $type='Later_Due';
            }

            $newID=0;
            foreach($items as $row)
            {


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


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


                }

                $date7=date("Y-m-d", strtotime("-6 days", strtotime(date('Y-m-d'))));
                $date7Minus=date("Y-m-d", strtotime("-7 days", strtotime(date('Y-m-d'))));
                $date14=date("Y-m-d", strtotime("-13 days", strtotime(date('Y-m-d'))));
                $date14Minus=date("Y-m-d", strtotime("-14 days", strtotime(date('Y-m-d'))));
                $date21=date("Y-m-d", strtotime("-20 days", strtotime(date('Y-m-d'))));
                $date21Minus=date("Y-m-d", strtotime("-21 days", strtotime(date('Y-m-d'))));
                $date31=date("Y-m-d", strtotime("-30 days", strtotime(date('Y-m-d'))));
                $date31Minus=date("Y-m-d", strtotime("-31 days", strtotime(date('Y-m-d'))));
                $date3M=date("Y-m-d", strtotime("-89 days", strtotime(date('Y-m-d'))));
                $date3MMinus=date("Y-m-d", strtotime("-90 days", strtotime(date('Y-m-d'))));
                $date6M=date("Y-m-d", strtotime("-179 days", strtotime(date('Y-m-d'))));
                $date6MMinus=date("Y-m-d", strtotime("-180 days", strtotime(date('Y-m-d'))));
                $date9M=date("Y-m-d", strtotime("-269 days", strtotime(date('Y-m-d'))));
                $date9MMinus=date("Y-m-d", strtotime("-270 days", strtotime(date('Y-m-d'))));
                $date12M=date("Y-m-d", strtotime("-360 days", strtotime(date('Y-m-d'))));
                $date12MMinus=date("Y-m-d", strtotime("-361 days", strtotime(date('Y-m-d'))));
                $dateY=date("Y-m-d", strtotime("-1000 days", strtotime(date('Y-m-d'))));
                $dateYMinus=date("Y-m-d", strtotime("-1000 days", strtotime(date('Y-m-d'))));

                $Count7=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')
                    ->whereBetween($type,[$date7,date('Y-m-d')])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->count();

                $Count14=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')
                    ->whereBetween($type,[$date14,$date7Minus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->count();

                $Count21=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')
                    ->whereBetween($type,[$date21,$date14Minus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->count();

                $Count31=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')
                    ->whereBetween($type,[$date31,$date21Minus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->count();

                $Count3M=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')
                    ->whereBetween($type,[$date3M,$date31Minus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->count();

                $Count6M=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')

                    ->whereBetween($type,[$date6M,$date3MMinus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->count();

                $Count9M=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')

                    ->whereBetween($type,[$date9M,$date6MMinus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->count();

                $Count12M=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')

                    ->whereBetween($type,[$date12M,$date9MMinus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->count();

                $CountY=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')

                    ->whereBetween($type,[$dateY,$date12MMinus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->count();

                $Total7=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')
                    ->whereBetween($type,[$date7,date('Y-m-d')])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get()->sum('Total_Net');

                $Total14=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')

                    ->whereBetween($type,[$date14,$date7Minus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get()->sum('Total_Net');

                $Total21=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')

                    ->whereBetween($type,[$date21,$date14Minus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get()->sum('Total_Net');

                $Total31=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')

                    ->whereBetween($type,[$date31,$date21Minus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get()->sum('Total_Net');

                $Total3M=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')

                    ->whereBetween($type,[$date3M,$date31Minus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get()->sum('Total_Net');

                $Total6M=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')

                    ->whereBetween($type,[$date6M,$date3MMinus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get()->sum('Total_Net');

                $Total9M=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')

                    ->whereBetween($type,[$date9M,$date6MMinus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get()->sum('Total_Net');

                $Total12M=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')

                    ->whereBetween($type,[$date12M,$date9MMinus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get()->sum('Total_Net');

                $TotalY=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')

                    ->whereBetween($type,[$dateY,$date12MMinus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get()->sum('Total_Net');


                $TotalPay7=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')
                    ->whereBetween($type,[$date7,date('Y-m-d')])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get()->sum('Pay');

                $TotalPay14=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')

                    ->whereBetween($type,[$date14,$date7Minus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get()->sum('Pay');

                $TotalPay21=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')

                    ->whereBetween($type,[$date21,$date14Minus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get()->sum('Pay');

                $TotalPay31=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')

                    ->whereBetween($type,[$date31,$date21Minus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get()->sum('Pay');

                $TotalPay3M=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')

                    ->whereBetween($type,[$date3M,$date31Minus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get()->sum('Pay');

                $TotalPay6M=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')

                    ->whereBetween($type,[$date6M,$date3MMinus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get()->sum('Pay');

                $TotalPay9M=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')

                    ->whereBetween($type,[$date9M,$date6MMinus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get()->sum('Pay');

                $TotalPay12M=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')

                    ->whereBetween($type,[$date12M,$date9MMinus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get()->sum('Pay');

                $TotalPayY=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')

                    ->whereBetween($type,[$dateY,$date12MMinus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get()->sum('Pay');







                $Get7=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')

                    ->whereBetween($type,[$date7,date('Y-m-d')])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get('Code');

                $Get14=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')

                    ->whereBetween($type,[$date14,$date7Minus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get('Code');

                $Get21=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')

                    ->whereBetween($type,[$date21,$date14Minus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get('Code');

                $Get31=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')

                    ->whereBetween($type,[$date31,$date21Minus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get('Code');

                $Get3M=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')

                    ->whereBetween($type,[$date3M,$date31Minus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get('Code');

                $Get6M=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')

                    ->whereBetween($type,[$date6M,$date3MMinus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get('Code');

                $Get9M=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')

                    ->whereBetween($type,[$date9M,$date6MMinus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get('Code');

                $Get12M=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')

                    ->whereBetween($type,[$date12M,$date9MMinus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get('Code');

                $GetY=Purchases::
                where('Vendor',$row->id)
                    ->where('Payment_Method','Later')

                    ->whereBetween($type,[$dateY,$date12MMinus])
                    ->where('Edit',0)
                    ->where('Delete',0)
                    ->get('Code');

                $new7=[];
                for($i=0 ; $i < count($Get7) ; $i++){

                    array_push($new7,$Get7[$i]['Code']);

                }
                $Totrecipt7=PaymentVoucherDetails::whereRelation('PV_ID','Status',1)->whereRelation('PV_ID','Delete',null)->whereRelation('PV_ID','Edit',null)->whereIn('Bill_Num',$new7)->get()->sum('Debitor');


                $new14=[];
                for($i=0 ; $i < count($Get14) ; $i++){

                    array_push($new14,$Get14[$i]['Code']);

                }
     $Totrecipt14=PaymentVoucherDetails::whereRelation('PV_ID','Status',1)->whereRelation('PV_ID','Delete',null)->whereRelation('PV_ID','Edit',null)->whereIn('Bill_Num',$new14)->get()->sum('Debitor');

                $new21=[];
                for($i=0 ; $i < count($Get21) ; $i++){

                    array_push($new21,$Get21[$i]['Code']);

                }
     $Totrecipt21=PaymentVoucherDetails::whereRelation('PV_ID','Status',1)->whereRelation('PV_ID','Delete',null)->whereRelation('PV_ID','Edit',null)->whereIn('Bill_Num',$new21)->get()->sum('Debitor');

                $new31=[];
                for($i=0 ; $i < count($Get31) ; $i++){

                    array_push($new31,$Get31[$i]['Code']);

                }
     $Totrecipt31=PaymentVoucherDetails::whereRelation('PV_ID','Status',1)->whereRelation('PV_ID','Delete',null)->whereRelation('PV_ID','Edit',null)->whereIn('Bill_Num',$new31)->get()->sum('Debitor');

                $new3M=[];
                for($i=0 ; $i < count($Get3M) ; $i++){

                    array_push($new3M,$Get3M[$i]['Code']);

                }
     $Totrecipt3M=PaymentVoucherDetails::whereRelation('PV_ID','Status',1)->whereRelation('PV_ID','Delete',null)->whereRelation('PV_ID','Edit',null)->whereIn('Bill_Num',$new3M)->get()->sum('Debitor');

                $new6M=[];
                for($i=0 ; $i < count($Get6M) ; $i++){

                    array_push($new6M,$Get6M[$i]['Code']);

                }
     $Totrecipt6M=PaymentVoucherDetails::whereRelation('PV_ID','Status',1)->whereRelation('PV_ID','Delete',null)->whereRelation('PV_ID','Edit',null)->whereIn('Bill_Num',$new6M)->get()->sum('Debitor');

                $new9M=[];
                for($i=0 ; $i < count($Get9M) ; $i++){

                    array_push($new9M,$Get9M[$i]['Code']);

                }
     $Totrecipt9M=PaymentVoucherDetails::whereRelation('PV_ID','Status',1)->whereRelation('PV_ID','Delete',null)->whereRelation('PV_ID','Edit',null)->whereIn('Bill_Num',$new9M)->get()->sum('Debitor');

                $new12M=[];
                for($i=0 ; $i < count($Get12M) ; $i++){

                    array_push($new12M,$Get12M[$i]['Code']);

                }
     $Totrecipt12M=PaymentVoucherDetails::whereRelation('PV_ID','Status',1)->whereRelation('PV_ID','Delete',null)->whereRelation('PV_ID','Edit',null)->whereIn('Bill_Num',$new12M)->get()->sum('Debitor');

                $newY=[];
                for($i=0 ; $i < count($GetY) ; $i++){

                    array_push($newY,$GetY[$i]['Code']);

                }
     $TotreciptY=PaymentVoucherDetails::whereRelation('PV_ID','Status',1)->whereRelation('PV_ID','Delete',null)->whereRelation('PV_ID','Edit',null)->whereIn('Bill_Num',$newY)->get()->sum('Debitor');


                $output .= '
                                            <tr>
                                                    <td>' . $Name . '</td>

                                                    <td>' . $Count7 . '</td>
                                                    <td>' .$Total7 - ($Totrecipt7 + $TotalPay7). '</td>


                                                    <td>' . $Count14 . '</td>
                                                    <td>' .$Total14 -  ($Totrecipt14 + $TotalPay14). '</td>

                                                    <td>' . $Count21 . '</td>
                                                    <td>' .$Total21 -  ($Totrecipt21 + $TotalPay21). '</td>

                                                    <td>' . $Count31 . '</td>
                                                    <td>' .$Total31 -  ($Totrecipt31 + $TotalPay31). '</td>

                                                    <td>' . $Count3M . '</td>
                                                    <td>' .$Total3M -  ($Totrecipt3M + $TotalPay3M). '</td>

                                                    <td>' . $Count6M . '</td>
                                                    <td>' .$Total6M -  ($Totrecipt6M + $TotalPay6M). '</td>

                                                    <td>' . $Count9M . '</td>
                                                    <td>' .$Total9M -  ($Totrecipt9M + $TotalPay9M). '</td>

                                                    <td>' . $Count12M . '</td>
                                                    <td>' .$Total12M -  ($Totrecipt12M + $TotalPay12M). '</td>

                                                    <td>' . $CountY . '</td>
                                                    <td>' .$TotalY -  ($TotreciptY + $TotalPayY). '</td>


                                                </tr>

                                    ';



            }




            return   $output ;
        }

        return view('admin.AccountsReports.VendorDebtRestructuringFilter',get_defined_vars());
    }




    //Vendor_Balances

    public function VendorsBalancesReport(){

        return view('admin.AccountsReports.VendorsBalancesReport');
    }

    public function VendorsBalancesReportFilterTwo(Request $request){

        $from = $request->get('From');
        $to = $request->get('To');
        $zero = $request->get('Zero');


        $Accounts = AcccountingManual::where('Parent',37)
            ->where('Type', 1)
            ->orderBy('id', 'asc')
            ->paginate(100);

        $AccountsCount = AcccountingManual::where('Parent',37)
            ->where('Type', 1)
            ->orderBy('id', 'asc')
            ->count();

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

            ->whereRelation('Account','Parent',37)

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

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

            ->whereRelation('Account','Parent',37)

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

        $totalAllD=GeneralDaily::

        whereRelation('Account','Parent',37)

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

        $totalAllC=GeneralDaily::

        whereRelation('Account','Parent',37)


            ->get()->sum('Creditor_Coin');
        $Credit=$totalD - $totalC;
        $CreditAll=$totalAllD - $totalAllC;



        $output = '';
        if($request->ajax())
        {
            $from = $request->get('From');
            $to = $request->get('To');
            $zero = $request->get('Zero');
            $DBBEFORE=0;
            $CRBEFORE=0;
            $DBTOTAL=0;
            $CRTOTAL=0;
            $DBBALANCE=0;
            $CRBALANCE=0;





            foreach($Accounts as $row)
            {
                $apear=0;
                $DebBef =GeneralDaily::where('Account',$row->id)
                    ->where('Date','<',$from)
                    ->get()->sum('Debitor_Coin');


                $CredBef =GeneralDaily::where('Account',$row->id)
                    ->where('Date','<',$from)
                    ->get()->sum('Creditor_Coin');

                $TotalDeb =GeneralDaily::where('Account',$row->id)
                    ->whereBetween('Date', [$from, $to])
                    ->get()->sum('Debitor_Coin');


                $TotalCred =GeneralDaily::where('Account',$row->id)
                    ->whereBetween('Date', [$from, $to])
                    ->get()->sum('Creditor_Coin');


                $x=( $DebBef + $TotalDeb ) - ( $CredBef + $TotalCred ) ;


                if($x < 0){

                    $y=0;
                    $z=abs($x);
                }else{

                    $y=$x;
                    $z=0;

                }

                $DBBEFORE +=$DebBef;
                $CRBEFORE +=$CredBef;
                $DBTOTAL +=$TotalDeb;
                $CRTOTAL +=$TotalCred;
                $DBBALANCE +=$y;
                $CRBALANCE +=$z;



                if($zero == 1) {
                    if($DebBef == 0  and $CredBef == 0 and $TotalDeb == 0  and $TotalCred == 0 and $y == 0  and $z == 0 ){
                        $apear=1;
                    }
                }

                if($apear == 0){

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

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

                    }

                    $output .= '
        <tr>
                                             <td class="">'.$row->Code.'</td>
                                                       <td> '.$xName.'</td>
                                                     <td><input type="hidden" class="DBBEFORE" value="'.$DebBef.'"> '.$DebBef.'</td>
                                                    <td><input type="hidden" class="CRBEFORE" value="'.$CredBef.'">'.$CredBef.'</td>
                                                    <td><input type="hidden" class="DBTOTAL" value="'.$TotalDeb.'">'.$TotalDeb.'</td>
                                                    <td><input type="hidden" class="CRTOTAL" value="'.$TotalCred.'">'.$TotalCred.'</td>
                                                    <td><input type="hidden" class="DBBALANCE" value="'.$y.'">'.$y.'</td>
                                                    <td><input type="hidden" class="CRBALANCE" value="'.$z.'">'.$z.'</td>
                                                </tr>

        ';


                }

            }



            return   $output ;
        }

        return view('admin.AccountsReports.VendorsBalancesReportFilterTwo',get_defined_vars());
    }






}
