IMMREX7

aku nok ndi : /home/spdtg/www/schoolmis/app/Http/Controllers/Student/
File Up :
aku nok ndi : /home/spdtg/www/schoolmis/app/Http/Controllers/Student/OnlineFeeController.php

<?php

namespace App\Http\Controllers\Student;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Session;
use DB;
use App\Http\TransactionRequestBean;
use App\Http\TransactionResponseBean;
use Carbon\Carbon;
use PDF;
use App\Http\Cashfree;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use App\Http\PaymentCalculation;

class OnlineFeeController extends StudentController {

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function extraFeeDetails(Request $request){
        $student = \App\AdmEntry::where('idStudent', '=', Session::get('idStudent'))->first();
        $paidfees =\App\StudentExtraTransaction::where('idStudent', '=', $student->idStudent)
                    ->where('idFinancialYear', '=', $student->idFinancialYear)
                    ->where(function($query) {
                        $query->whereNull('status');
                        $query->orWhere('status', '=', 'In-Process');
                        $query->orWhere('status', '=', 'Cleared');
                        $query->orWhere('status', '=', 'Success');
                    })->get();
        $feeheads = \App\ExtraFeehead::where(function($q) use ($student){ 
            $q->where('idClass', '=', $student->idClass)->orWhereNull('idClass');
        })
        ->where('extra_feehead.idSchool', '=', $student->idSchool)
        ->where('extra_feehead.idFinancialYear','=', $student->idFinancialYear)
        ->get();
        return view('students.onlinefees.royal_extra_feedetails', compact('student','feeheads','paidfees'));
    }

    public function index(Request $request) {
        $student = \App\AdmEntry::where('idStudent', '=', Session::get('idStudent'))->first();
        $paidfees_tot = \App\StudentTransaction::where('idStudent', '=', $student->idStudent)
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })
                        ->select('paymentMode', 'paymentDate', 'idTransaction', DB::raw('SUM(totalPaid) as totalPaid'), DB::raw('SUM(discount) as discount'), DB::raw('SUM(fine) as fine'), DB::raw('SUM(penaltyAmount) as penaltyAmount'))->first();
        // dd($paidfees_tot);
        $paidfees = \App\StudentTransaction::where('idStudent', '=', $student->idStudent)
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'Success');
                        })->get();
        $lesserfees = \App\LesserTransaction::where('idStudent', '=', $student->idStudent)
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'Success');
                        })->get();
        
        if ($student->idSchool == 135 || $student->idSchool == 140 || $student->idSchool == 159 || $student->idSchool == 160) {
            $paymentMode = "easebuzz"; 
            $isFull = "Full";
            if ($request->get('paymode') != null) {
                if ($request->get('paymode') == "full"){
                    $isFull = "Full";
                }else
                    $isFull = "Installment";
            }  

            $admission_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                                ->where('idSection', '=', $student->idSection)
                                ->where('idFinancialYear', '=', $student->idFinancialYear)
                                ->where('studentCategory', '=', $student->studentType)
                                ->where('feeheadName', 'LIKE', '%Admission Confirmation Fee%')->first();
            if($admission_feeheads == null){
                $class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                ->where('idSection', '=', $student->idSection)
                ->where('idFinancialYear', '=', $student->idFinancialYear)
                ->where('studentCategory', '=', $student->studentType)
                ->whereNull('idStudent');
                //   ->get();
                $allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                        ->where('idSection', '=', $student->idSection)
                        ->where('studentCategory', '=', 'All')
                        ->where('idFinancialYear', '=', $student->idFinancialYear)
                        ->whereNull('idStudent');
                //   ->get();
                $feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                        ->where('idFinancialYear', '=', $student->idFinancialYear)
                        ->union($class_feeheads)
                        ->union($allcat_feeheads)
                        ->orderBy('toDate')
                        ->get();
                $feetotal = $feeheads->sum('amount');
            }else{
                //check if paid
                $feepaid = \App\StudentTransactionDetail::where('idStudent', '=', $student->idStudent)
                            ->where('idFeehead', '=', $admission_feeheads->idFeehead)
                            ->select(DB::raw('SUM(amountPaid) as totalPaid'))->first();
                $lesser_feepaid = DB::table('lesser_transaction')
                                        ->join('lesser_transaction_details', 'lesser_transaction_details.idLesserTransaction', '=', 'lesser_transaction.idLesserTransaction')
                                        ->where('lesser_transaction.idStudent', '=', $student->idStudent)
                                        ->where('idFeehead', '=', $admission_feeheads->idFeehead)
                                        ->where(function($query) {
                                                $query->whereNull('lesser_transaction.status');
                                                $query->orWhere('lesser_transaction.status', '=', 'Cleared');
                                                $query->orWhere('lesser_transaction.status', '=', 'In-Process');
                                                $query->orWhere('lesser_transaction.status', '=', 'Success');
                                            })
                                        ->select(DB::raw('SUM(totalPaid) as totalPaid'))
                                        ->first();
                $lesser_feepaid;
                if($feepaid->totalPaid == 0 && $lesser_feepaid->totalPaid == 0) {
                    $afeeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                    ->where('idSection', '=', $student->idSection)
                    ->where('idFinancialYear', '=', $student->idFinancialYear)
                    ->where('studentCategory', '=', $student->studentType)
                    ->where('feeheadName', 'LIKE', '%Admission Confirmation Fee%');
                    $feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                            ->where('idFinancialYear', '=', $student->idFinancialYear)
                            ->union($afeeheads)
                            ->orderBy('toDate')
                            ->get();
                    $feetotal = $feeheads->sum('amount');
                }else{
                    $class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                    ->where('idSection', '=', $student->idSection)
                    ->where('idFinancialYear', '=', $student->idFinancialYear)
                    ->where('studentCategory', '=', $student->studentType)
                    ->whereNull('idStudent');
                    //   ->get();
                    $allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                            ->where('idSection', '=', $student->idSection)
                            ->where('studentCategory', '=', 'All')
                            ->where('idFinancialYear', '=', $student->idFinancialYear)
                            ->whereNull('idStudent');
                    //   ->get();
                    $feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                            ->where('idFinancialYear', '=', $student->idFinancialYear)
                            ->union($class_feeheads)
                            ->union($allcat_feeheads)
                            ->orderBy('toDate')
                            ->get();
                    $feetotal = $feeheads->sum('amount');
                }
            }


            
            $feeheader_ids = $feeheads->pluck('idFeehead')->toArray();
            $prevaccess_fee = DB::table('excess_transaction')
                            ->join('student_transaction', 'excess_transaction.idTransaction', '=', 'student_transaction.idTransaction')
                            ->where('idStudent', '=', $student->idStudent)
                            ->where('idFinancialYear', '=', $student->idFinancialYear)
                            ->where('excess_transaction.isActive', '=', 'Y')
                            ->orderBy('excess_transaction.idTransaction', 'desc')->first();
            $lesser_transaction = DB::table('lesser_transaction')
                    ->join('lesser_transaction_details', 'lesser_transaction_details.idLesserTransaction', '=', 'lesser_transaction.idLesserTransaction')
                    ->where('lesser_transaction.idStudent', '=', $student->idStudent)
                    ->where('lesser_transaction.idFinancialYear', '=', $student->idFinancialYear)
                    ->whereIn('idFeehead', $feeheader_ids)
                    ->where(function($query) {
                        $query->whereNull('lesser_transaction.status');
                        $query->orWhere('lesser_transaction.status', '=', 'Cleared');
                        $query->orWhere('lesser_transaction.status', '=', 'In-Process');
                        $query->orWhere('lesser_transaction.status', '=', 'Success');
                    })
                ->select(DB::raw('SUM(totalPaid) as totalPaid'))
                ->first();
            if($student->idSchool == 159 || $student->idSchool == 160){
                return view('students.onlinefees.mhws_college_feedetails', compact('lesser_transaction', 'lesserfees', 'feetotal', 'paidfees_tot', 'student', 'paidfees', 'feeheads',  'penalty', 'feeheadwiseamount', 'prevaccess_fee','paymentMode'));
            }
            return view('students.onlinefees.mhws_feedetails', compact('paymentMode','lesser_transaction', 'lesserfees', 'feetotal', 'paidfees_tot', 'student', 'paidfees', 'feeheads', 'prevaccess_fee', 'isFull'));
        }

        /*if ($student->idSchool == 135 || $student->idSchool == 140) {
                $isFull = "installments";
                $isAdmissionPaid = 0;
                if ($request->get('paymode') != null) {
                    if ($request->get('paymode') == "full"){
                        $isFull = "full";
                    }else
                        $isFull = "installments";
                }else{
                    if($paidfees->count() > 0){
                        foreach($paidfees as $paidfee){
                            $transactions = \App\StudentTransactionDetail::where('idTransaction','=',$paidfee->idTransaction)->get();
                            foreach($transactions as $transaction){
                                $header = \DB::table('feeheads')->where('idFeehead',$transaction->idFeehead)->first();
                                if($header != null){
                                    if (str_contains($header->feeheadName, 'Plan A')) {
                                        $isFull = 'full';
                                        break;
                                    }else if (str_contains($header->feeheadName, 'Plan B')) {
                                        $isFull = 'installments';
                                        break;
                                    }else if (str_contains($header->feeheadName, 'Admission')) {
                                        $isAdmissionPaid++;
                                        $isFull = 'full';
                                        break;
                                    }
                                }
                            }
                            if($isFull != '') break;
                        }
                    }

                    if($lesserfees->count() > 0 && $isFull == ''){
                        foreach($lesserfees as $paidfee){
                            $transactions = \App\LesserTransactionDetail::where('idLesserTransaction','=',$paidfee->idLesserTransaction)->get();
                            foreach($transactions as $transaction){
                                $header = \DB::table('feeheads')->where('idFeehead',$transaction->idFeehead)->first();
                                if($header != null){
                                    if (str_contains($header->feeheadName, 'Plan A')) {
                                        $isFull = 'full';
                                        break;
                                    }else if (str_contains($header->feeheadName, 'Plan B')) {
                                        $isFull = 'installments';
                                        break;
                                    }else if (str_contains($header->feeheadName, 'Admission')) {
                                        $isAdmissionPaid++;
                                        $isFull = 'full';
                                        break;
                                    }
                                }
                            }
                            if($isFull != '') break;
                        }
                    }
                }  

                if ($isFull == "full") {
                    $admission_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                    ->where('idSection', '=', $student->idSection)
                    ->where('idFinancialYear', '=', $student->idFinancialYear)
                    ->where('studentCategory', '=', $student->studentType)
                    ->where('feeheadName', 'LIKE', '%Admission Confirmation Fee%'); 
                    if($isAdmissionPaid == 0){
                        $feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                                ->where('idFinancialYear', '=', $student->idFinancialYear)
                                ->where('feeheadName', 'LIKE', '%(Full Payment)')
                                ->union($admission_feeheads)
                                ->orderBy('toDate')
                                ->get();
                        $feetotal = $feeheads->sum('amount');
                    }else{
                        $class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                        ->where('idSection', '=', $student->idSection)
                        ->where('idFinancialYear', '=', $student->idFinancialYear)
                        ->where('studentCategory', '=', $student->studentType)
                        ->where('feeheadName', 'LIKE', '%(Full Payment)')
                        ->whereNull('idStudent');
                        $p1_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                                ->where('idSection', '=', $student->idSection)
                                ->where('idFinancialYear', '=', $student->idFinancialYear)
                                ->where('feeheadName', 'LIKE', 'P1%');  
                        $p2_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                                ->where('idSection', '=', $student->idSection)
                                ->where('idFinancialYear', '=', $student->idFinancialYear)
                                ->where('feeheadName', 'LIKE', 'P2%');    
                        //   ->get();
                        $allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                                ->where('idSection', '=', $student->idSection)
                                ->where('studentCategory', '=', 'All')
                                ->where('idFinancialYear', '=', $student->idFinancialYear)
                                ->where('feeheadName', 'LIKE', '%(Full Payment)')
                                ->whereNull('idStudent');
                        //   ->get();
                        $feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                                ->where('idFinancialYear', '=', $student->idFinancialYear)
                                ->where('feeheadName', 'LIKE', '%(Full Payment)')
                                ->union($class_feeheads)
                                ->union($allcat_feeheads)
                                ->union($admission_feeheads)
                                ->union($p1_feeheads)
                                ->union($p2_feeheads)
                                ->orderBy('toDate')
                                ->get();
                        $feetotal = $feeheads->sum('amount');
                    } 
            } else {
                $admission_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                        ->where('idSection', '=', $student->idSection)
                        ->where('idFinancialYear', '=', $student->idFinancialYear)
                        ->where('studentCategory', '=', $student->studentType)
                        ->where('feeheadName', 'LIKE', '%Admission Confirmation Fee%'); 
                if($isAdmissionPaid == 0){
                    $feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                                ->where('idFinancialYear', '=', $student->idFinancialYear)
                                ->where('feeheadName', 'LIKE', '%(Full Payment)')
                                ->union($admission_feeheads)
                                ->orderBy('toDate')
                                ->get();
                        $feetotal = $feeheads->sum('amount');
                }else{
                    $p1_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                    ->where('idSection', '=', $student->idSection)
                    ->where('idFinancialYear', '=', $student->idFinancialYear)
                    ->where('feeheadName', 'LIKE', 'P1%');  
                   $p2_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                    ->where('idSection', '=', $student->idSection)
                    ->where('idFinancialYear', '=', $student->idFinancialYear)
                    ->where('feeheadName', 'LIKE', 'P2%'); 
                    $class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                            ->where('idSection', '=', $student->idSection)
                            ->where('idFinancialYear', '=', $student->idFinancialYear)
                            ->where('studentCategory', '=', $student->studentType)
                            ->where('feeheadName', 'LIKE', '%Installment)')
                            ->whereNull('idStudent');
                    //   ->get();
                    $allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                            ->where('idSection', '=', $student->idSection)
                            ->where('studentCategory', '=', 'All')
                            ->where('idFinancialYear', '=', $student->idFinancialYear)
                            ->where('feeheadName', 'LIKE', '%Installment)')
                            ->whereNull('idStudent');
                    //   ->get();
                    $feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                            ->where('idFinancialYear', '=', $student->idFinancialYear)
                            ->where('feeheadName', 'LIKE', '%Installment)')
                            ->union($class_feeheads)
                            ->union($allcat_feeheads)
                            ->union($admission_feeheads)
                            ->union($p1_feeheads)
                            ->union($p2_feeheads)
                            ->orderBy('toDate')
                            ->get();
                    $feetotal = $feeheads->sum('amount');   
                }
                
            }
                $feeheader_ids = $feeheads->pluck('idFeehead')->toArray();
                $lesser_transaction = DB::table('lesser_transaction')
                ->join('lesser_transaction_details', 'lesser_transaction_details.idLesserTransaction', '=', 'lesser_transaction.idLesserTransaction')
                ->where('lesser_transaction.idStudent', '=', $student->idStudent)
                ->where('lesser_transaction.idFinancialYear', '=', $student->idFinancialYear)
                ->whereIn('idFeehead', $feeheader_ids)
                ->where(function($query) {
                    $query->whereNull('lesser_transaction.status');
                    $query->orWhere('lesser_transaction.status', '=', 'Cleared');
                    $query->orWhere('lesser_transaction.status', '=', 'In-Process');
                    $query->orWhere('lesser_transaction.status', '=', 'Success');
                })
                ->select(DB::raw('SUM(totalPaid) as totalPaid'),DB::raw('SUM(lesser_transaction_details.discount) as discount'))
                ->first();
              
            if($student->idSchool == 135)
            $paymentMode = "easebuzz";    
            else $paymentMode = "easebuzz";   
            return view('students.onlinefees.mhws_feedetails', compact('paymentMode','lesser_transaction', 'lesserfees', 'feetotal', 'paidfees_tot', 'student', 'paidfees', 'feeheads', 'excesspaid', 'penalty', 'feeheadwiseamount', 'prevaccess_fee', 'isFull'));
        } else*/ if($student->idSchool == 25){
            if($request->get('session') != null){
                $studentNew = \App\AdmEntry::where('idStudent', '=', $request->get('session'))->first();
                session()->forget('idStudent');
                Session::save();
                session()->put('idStudent', $studentNew->idStudent);
                return redirect('student/payfees');
            } 
            $fy = array();
            $fetchSession = \App\FinancialYear::where('idFinancialYear','>=',$student->idFinancialYear)->get();
            foreach($fetchSession as $session){
                $promotions = \App\AdmEntry::where('idSchool', '=', $student->idSchool)
                    ->where('father_mobile','=',$student->father_mobile)
                    ->where('father_fname','=',$student->father_fname)
                    ->where('ecNo','=',$student->ecNo)
                    ->where('idFinancialYear','=',$session->idFinancialYear)
                    ->first();
                if($promotions != null)
                array_push($fy,array(
                    "id" => $promotions->idStudent,
                    "yearName" => $session->financialYearName,
                    "idFinancialYear" => $promotions->idFinancialYear
                ));
            }
            $lesser_transaction = [];
            $feeheads = [];
            $feetotal = 0;
            $plan = '';
            $session = $student->idFinancialYear;
            if($paidfees->count() > 0){
                foreach($paidfees as $paidfee){
                    $transactions = \App\StudentTransactionDetail::where('idTransaction','=',$paidfee->idTransaction)->get();
                    foreach($transactions as $transaction){
                        $header = \DB::table('feeheads')->where('idFeehead',$transaction->idFeehead)->first();
                        if (str_contains($header->feeheadLabel, 'Plan A')) {
                            $plan = 'Plan A';
                            break;
                        }else if (str_contains($header->feeheadLabel, 'Plan B')) {
                            $plan = 'Plan B';
                            break;
                        }else if (str_contains($header->feeheadLabel, 'Plan C')) {
                            $plan = 'Plan C';
                            break;
                        }
                    }

                    if($plan != '') break;
                }
            }

            $type = '';
            if($request->get('paymode') != null && $plan == ''){
                $type = $request->get('paymode');
                $class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                ->where('idSection', '=', $student->idSection)
                ->where('idFinancialYear','=', $student->idFinancialYear)
                ->where('studentCategory', '=', $student->studentType)
                ->where('feeheadLabel', 'LIKE', $type.'%')
                ->whereNull('idStudent');
                $allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                        ->where('idSection', '=', $student->idSection)
                        ->where('studentCategory', '=', 'All')
                        ->where('idFinancialYear','=', $student->idFinancialYear)
                        ->where('feeheadLabel', 'LIKE', $type.'%')
                        ->whereNull('idStudent');
                $feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                        ->where('idFinancialYear','=', $student->idFinancialYear)
                        ->where('feeheadLabel', 'LIKE', $type.'%')
                        ->union($class_feeheads)
                        ->union($allcat_feeheads)
                        ->orderBy('idFeehead','ASC')
                        ->orderBy('toDate')
                        ->get();
                $feetotal = $feeheads->sum('amount');
                $feeheader_ids = $feeheads->pluck('idFeehead')->toArray();
                $lesser_transaction = DB::table('lesser_transaction')
                ->join('lesser_transaction_details', 'lesser_transaction_details.idLesserTransaction', '=', 'lesser_transaction.idLesserTransaction')
                ->where('lesser_transaction.idStudent', '=', $student->idStudent)
                ->where('lesser_transaction.idFinancialYear', '=', $student->idFinancialYear)
                ->whereIn('idFeehead', $feeheader_ids)
                ->where(function($query) {
                    $query->whereNull('lesser_transaction.status');
                    $query->orWhere('lesser_transaction.status', '=', 'Cleared');
                    $query->orWhere('lesser_transaction.status', '=', 'In-Process');
                    $query->orWhere('lesser_transaction.status', '=', 'Success');
                })
                ->select(DB::raw('SUM(totalPaid) as totalPaid'),DB::raw('SUM(lesser_transaction_details.discount) as discount'))
                ->first();

            }else if($plan != ''){
                $class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                ->where('idSection', '=', $student->idSection)
                ->where('idFinancialYear','=', $student->idFinancialYear)
                ->where('studentCategory', '=', $student->studentType)
                ->where('feeheadLabel', 'LIKE', $plan.'%')
                ->whereNull('idStudent');
                $allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                        ->where('idSection', '=', $student->idSection)
                        ->where('studentCategory', '=', 'All')
                        ->where('idFinancialYear','=', $student->idFinancialYear)
                        ->where('feeheadLabel', 'LIKE', $plan.'%')
                        ->whereNull('idStudent');
                $feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                        ->where('idFinancialYear','=', $student->idFinancialYear)
                        ->where('feeheadLabel', 'LIKE', $plan.'%')
                        ->union($class_feeheads)
                        ->union($allcat_feeheads)
                        ->orderBy('idFeehead','ASC')
                        ->orderBy('toDate')
                        ->get();
                $feetotal = $feeheads->sum('amount');
                $feeheader_ids = $feeheads->pluck('idFeehead')->toArray();
                $lesser_transaction = DB::table('lesser_transaction')
                ->join('lesser_transaction_details', 'lesser_transaction_details.idLesserTransaction', '=', 'lesser_transaction.idLesserTransaction')
                ->where('lesser_transaction.idStudent', '=', $student->idStudent)
                ->where('lesser_transaction.idFinancialYear', '=',$student->idFinancialYear)
                ->whereIn('idFeehead', $feeheader_ids)
                ->where(function($query) {
                    $query->whereNull('lesser_transaction.status');
                    $query->orWhere('lesser_transaction.status', '=', 'Cleared');
                    $query->orWhere('lesser_transaction.status', '=', 'In-Process');
                    $query->orWhere('lesser_transaction.status', '=', 'Success');
                })
                ->select(DB::raw('SUM(totalPaid) as totalPaid'),DB::raw('SUM(lesser_transaction_details.discount) as discount'),DB::raw('SUM(lesser_transaction_details.fine) as fine'))
                ->first();
            }
            $feeData = PaymentCalculation::calculateFee($student,$request);
            $sessionPending = 0;
            $idStudentSession = null;
            $fetchSession = \App\FinancialYear::where('idFinancialYear','<',$student->idFinancialYear)->where('idSchool', '=',$student->idSchool)->orderBy('idFinancialYear','DESC')->first();
            if($fetchSession != null){
                $studentSession = \App\AdmEntry::where('idSchool', '=', $student->idSchool)->where('idFinancialYear', '=', $fetchSession->idFinancialYear)->where('ecNo', '=', $student->ecNo)->where('isActive','Y')->first();
                if($studentSession != null){
                    $sessionPending = PaymentCalculation::getOutstandingAmount($studentSession,$request);
                }
            }
            return view('students.onlinefees.royal_feedetails', compact('sessionPending','feeData','fy','lesser_transaction', 'lesserfees', 'feetotal', 'paidfees_tot', 'student', 'paidfees', 'feeheads', 'type','plan'));
        }else
        {
            $class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                ->where('idSection', '=', $student->idSection)
                ->where('idFinancialYear', '=', $student->idFinancialYear)
                ->where('studentCategory', '=', $student->studentType)
                ->whereNull('idStudent');
            //   ->get();
            $allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                    ->where('idSection', '=', $student->idSection)
                    ->where('studentCategory', '=', 'All')
                    ->where('idFinancialYear', '=', $student->idFinancialYear)
                    ->whereNull('idStudent');
            //   ->get();
            $feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                    ->where('idFinancialYear', '=', $student->idFinancialYear)
                    ->union($class_feeheads)
                    ->union($allcat_feeheads)
                    ->orderBy('toDate')
                    ->get();
            $feetotal = $feeheads->sum('amount');
            $feeheader_ids = $feeheads->pluck('idFeehead')->toArray();
            $prevaccess_fee = DB::table('excess_transaction')
                            ->join('student_transaction', 'excess_transaction.idTransaction', '=', 'student_transaction.idTransaction')
                            ->where('idStudent', '=', $student->idStudent)
                            ->where('idFinancialYear', '=', $student->idFinancialYear)
                            ->where('excess_transaction.isActive', '=', 'Y')
                            ->orderBy('excess_transaction.idTransaction', 'desc')->first();
            $lesser_transaction = DB::table('lesser_transaction')
                    ->join('lesser_transaction_details', 'lesser_transaction_details.idLesserTransaction', '=', 'lesser_transaction.idLesserTransaction')
                    ->where('lesser_transaction.idStudent', '=', $student->idStudent)
                    ->where('lesser_transaction.idFinancialYear', '=', $student->idFinancialYear)
                    ->whereIn('idFeehead', $feeheader_ids)
                    ->where(function($query) {
                        $query->whereNull('lesser_transaction.status');
                        $query->orWhere('lesser_transaction.status', '=', 'Cleared');
                        $query->orWhere('lesser_transaction.status', '=', 'In-Process');
                        $query->orWhere('lesser_transaction.status', '=', 'Success');
                    })
                ->select(DB::raw('SUM(totalPaid) as totalPaid'))
                ->first();

            /*if($student->idSchool == 159 || $student->idSchool == 160)
            {
                if($student->idSchool == 159)
                $paymentMode = "easebuzz";    
                else $paymentMode = "easebuzz";  
                return view('students.onlinefees.mhws_college_feedetails', compact('lesser_transaction', 'lesserfees', 'feetotal', 'paidfees_tot', 'student', 'paidfees', 'feeheads', 'excesspaid', 'penalty', 'feeheadwiseamount', 'prevaccess_fee','paymentMode'));
            }
            else*/
            return view('students.onlinefees.feedetails', compact('lesser_transaction', 'lesserfees', 'feetotal', 'paidfees_tot', 'student', 'paidfees', 'feeheads',  'penalty', 'feeheadwiseamount', 'prevaccess_fee'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create() {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request) {
        exit;
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id) {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id) {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id) {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id) {
        //
    }

    public function testPayment() {
        return view('students.onlinefees.test');
    }

    public function feePaid(Request $request) {
        $student = \App\AdmEntry::where('idStudent', '=', Session::get('idStudent'))->first();
        $transactions = DB::table('student_transaction')
                ->join('students', 'student_transaction.idStudent', '=', 'students.idStudent')
                ->join('classes', 'students.idClass', '=', 'classes.idClass')
                ->join('sections', 'students.idSection', '=', 'sections.idSection')
                ->where('student_transaction.idStudent', '=', $student->idStudent)
                ->where('student_transaction.idFinancialYear', '=', $student->idFinancialYear)
                ->where(function($query) {
                    $query->whereNull('status');
                    $query->orWhere('status', '=', 'Cleared');
                    $query->orWhere('status', '=', 'Success');
                })
                ->select('ecNo', 'idTransaction', 'student_transaction.idFinancialYear', 'students.idClass', 'students.idStudent', 'students.idSection', 'firstName', 'middleName', 'contactPersonMobile', 'lastName', 'className', 'sectionName', 'father_fname', 'father_mobile', 'father_lname', 'receiptNo', 'paymentMode', 'totalPaid', 'penaltyAmount', 'discount', 'fine', 'penaltyRemarks', 'excessAmountUsed', 'paymentDate')
                ->get();
        if( $student->idSchool == 25)
        {
            $plan = '';
            $paidfees = \App\StudentTransaction::where('idStudent', '=', Session::get('idStudent'))
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'Success');
                        })->get();
            if($paidfees->count() > 0){
                foreach($paidfees as $paidfee){
                    $txns = \App\StudentTransactionDetail::where('idTransaction','=',$paidfee->idTransaction)->get();
                    foreach($txns as $transaction){
                        $header = \DB::table('feeheads')->where('idFeehead',$transaction->idFeehead)->first();
                        if (str_contains($header->feeheadName, 'Plan A')) {
                            $plan = 'Plan A';
                            break;
                        }else if (str_contains($header->feeheadName, 'Plan B')) {
                            $plan = 'Plan B';
                            break;
                        }else if (str_contains($header->feeheadName, 'Plan C')) {
                            $plan = 'Plan C';
                            break;
                        }
                    }

                    if($plan != '') break;
                }
            }

            if($plan == '') $plan = 'Plan A';

            $class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
            ->where('idSection', '=', $student->idSection)
            ->where('idFinancialYear','=', $student->idFinancialYear)
            ->where('studentCategory', '=', $student->studentType)
            ->where('feeheadName', 'LIKE', $plan.'%')
            ->whereNull('idStudent');
            $allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                    ->where('idSection', '=', $student->idSection)
                    ->where('studentCategory', '=', 'All')
                    ->where('idFinancialYear','=', $student->idFinancialYear)
                    ->where('feeheadName', 'LIKE', $plan.'%')
                    ->whereNull('idStudent');
            $feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                    ->where('idFinancialYear','=', $student->idFinancialYear)
                    ->where('feeheadName', 'LIKE', $plan.'%')
                    ->union($class_feeheads)
                    ->union($allcat_feeheads)
                    ->orderBy('idFeehead','ASC')
                    ->orderBy('toDate')
                    ->get();
            $feetotal = $feeheads->sum('amount');
            return view('students.feepaid_royal', compact('student', 'transactions','feetotal'));
        }else if( $student->idSchool == 135 || $student->idSchool == 140) 
        {
            $isFull = $request->get('paymode');
            return view('students.feepaid_mhws', compact('student','isFull', 'transactions'));
        }
        else return view('students.feepaid', compact('student', 'transactions'));
    }

    public function feePending(Request $request) {
        $student = \App\AdmEntry::where('idStudent', '=', Session::get('idStudent'))->first();
        if( $student->idSchool == 25)
        {
            $plan = '';
            $paidfees = \App\StudentTransaction::where('idStudent', '=', Session::get('idStudent'))
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'Success');
                        })->get();
            if($paidfees->count() > 0){
                foreach($paidfees as $paidfee){
                    $txns = \App\StudentTransactionDetail::where('idTransaction','=',$paidfee->idTransaction)->get();
                    foreach($txns as $transaction){
                        $header = \DB::table('feeheads')->where('idFeehead',$transaction->idFeehead)->first();
                        if (str_contains($header->feeheadName, 'Plan A')) {
                            $plan = 'Plan A';
                            break;
                        }else if (str_contains($header->feeheadName, 'Plan B')) {
                            $plan = 'Plan B';
                            break;
                        }else if (str_contains($header->feeheadName, 'Plan C')) {
                            $plan = 'Plan C';
                            break;
                        }
                    }

                    if($plan != '') break;
                }
            }

            if($plan == '') $plan = 'Plan A';

            $class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
            ->where('idSection', '=', $student->idSection)
            ->where('idFinancialYear','=', $student->idFinancialYear)
            ->where('studentCategory', '=', $student->studentType)
            ->where('feeheadName', 'LIKE', $plan.'%')
            ->whereNull('idStudent');
            $allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                    ->where('idSection', '=', $student->idSection)
                    ->where('studentCategory', '=', 'All')
                    ->where('idFinancialYear','=', $student->idFinancialYear)
                    ->where('feeheadName', 'LIKE', $plan.'%')
                    ->whereNull('idStudent');
            $feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                    ->where('idFinancialYear','=', $student->idFinancialYear)
                    ->where('feeheadName', 'LIKE', $plan.'%')
                    ->union($class_feeheads)
                    ->union($allcat_feeheads)
                    ->orderBy('idFeehead','ASC')
                    ->orderBy('toDate')
                    ->get();
            $feetotal = $feeheads->sum('amount');
            return view('students.feepending_royal', compact('student', 'feetotal'));
        }        
        else if( $student->idSchool == 135 || $student->idSchool == 140) 
        {
            $isFull = $request->get('paymode');
            return view('students.feepending_mhws', compact('student','isFull'));
        }
        else return view('students.feepending', compact('student'));
    }

    public function getFeewiseData($id, $studentId, Request $request) {
        $feeheader_ids = array_map('intval', explode(',', $id));
        //return $feeheader_ids;
        $student = \App\AdmEntry::where('idStudent', '=', $studentId)->first();
        if($student->idSchool == 25){
            return PaymentCalculation::calculateRoyal($id, $studentId,$request);
        }
        $chqbounce = \App\StudentTransaction::where('idStudent', '=', $student->idStudent)
                ->where('idFinancialYear', '=', $student->idFinancialYear)
                ->where('status', '=', 'Bounced')
                ->where('chqFineStatus', '=', '0')
                ->get();

        $penaltyAmount = 0;
        if (isset($chqbounce)) {
            foreach ($chqbounce as $chqFine)
                $penaltyAmount = $penaltyAmount + $chqFine->chequeBounceCharge;
        }

        $prev_transaction = \App\StudentTransaction::where('idStudent', '=', $student->idStudent)
                        ->where('idFinancialYear', '=', $student->idFinancialYear)
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })
                        ->orderBy('idTransaction', 'desc')->first();

        $excessAmount = 0;
        if (isset($prev_transaction))
            $excessAmount = $prev_transaction->excessAmount;

        $selectedHeaders = \App\FeeHead::whereIn('idFeehead', $feeheader_ids)->get();
        $totalAmount = 0;
        $amountDiscount = 0;


        $lessPaid = 0;
        $lesser_transaction = DB::table('lesser_transaction')
                ->join('lesser_transaction_details', 'lesser_transaction_details.idLesserTransaction', '=', 'lesser_transaction.idLesserTransaction')
                ->where('lesser_transaction.idStudent', '=', $student->idStudent)
                ->where('lesser_transaction.idFinancialYear', '=', $student->idFinancialYear)
                ->whereIn('idFeehead', $feeheader_ids)
                ->where(function($query) {
                    $query->whereNull('lesser_transaction.status');
                    $query->orWhere('lesser_transaction.status', '=', 'Cleared');
                    $query->orWhere('lesser_transaction.status', '=', 'In-Process');
                    $query->orWhere('lesser_transaction.status', '=', 'Success');
                })
                ->select(DB::raw('SUM(totalPaid) as totalPaid'))
                ->first();

        if (isset($lesser_transaction))
            $lessPaid = $lesser_transaction->totalPaid;

        for ($i = 0; $i < sizeof($selectedHeaders); $i++) {
            $stepFine = 0;
            $stepDiscount = 0;
            $stepAmount = 0;
            $headerObject = $selectedHeaders[$i];
            $date = Carbon::parse($headerObject['toDate']);
            $now = Carbon::now();
            $diff = $date->diffInDays($now, false);
            if ($diff > 0) {
                if ($headerObject['fine'] != null && $headerObject['fine'] != 0.00) {
                    $stepFine = ( $headerObject['fine'] * $diff);
                } else
                if ($headerObject['flatFine'] != null) {
                    if( $student->idSchool == 25){
                        if($now->format('M') != $date->format('M')){
                            $now->addMonth();
                            $months = $now->diffInMonths($date);
                            $stepFine = $stepFine + ($headerObject['flatFine'] * $months);
                        }else
                        $stepFine = $stepFine + $headerObject['flatFine'];
                    }else
                    $stepFine = $stepFine + $headerObject['flatFine'];
                }
            }

            $discountfees = DB::table('student_discounts')->where('idFinancialYear', '=', $student->idFinancialYear)->where('idStudent', '=', $student->idStudent)->where('idFeehead', '=', $headerObject['idFeehead'])->where('isActive', 'Y')->get();

            if (isset($discountfees)) {
                foreach ($discountfees as $discounts) {
                    $stepDiscount = $stepDiscount + $discounts->amount;
                    $amountDiscount = $amountDiscount + $stepDiscount;
                }
            }

            $totalAmount = $totalAmount + ( $headerObject['amount'] + $stepFine );
            $totalAmount = $totalAmount - $stepDiscount;
            $totalAmount = $totalAmount - $lessPaid;
        }

        $totalAmount = $totalAmount + $penaltyAmount;
        if ($totalAmount < $excessAmount)
            return 0;
        else
            return $totalAmount - $excessAmount;
    }

    public function makeBusPayment(Request $request){
        $student = \App\AdmEntry::where('idStudent', '=', $request->idStudent)->first();
        if($request->selectedHeaders == null){
            return response()->json(['message' => 'Please select a feeheader to continue']);
        }
        $now = Carbon::now();
        $penaltyAmount = 0;
        $payAmount = 0;
        $order = new \App\OrderReceipt();
        $order->fill($request->all());
        $order->idSchool = $student->idSchool;
        $order->idClass = $student->idClass;
        $order->order_note = 'Online Bus Fee Submission';
        $order->purpose = 'Fees';
        $order->notes = json_encode($request->all());
        $order->dateOfTransaction = today();

        if (count($request->selectedHeaders) > 1) {
            $order->isMultipleFeehead = 'Y';
            $order->feeheads = $request->selectedHeaders;

            foreach ($request->selectedHeaders as $idfee) {
                $details = \App\BusFeehead::where('idBusFeehead', '=', $idfee)->first();
                $transaction = \App\BusTransactionDetail::where('idBusFeehead','=',$idfee)->where('idStudent','=',$request->idStudent)->where('status','!=','Cancelled')->first();
                if($transaction != null){
                    return json_encode([]);
                }
                $totalAmount = $details->amount;
                $fineAmount = 0;
                $lastDate = Carbon::parse($details->toDate);
                $diff = $lastDate->diffInDays($now, false);
                if ($diff > 0) {
                    if ($details->fine != null)
                        $fineAmount = $diff * $details->fine + $fineAmount;
                    else if ($details->flatFine != null) {
                        if($student->idSchool == 25){
                            if($now->format('M') != $lastDate->format('M')){
                                $now->addMonth();
                                $months = $now->diffInMonths($lastDate);
                                $fineAmount = $fineAmount + ($details->flatFine * $months);
                            }else
                            $fineAmount = $details->flatFine + $fineAmount;
                        }else
                        $fineAmount = $details->flatFine + $fineAmount;
                    }
                }
                $payAmount = $payAmount + $totalAmount + $fineAmount;
                $penaltyAmount = $penaltyAmount + $fineAmount;
                $order->order_amount = $payAmount;
                $order->fine_amount = $penaltyAmount;
            }
        } else {
            $order->isMultipleFeehead = 'N';
            $order->idFeehead = $request->selectedHeaders[0];
            foreach ($request->selectedHeaders as $idfee) {
                $details = \App\BusFeehead::where('idBusFeehead', '=', $idfee)->first();
                $transaction = \App\BusTransactionDetail::where('idBusFeehead','=',$idfee)->where('idStudent','=',$request->idStudent)->where('status','!=','Cancelled')->first();
                if($transaction != null){
                    return json_encode([]);
                }
                $totalAmount = $details->amount;
                $fineAmount = 0;
                $lastDate = Carbon::parse($details->toDate);
                $diff = $lastDate->diffInDays($now, false);
                if ($diff > 0) {
                    if ($details->fine != null && $details->fine > 0)
                        $fineAmount = $diff * $details->fine + $fineAmount;
                    else if ($details->flatFine != null) {
                        if($student->idSchool == 25){
                            if($now->format('M') != $lastDate->format('M')){
                                $now->addMonth();
                                $months = $now->diffInMonths($lastDate);
                                $fineAmount = $fineAmount + ($details->flatFine * $months);
                            }else
                            $fineAmount = $details->flatFine + $fineAmount;
                        }else
                        $fineAmount = $details->flatFine + $fineAmount;
                    }
                }
                $payAmount = $payAmount + $totalAmount + $fineAmount;
                $penaltyAmount = $penaltyAmount + $fineAmount;
                $order->order_amount = $payAmount;
                $order->fine_amount = $penaltyAmount;
            }
        }
        $order->type = "Bus";
        $order->save();
        return Cashfree::generateEaseBuzzOrder($order, $student);
    }


    public function makePayment(Request $request){
        $student = \App\AdmEntry::where('idStudent', '=', $request->idStudent)->first();
        if($request->selectedHeaders == null){
            return response()->json(['message' => 'Please select a feeheader to continue']);
        }
        $now = Carbon::now();
        $penaltyAmount = 0;
        $payAmount = 0;
        $order = new \App\OrderReceipt();
        $order->fill($request->all());
        $order->idSchool = $student->idSchool;
        $order->idClass = $student->idClass;
        $order->order_note = 'Online Fee Submission';
        $order->purpose = 'Fees';
        $order->notes = json_encode($request->all());
        $order->dateOfTransaction = today();

        if(isset($request->type)){
            if (count($request->selectedHeaders) > 1) {
                $order->isMultipleFeehead = 'Y';
                $order->feeheads = $request->selectedHeaders;
    
                foreach ($request->selectedHeaders as $idfee) {
                    $details = \App\ExtraFeehead::where('idExtraFeehead', '=', $idfee)->first();
                    $totalAmount = $details->amount;
                    $fineAmount = 0;
                    $lastDate = Carbon::parse($details->toDate);
                    $diff = $lastDate->diffInDays($now, false);
                    if ($diff > 0) {
                        if ($details->fine != null)
                            $fineAmount = $diff * $details->fine + $fineAmount;
                        else if ($details->flatFine != null) {
                            $fineAmount = $details->flatFine + $fineAmount;
                        }
                    }
                    $payAmount = $payAmount + $totalAmount + $fineAmount;
                    $penaltyAmount = $penaltyAmount + $fineAmount;
                    $order->order_amount = $payAmount;
                    $order->fine_amount = $penaltyAmount;
                }
            } else {
                $order->isMultipleFeehead = 'N';
                $order->idFeehead = $request->selectedHeaders[0];
                foreach ($request->selectedHeaders as $idfee) {
                    $details = \App\ExtraFeehead::where('idExtraFeehead', '=', $idfee)->first();
                    $totalAmount = $details->amount;
                    $fineAmount = 0;
                    $lastDate = Carbon::parse($details->toDate);
                    $diff = $lastDate->diffInDays($now, false);
                    if ($diff > 0) {
                        if ($details->fine != null)
                            $fineAmount = $diff * $details->fine + $fineAmount;
                        else if ($details->flatFine != null) {
                            $fineAmount = $details->flatFine + $fineAmount;
                        }
                    }
                    $payAmount = $payAmount + $totalAmount + $fineAmount;
                    $penaltyAmount = $penaltyAmount + $fineAmount;
                    $order->order_amount = $payAmount;
                    $order->fine_amount = $penaltyAmount;
                }
            }
        }else{
            if (count($request->selectedHeaders) > 1) {
                $order->isMultipleFeehead = 'Y';
                $order->feeheads = $request->selectedHeaders;
    
                foreach ($request->selectedHeaders as $idfee) {
                    $details = \App\FeeHead::where('idFeehead', '=', $idfee)->first();
                    $transaction = \App\StudentTransactionDetail::where('idFeehead','=',$idfee)->where('idStudent','=',$request->idStudent)->where('status','!=','Cancelled')->first();
                    if($transaction != null){
                        return json_encode([]);
                    }
                    $totalAmount = $details->amount;
                    $fineAmount = 0;
                    $lastDate = Carbon::parse($details->toDate);
                    $diff = $lastDate->diffInDays($now, false);
                    if ($diff > 0) {
                        if ($details->fine != null)
                            $fineAmount = $diff * $details->fine + $fineAmount;
                        else if ($details->flatFine != null) {
                            if($student->idSchool == 25){
                                if($now->format('M') != $lastDate->format('M')){
                                    $now->addMonth();
                                    $months = $now->diffInMonths($lastDate);
                                    $fineAmount = $fineAmount + ($details->flatFine * $months);
                                }else
                                $fineAmount = $details->flatFine + $fineAmount;
                            }else
                            $fineAmount = $details->flatFine + $fineAmount;
                        }
                    }
                    $payAmount = $payAmount + $totalAmount + $fineAmount;
                    $penaltyAmount = $penaltyAmount + $fineAmount;
                    $order->order_amount = $payAmount;
                    $order->fine_amount = $penaltyAmount;
                }
            } else {
                $order->isMultipleFeehead = 'N';
                $order->idFeehead = $request->selectedHeaders[0];
                foreach ($request->selectedHeaders as $idfee) {
                    $details = \App\FeeHead::where('idFeehead', '=', $idfee)->first();
                    $transaction = \App\StudentTransactionDetail::where('idFeehead','=',$idfee)->where('idStudent','=',$request->idStudent)->where('status','!=','Cancelled')->first();
                    if($transaction != null){
                        return json_encode([]);
                    }
                    $totalAmount = $details->amount;
                    $fineAmount = 0;
                    $lastDate = Carbon::parse($details->toDate);
                    $diff = $lastDate->diffInDays($now, false);
                    if ($diff > 0) {
                        if ($details->fine != null && $details->fine > 0)
                            $fineAmount = $diff * $details->fine + $fineAmount;
                        else if ($details->flatFine != null) {
                            if($student->idSchool == 25){
                                if($now->format('M') != $lastDate->format('M')){
                                    $now->addMonth();
                                    $months = $now->diffInMonths($lastDate);
                                    $fineAmount = $fineAmount + ($details->flatFine * $months);
                                }else
                                $fineAmount = $details->flatFine + $fineAmount;
                            }else
                            $fineAmount = $details->flatFine + $fineAmount;
                        }
                    }
                    $payAmount = $payAmount + $totalAmount + $fineAmount;
                    $penaltyAmount = $penaltyAmount + $fineAmount;
                    $order->order_amount = $payAmount;
                    $order->fine_amount = $penaltyAmount;
                }
            }
        }
        //return json_encode([]);
        if(isset($request->type)){
            $order->type = "extra";
        }

        $order->save();
        return Cashfree::generateEaseBuzzOrder($order, $student);

        /*
        $totalAmount = $payAmount;// . '00';
        $post = [
            'order_id' => 'rcptid' . $order->idOrder, 
            'amount' => $totalAmount, 
            'customer_id' => $student->idStudent."TON".$student->idSchool,
            'customer_email' => 'sppedtrackgps@gmail.com',
            'customer_phone' => $student->father_mobile,
            'payment_page_client_id' => 'roin',
            'return_url' => 'https://online-login.online/juspay/return',
            'action' => 'paymentPage'
        ];
        $client = new Client();
        $response = $client->request('POST', 'https://api.juspay.in/session', ['headers' => ['Authorization' => 'Basic '.base64_encode("069A05342E3495E8B686A0AFAF425F:"), 'x-merchantid' => 'ROIN', 'Content-Type' => 'application/json'],'body' => json_encode($post)]);
        $data = $response->getBody();
        DB::table('order_receipts')->where('idOrder', $order->idOrder)->update(['order_id' => 'rcptid'. $order->idOrder]);
        return $data;*/
        //return json_encode(['data' => $post, 'item' => json_decode($data,true), 'auth' =>'Basic '.base64_encode("069A05342E3495E8B686A0AFAF425F:")]); 
        /*$client = new Client();
        $response = $client->request('POST', 'https://api.razorpay.com/v1/orders', ['headers' => ['Accept' => 'application/json'], 'auth' => ['rzp_live_3pII9YBnGYch65', '1GDg04NimKEWNFMqW8OJeGAa'], 'form_params' => ['amount' => $totalAmount, 'currency' => "INR", 'receipt' => 'rcptid_' . $order->idOrder, 'payment_capture' => "1"]]);
        $data = json_decode($response->getBody());
        $data->idOrder = $order->idOrder;
        DB::table('order_receipts')->where('idOrder', $order->idOrder)->update(['order_id' => $data->id]);
        return response()->json($data, 200);*/
        
    }

    public function addTransaction(Request $request) {
        $onlineData = array();
        $onlineData['idStudent'] = $request->idStudent;
        $onlineData['idFinancialYear'] = $request->idFinancialYear;
        if (isset($request->mrctTxtID))
            $onlineData['idReference'] = $request->mrctTxtID;
        else
            $onlineData['idReference'] = $request->CustomerID;
        if (isset($request->tpsl_txn_id))
            $onlineData['onlineTransactionId'] = $request->tpsl_txn_id;
        $onlineData['code'] = 0;
        $onlineData['created_at'] = Carbon::now();
        $onlineData['payableAmount'] = $request->payableAmount;
        if (isset($request->fineAmount))
            $onlineData['penaltyAmount'] = $request->fineAmount;
        $onlineData['amount'] = $request->TxnAmount;
        $onlineData['idFeehead'] = json_encode($request->selectedHeaders);
        $insertTransaction = DB::table('student_transaction_online')->insert(
                $onlineData
        );
        if ($insertTransaction)
            return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
        else
            return response()->json(['success' => "failed"], 201, ['app-status' => 'failed']);
    }

    public function printBooksReceipt($id){
        $student = \App\AdmEntry::where('idStudent', '=', Session::get('idStudent'))->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        $feeHead = \App\StudentTransactionDetail::join('feeheads', 'student_transaction_details.idFeehead', '=', 'feeheads.idFeehead')->where('idTransaction', '=', substr($id,0,-2))->first();
        if($feeHead != null){
            if(str_contains($feeHead->feeheadName, "Full Payment") && $feeHead->idFinancialYear == 244){
                $transaction = \App\StudentTransaction::where('idTransaction', '=', substr($id,0,-2))->first();
                $pdf = PDF::loadView('schools.transaction.book_print_receipt', ['margin_top' => 20], compact('transaction', 'school', 'student', 'feetotal'));
                return $pdf->stream('feereceipt.pdf');
            }
        }
        return redirect()->back();
    }

    public function printReceipt($id) {
        $student = \App\AdmEntry::where('idStudent', '=', Session::get('idStudent'))->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        $transaction = \App\StudentTransaction::where('idTransaction', '=', $id)->first();
        $class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                ->where('idSection', '=', $student->idSection)
                ->where('studentCategory', '=', $student->studentType)
                ->whereNull('idStudent');
        //   ->get();
        $allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                ->where('idSection', '=', $student->idSection)
                ->where('studentCategory', '=', 'All')
                ->whereNull('idStudent');
        //   ->get();
        $feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                ->union($class_feeheads)
                ->union($allcat_feeheads)
                ->orderBy('toDate')
                ->get();
        $feetotal = $feeheads->sum('amount');

        $pdf = PDF::loadView('schools.transaction.print_receipt', ['margin_top' => 20], compact('transaction', 'school', 'student', 'feetotal'));
        return $pdf->stream('feereceipt.pdf');
    }

    public function lesserAmtReceipt($id) {
        $student = \App\AdmEntry::where('idStudent', '=', Session::get('idStudent'))->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        $transaction = \App\LesserTransaction::where('idLesserTransaction', '=', $id)->first();
        $class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                ->where('idSection', '=', $student->idSection)
                ->where('studentCategory', '=', $student->studentType)
                ->whereNull('idStudent');
        //   ->get();
        $allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                ->where('idSection', '=', $student->idSection)
                ->where('studentCategory', '=', 'All')
                ->whereNull('idStudent');
        //   ->get();
        $feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                ->union($class_feeheads)
                ->union($allcat_feeheads)
                ->orderBy('toDate')
                ->get();
        $feetotal = $feeheads->sum('amount');

        $pdf = PDF::loadView('schools.transaction.print_lesseramt_receipt', ['margin_top' => 20], compact('transaction', 'school', 'student', 'feetotal'));
        return $pdf->stream('feereceipt.pdf');
    }


    public function generateShopOrder(){
        $payAmount = 0;
        $penaltyAmount = 0;
        $totalHeaders = 0;
        $order = [];
        $student = \App\AdmEntry::where('idStudent', '=', Session::get('idStudent'))->first();
        $cart =  DB::table('order_cart')->select('idProduct','qty')->where('idStudent','=', Session::get('idStudent'))->get()->toArray();
        foreach($cart as $idfee){
            $product =  \App\Product::where('idProduct',$idfee->idProduct)->first();
            if($product != null){
                $price = $idfee->qty * $product->salePrice;
                $payAmount = $payAmount + $price;
                if (str_contains($product->productName, 'Books') || str_contains($product->productName, 'BOOKS')) {
                    $order['purpose'] = 'Books';
                }
                if (str_contains($product->productName, 'Uniform')) {
                    $order['purpose'] = 'Uniform';
                }
            }
        }
        $order['idStudent']=$student->idStudent;
        $order['idSchool']=$student->idSchool;
        $order['idFinancialYear']=$student->idFinancialYear;
        $order['idClass']= $student->idClass;
        $order['isMultipleFeehead'] = "Y";
        $order['idFeehead']= 0;
        $order['type']= "Shop";
        $order['feeheads']= json_encode($cart);
        $order['dateOfTransaction'] = Carbon::now()->format('Y-m-d');
        $order['order_amount'] = $payAmount;
        $order['fine_amount'] = $penaltyAmount;

        /*if($student->idSchool == 135 || $student->idSchool == 159 || $student->idSchool == 160 || $student->idSchool == 140){
            $idOrder = DB::table('order_receipts')->insertGetId($order);
            $orderDetails = DB::table('order_receipts')->where('idOrder',$idOrder)->first();
            $response =  Cashfree::generateEaseBuzzOrder($orderDetails, $student);
            $idOrder = DB::table('order_receipts')->where('idOrder',$idOrder)->update(
                ["order_id" => $response->data]
            );
            return $response;
        }*/  
        
        $idOrder = DB::table('order_receipts')->insertGetId($order);
        $orders = \App\OrderReceipt::where('idOrder',$idOrder)->first();
        return Cashfree::generateEaseBuzzOrder($orders, $student);
    }

    public function generateCanteenOrder(){
        $payAmount = 0;
        $penaltyAmount = 0;
        $totalHeaders = 0;
        $order = [];
        $student = \App\AdmEntry::where('idStudent', '=', Session::get('idStudent'))->first();
        $cart =  DB::table('order_cart_food')->select('idProduct','qty')->where('idStudent','=', Session::get('idStudent'))->get()->toArray();
        foreach($cart as $idfee){
            $product =  \App\Food::select('id as idProduct','item_name as productName','pic as productImage','price as salePrice','idSchool','max_buy as max')->where('id',$idfee->idProduct)->first();
            if($product != null){
                $price = $idfee->qty * $product->salePrice;
                $payAmount = $payAmount + $price;
            }
        }
        $order['idStudent']=$student->idStudent;
        $order['idSchool']=$student->idSchool;
        $order['idFinancialYear']=$student->idFinancialYear;
        $order['idClass']= $student->idClass;
        $order['isMultipleFeehead'] = "Y";
        $order['idFeehead']= 0;
        $order['type']= "Food";
        $order['purpose']= "Food";
        $order['feeheads']= json_encode($cart);
        $order['dateOfTransaction'] = Carbon::now()->format('Y-m-d');
        $order['order_amount'] = $payAmount;
        $order['fine_amount'] = $penaltyAmount;

        if($payAmount == 0){
            $feedback["message"] ="Add items to continue";
            return response()->json(['message' => $feedback["message"]],404);
        }

        $foodVendor = \App\FoodVendor::where('idSchool', $student->idSchool)->where('idFinancialYear', $student->idFinancialYear)->first();
            if($foodVendor == null){
                $feedback["result"] = "0";
                $feedback["message"] ="You have not registered any vendor deliver your order. Please contact the administrator";
                return response()->json(['message' => $feedback["message"]],404);
            }

            $orderEndTime = explode("-",$foodVendor ->order_time);
            if(count($orderEndTime) > 1){
                $now = Carbon::now()->format('d-m-Y');
                $endTime = Carbon::parse($now.' '.$orderEndTime[1].':00');
                $currentTime =  Carbon::now();
                $are_different = $currentTime->gt($endTime);
                if($are_different){
                    $feedback["result"] = "0";
                    $feedback["message"] ="Vendor is not closed for taking any new order right now.Please try again tomorrow";
                    return response()->json(['message' => $feedback["message"]],404);
                }
            }else{
                $feedback["result"] = "0";
                $feedback["message"] = "Vendor is not taking any new order right now";
                return response()->json(['message' => $feedback["message"]],404);
            }

            $shopReceipt = \App\FoodTransaction::where('idStudent', '=', $student->idStudent)->where('idFinancialYear','=',$student->idFinancialYear)
            ->where(function($query) {
                $query->whereNull('status');
                $query->orWhere('status', '=', 'In-Process');
                $query->orWhere('status', '=', 'Cleared');
                $query->orWhere('status', '=', 'Success');
            })
            ->whereDate('paymentDate',Carbon::now()->format('Y-m-d'))
            ->first();

            if($shopReceipt != null){
                $feedback["result"] = "0";
                $feedback["message"] = "You have already placed your order. Please try again tomorrow";
                return response()->json(['message' => $feedback["message"]],404);
            }

        /*if($student->idSchool == 135 || $student->idSchool == 159 || $student->idSchool == 160 || $student->idSchool == 140){
            $idOrder = DB::table('order_receipts')->insertGetId($order);
            $orderDetails = DB::table('order_receipts')->where('idOrder',$idOrder)->first();
            $response =  Cashfree::generateEaseBuzzOrder($orderDetails, $student);
            $idOrder = DB::table('order_receipts')->where('idOrder',$idOrder)->update(
                ["order_id" => $response->data]
            );
            return $response;
        }*/  

        
        
        $idOrder = DB::table('order_receipts')->insertGetId($order);
        $orders = \App\OrderReceipt::where('idOrder',$idOrder)->first();
        return Cashfree::generateEaseBuzzOrder($orders, $student);
    }

    public function generateEaseBuzz(Request $request){
        $student = \App\AdmEntry::where('idStudent', '=', $request->idStudent)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        //check if school enabled payment
        if($school->pg_start != null && $school->pg_stop != null){
            $kolkataTimezone = 'Asia/Kolkata';
            $nowKolkata = Carbon::now($kolkataTimezone);
            $start = Carbon::parse($school->pg_start, $kolkataTimezone);
            $end = Carbon::parse($school->pg_stop, $kolkataTimezone);
            if($nowKolkata->between($start, $end)){
                $feedback["result"] = "0";
                $feedback["message"] = "Online payment has been stopped by administrator.";
                return response()->json(['message' => $feedback["message"]],404);
            }
        }
        if(isset($request->type)) return $this->generateBusFees($request);
        $penaltyAmount = 0;
        $payAmount = 0;
        $mainFee = 0;
        $data['installment'] = 0;
        $data['p2'] = 0;
        $now = Carbon::now();
        $order = new \App\OrderReceipt();
        $order->fill($request->all());
        $order->idSchool = $student->idSchool;
        $order->idClass = $student->idClass;
        $order->order_note = 'Online Fee Submission';
        $order->purpose = 'Fees';
        if($student->idSchool == 135){
            $classes = array("1046", "1047", "1048");
            if (in_array($student->idClass, $classes)){
                $order->purpose = 'Pre Fees';
            }
            $classes = array("1065", "1316", "1391");
            if (in_array($student->idClass, $classes)){
                $order->purpose = 'Post Fees';
            }
        }
        if($student->idSchool == 181){
            $classes = array("1438", "1434", "1439", "1440");
            if (in_array($student->idClass, $classes)){
                $order->purpose = 'Pre Fees';
            }
            $classes = array("1422", "1423", "1424", "1425", "1426", "1427");
            if (in_array($student->idClass, $classes)){
                $order->purpose = 'Fees';
            }
        }

        if($student->idSchool == 39){
            $classes = array("406", "407");
            if (in_array($student->idClass, $classes)){
                $order->purpose = 'Pre Fees';
            }
            $classes = array("408", "409", "410", "411", "412", "413","414",'415');
            if (in_array($student->idClass, $classes)){
                $order->purpose = 'Fees';
            }
            $classes = array("416", "417");
            if (in_array($student->idClass, $classes)){
                $order->purpose = 'Post Fees';
            }
        }
        $order->notes = json_encode($request->all());
        $order->dateOfTransaction = today();
        if (count($request->selectedHeaders) > 1) {
            $order->isMultipleFeehead = 'Y';
            $order->feeheads = implode(",", $request->selectedHeaders);
            $feeheaders = [];
            foreach ($request->selectedHeaders as $idfee) {
                $details = \App\FeeHead::where('idFeehead', '=', $idfee)->first();
                if(str_contains($details->feeheadName, "Full Payment")){
                    $mainFee++;
                }
                if(str_contains($details->feeheadName, "Installment")){
                    $mainFee++;
                    if(str_contains($details->feeheadName, "Second Installment"))
                    $data['installment'] = $data['installment'] + 1;
                }
                if(str_contains($details->feeheadName, "Admission")){
                    $mainFee++;
                }
                if(str_contains($details->feeheadName, "environment")){
                    $mainFee = 2;
                }
                if(str_contains($details->feeheadName, "P1")){
                    $mainFee++;
                }
                if(str_contains($details->feeheadName, "P2")){
                    $data['p2'] = 1;
                }
                $totalAmount = $details->amount;
                $fineAmount = 0;
                $lastDate = Carbon::parse($details->toDate);
                $diff = $lastDate->diffInDays($now, false);
                if ($diff > 0) {
                    if ($details->fine != null)
                        $fineAmount = $diff * $details->fine + $fineAmount;
                    else if ($details->flatFine != null) {
                        $fineAmount = $details->flatFine + $fineAmount;
                    }
                }
                $payAmount = $payAmount + $totalAmount + $fineAmount;
                $penaltyAmount = $penaltyAmount + $fineAmount;
                $order->order_amount = $payAmount;
                $order->fine_amount = $penaltyAmount;
                array_push($feeheaders,intval($idfee));
            }
            $order->feeheads = json_encode($feeheaders);

            if($student->idSchool != 140 && $student->idSchool != 160){
                if($data['p2'] == 1 && $mainFee == 1){

                }else{
                    $feedback["result"] = "0";
                    $feedback["message"] = "Plese select the fee installment or full payment to pay amount.";
                    return response()->json(['message' => $feedback["message"]],404);
                }
            }else{
                if($student->idSchool == 140){
                    if($data['installment'] == 0 && $data['p2'] == 1){
                        $feedback["result"] = "0";
                        $feedback["message"] = "Plese select the fee installment or full payment to pay amount with P2.";
                        return response()->json(['message' => $feedback["message"]],404);
                    }
                }
            }
            

        } else {
            $order->isMultipleFeehead = 'N';
            $order->idFeehead = $request->selectedHeaders['0'];
            foreach ($request->selectedHeaders as $idfee) {
                $details = \App\FeeHead::where('idFeehead', '=', $idfee)->first();
                if(str_contains($details->feeheadName, "Full Payment")){
                    $mainFee++;
                }
                if(str_contains($details->feeheadName, "Installment")){
                    $mainFee++;
                    if(str_contains($details->feeheadName, "Second Installment"))
                    $data['installment'] = $data['installment'] + 1;
                }
                if(str_contains($details->feeheadName, "Admission")){
                    $mainFee = 2;
                }
                if(str_contains($details->feeheadName, "P1")){
                    $mainFee++;
                }
                if(str_contains($details->feeheadName, "P2")){
                    $data['p2'] = 1;
                }
                $totalAmount = $details->amount;
                $fineAmount = 0;
                $lastDate = Carbon::parse($details->toDate);
                $diff = $lastDate->diffInDays($now, false);
                if ($diff > 0) {
                    if ($details->fine != null)
                        $fineAmount = $diff * $details->fine + $fineAmount;
                    else if ($details->flatFine != null) {
                        $fineAmount = $details->flatFine + $fineAmount;
                    }
                }
                $payAmount = $payAmount + $totalAmount + $fineAmount;
                $penaltyAmount = $penaltyAmount + $fineAmount;
                $order->order_amount = $payAmount;
                $order->fine_amount = $penaltyAmount;
            }
            if($data['p2'] == 1 && $data['installment'] == 0){
                $transaction = new \Illuminate\Database\Eloquent\Collection;
                $paidfees = \App\StudentTransaction::where('idStudent', '=', $request->id)->where('idFinancialYear','=',$student->idFinancialYear)
                ->where(function($query) {
                    $query->whereNull('status');
                    $query->orWhere('status', '=', 'In-Process');
                    $query->orWhere('status', '=', 'Cleared');
                    $query->orWhere('status', '=', 'Success');
                })
                ->get();
                $transaction = $transaction->merge($paidfees);
                foreach($transaction as $transact){
                    $feeHead = \App\StudentTransactionDetail::join('feeheads', 'student_transaction_details.idFeehead', '=', 'feeheads.idFeehead')->where('idTransaction', '=', $transact->idTransaction)->get();
                    if(count($feeHead) > 0){
                        foreach($feeHead as $header){
                            if(str_contains($header->feeheadName, "Full Payment") || $header->feeheadName == "Plan A (Full Payment)"){
                                $mainFee = 3;
                                break;
                            }
                        }
                    }
                }
            }
            if($student->idSchool != 140 && $student->idSchool != 160){
                if($mainFee < 2){
                    if($data['p2'] == 1 && $mainFee == 1){

                    }else{
                        $feedback["result"] = "0";
                        $feedback["message"] = "Plese select the fee installment or full payment to pay amount.";
                        return response()->json(['message' => $feedback["message"]],404);
                    }
                }
            }else{
                if($student->idSchool == 140){
                    if($data['installment'] == 0 && $data['p2'] == 1){
                        $feedback["result"] = "0";
                        $feedback["message"] = "Plese select the fee installment or full payment to pay amount with P2.";
                        return response()->json(['message' => $feedback["message"]],404);
                    }
                }
            }
        }
        $order->save();
        return Cashfree::generateEaseBuzzOrder($order, $student);
    }

    public function generateBusFees(Request $request){
        $student = \App\AdmEntry::where('idStudent', '=', $request->idStudent)->first();
        $penaltyAmount = 0;
        $payAmount = 0;
        $mainFee = 0;
        $data['installment'] = 0;
        $data['p2'] = 0;
        $now = Carbon::now();
        $order = new \App\OrderReceipt();
        $order->fill($request->all());
        $order->idSchool = $student->idSchool;
        $order->idClass = $student->idClass;
        $order->order_note = 'Bus';
        $order->purpose = 'Bus';
        $order->type= "Bus";
        $order->notes = json_encode($request->all());
        $order->dateOfTransaction = today();
        if (count($request->selectedHeaders) > 1) {
            $order->isMultipleFeehead = 'Y';
            $order->feeheads = implode(",", $request->selectedHeaders);
            $feeheaders = [];
            foreach ($request->selectedHeaders as $idfee) {
                $details = \App\BusFeehead::where('idBusFeehead', '=', $idfee)->first();
                $totalAmount = $details->amount;
                $fineAmount = 0;
                $lastDate = Carbon::parse($details->toDate);
                $diff = $lastDate->diffInDays($now, false);
                if ($diff > 0) {
                    if ($details->fine != null)
                        $fineAmount = $diff * $details->fine + $fineAmount;
                    else if ($details->flatFine != null) {
                        $fineAmount = $details->flatFine + $fineAmount;
                    }
                }
                $payAmount = $payAmount + $totalAmount + $fineAmount;
                $penaltyAmount = $penaltyAmount + $fineAmount;
                $order->order_amount = $payAmount;
                $order->fine_amount = $penaltyAmount;
                array_push($feeheaders,intval($idfee));
            }
            $order->feeheads = json_encode($feeheaders);
        } else {
            $order->isMultipleFeehead = 'N';
            $order->idFeehead = $request->selectedHeaders['0'];
            foreach ($request->selectedHeaders as $idfee) {
                $details = \App\BusFeehead::where('idBusFeehead', '=', $idfee)->first();
                $totalAmount = $details->amount;
                $fineAmount = 0;
                $lastDate = Carbon::parse($details->toDate);
                $diff = $lastDate->diffInDays($now, false);
                if ($diff > 0) {
                    if ($details->fine != null)
                        $fineAmount = $diff * $details->fine + $fineAmount;
                    else if ($details->flatFine != null) {
                        $fineAmount = $details->flatFine + $fineAmount;
                    }
                }
                $payAmount = $payAmount + $totalAmount + $fineAmount;
                $penaltyAmount = $penaltyAmount + $fineAmount;
                $order->order_amount = $payAmount;
                $order->fine_amount = $penaltyAmount;
            }
        }
        $order->save();
        return Cashfree::generateEaseBuzzOrder($order, $student);
    }

    public function generateCashfreeOrder(Request $request) {
        return response()->json(['message' => 'Failed to verify your payment.'],404);
//        dd($request->all());
        $student = \App\AdmEntry::where('idStudent', '=', $request->idStudent)->first();
//        $idfeeheads = [];
        $penaltyAmount = 0;
        $payAmount = 0;
        $now = Carbon::now();
        $order = new \App\OrderReceipt();
        $order->fill($request->all());
        $order->idSchool = $student->idSchool;
        $order->idClass = $student->idClass;
        $order->order_note = 'Online Fee Submission';
        $order->notes = json_encode($request->all());
        $order->dateOfTransaction = today();
        if (count($request->selectedHeaders) > 1) {
            $order->isMultipleFeehead = 'Y';
            $order->feeheads = implode(",", $request->selectedHeaders);
            $feeheaders = [];
            foreach ($request->selectedHeaders as $idfee) {
                $details = \App\FeeHead::where('idFeehead', '=', $idfee)->first();
                $totalAmount = $details->amount;
                $fineAmount = 0;
                $lastDate = Carbon::parse($details->toDate);
                $diff = $lastDate->diffInDays($now, false);
                if ($diff > 0) {
                    if ($details->fine != null)
                        $fineAmount = $diff * $details->fine + $fineAmount;
                    else if ($details->flatFine != null) {
                        $fineAmount = $details->flatFine + $fineAmount;
                    }
                }
                $payAmount = $payAmount + $totalAmount + $fineAmount;
                $penaltyAmount = $penaltyAmount + $fineAmount;
                $order->order_amount = $payAmount;
                $order->fine_amount = $penaltyAmount;
                array_push($feeheaders,$idfee);
            }
            $order->feeheads = json_encode($feeheaders);
        } else {
            $order->isMultipleFeehead = 'N';
            $order->idFeehead = $request->selectedHeaders['0'];
            foreach ($request->selectedHeaders as $idfee) {
                $details = \App\FeeHead::where('idFeehead', '=', $idfee)->first();
                $totalAmount = $details->amount;
                $fineAmount = 0;
                $lastDate = Carbon::parse($details->toDate);
                $diff = $lastDate->diffInDays($now, false);
                if ($diff > 0) {
                    if ($details->fine != null)
                        $fineAmount = $diff * $details->fine + $fineAmount;
                    else if ($details->flatFine != null) {
                        $fineAmount = $details->flatFine + $fineAmount;
                    }
                }
                $payAmount = $payAmount + $totalAmount + $fineAmount;
                $penaltyAmount = $penaltyAmount + $fineAmount;
                $order->order_amount = $payAmount;
                $order->fine_amount = $penaltyAmount;
            }
        }
        $order->save();
        $totalAmount = $payAmount . '00';
        if ($student->idSchool == 140 || $student->idSchool == 159 || $student->idSchool == 160) {
            return response()->json(['message' => 'Failed to verify your payment.'],404);
            //return Cashfree::generateOrder($order, $student);

            //return Cashfree::generateEaseBuzzOrder($order, $student);
        } else {
            return response()->json(['message' => 'Failed to verify your payment.'],404);
            $client = new Client();
            $response = $client->request('POST', 'https://api.razorpay.com/v1/orders', ['headers' => ['Accept' => 'application/json'], 'auth' => ['rzp_live_4gUv0qKqI3I7an', 'V0XtNlgExrR9eM8xlek987MO'], 'form_params' => ['amount' => $totalAmount, 'currency' => "INR", 'receipt' => 'rcptid_' . $order->idOrder, 'payment_capture' => "1"]]);
            $data = json_decode($response->getBody());
            $data->idOrder = $order->idOrder;
            DB::table('order_receipts')->where('idOrder', $order->idOrder)->update(['order_id' => $data->id]);
            return response()->json($data, 200);
        }
//        return Cashfree::generateOrder($order, $student);
    }

    public function updateRaorpay(Request $request){
        if($request->isPaid == 0){
            DB::table('order_receipts')->where('order_id', $request->idOrder)->update(['notes' => $request->reason, 'order_note' => "Failed"]);
            return response()->json(['message' => 'Failed to verify your payment.']);
        }
        $key_secret = "V0XtNlgExrR9eM8xlek987MO";
        $str_key = $request->razorpay_order_id."|".$request->razorpay_payment_id;
        $generated_signature = hash_hmac('sha256',$str_key, $key_secret);
        if ($generated_signature == $request->razorpay_signature) {
            $orderInfo = DB::table('order_receipts')->where('order_id', $request->razorpay_order_id)->first();
            $stdtransaction = new \App\StudentTransaction();
            $stdtransaction->idStudent = $orderInfo->idStudent;
            $stdtransaction->idFinancialYear = $orderInfo->idFinancialYear;
            $stdtransaction->paymentDate = today_date();
            $stdtransaction->totalPaid = $orderInfo->order_amount;
            $stdtransaction->paymentMode = 'Online';
            $stdtransaction->receiptNo = 'RCPONL' . $orderInfo->idOrder;
            $stdtransaction->idSchool = $orderInfo->idSchool;
            $stdtransaction->status = 'Success';
            $stdtransaction->penaltyAmount = 0.00;
            $stdtransaction->fine = $orderInfo->fine_amount;
            $stdtransaction->discount = 0.00;
            $stdtransaction->save();
            
            $totalFine = 0;
            $totalDiscount = 0;
            //for loop for headers
            $totalDiscount=0;
            if($orderInfo->isMultipleFeehead == "Y")
            $selectedHeaders = json_decode($orderInfo->feeheads, true);
            else 
            $selectedHeaders = array(
                $orderInfo->idFeehead
            );
            foreach($selectedHeaders as $headers){
                if(isset($headers)){
                    $subheaders = \App\FeeHead::where('idFeehead','=',$headers)->get()->toArray();
                    foreach($subheaders as $headerIds)
                        {
                            $stepFine = 0;
                            $stdtransaction_detail = new \App\StudentTransactionDetail();
                            $stdtransaction_detail->idStudent = $orderInfo->idStudent;
                            $stdtransaction_detail->idTransaction = $stdtransaction->idTransaction;
                            $stdtransaction_detail->idFeehead = $headerIds['idFeehead'];
                            $stdtransaction_detail->paymentDate = today_date();
                            $stdtransaction_detail->amountPaid = $headerIds['amount'];
                            $date = Carbon::parse($headerIds['toDate']);
                            $now = Carbon::now();
                            $diff = $date->diffInDays($now, false);
                            if ($diff > 0) {
                                if ($headerIds['fine'] != null && $headerIds['fine'] != 0.00) {
                                    $stepFine = ( $headerIds['fine'] * $diff);
                                } else
                                if ($headerIds['flatFine'] != null) {
                                    $stepFine = $stepFine + $headerIds['flatFine'];
                                }
                            }
                            $stdtransaction_detail->fine = 0;
                            $stdtransaction_detail->discount = 0.00;
                            $stdtransaction_detail->save();
                       }
                }
            }
            if($totalDiscount >0){
                $stdtransaction->discount = $totalDiscount;
                $stdtransaction->update(); 
            }
            return response()->json(['message' => 'Payment Done']);
        }else{
            return response()->json(['message' => 'Failed to verify your payment.']);
        }
    }


    public function updateRoyalRaorpay(Request $request){
        if($request->isPaid == 0){
            DB::table('order_receipts')->where('order_id', $request->idOrder)->update(['notes' => $request->reason, 'order_note' => "Failed"]);
            return response()->json(['message' => 'Failed to verify your payment.']);
        }
        $key_secret = "1GDg04NimKEWNFMqW8OJeGAa";
        $str_key = $request->razorpay_order_id."|".$request->razorpay_payment_id;
        $generated_signature = hash_hmac('sha256',$str_key, $key_secret);
        if ($generated_signature == $request->razorpay_signature) {
            $orderInfo = DB::table('order_receipts')->where('order_id', $request->razorpay_order_id)->first();
            $stdtransaction = new \App\StudentTransaction();
            $stdtransaction->idStudent = $orderInfo->idStudent;
            $stdtransaction->idFinancialYear = $orderInfo->idFinancialYear;
            $stdtransaction->paymentDate = today_date();
            $stdtransaction->totalPaid = $orderInfo->order_amount;
            $stdtransaction->paymentMode = 'Online';
            $stdtransaction->receiptNo = 'RCPONL' . $orderInfo->idOrder;
            $stdtransaction->idSchool = $orderInfo->idSchool;
            $stdtransaction->status = 'Success';
            $stdtransaction->penaltyAmount = 0.00;
            $stdtransaction->fine = $orderInfo->fine_amount;
            $stdtransaction->discount = 0.00;
            $stdtransaction->save();
            
            $totalFine = 0;
            $totalDiscount = 0;
            //for loop for headers
            $totalDiscount=0;
            if($orderInfo->isMultipleFeehead == "Y")
            $selectedHeaders = json_decode($orderInfo->feeheads, true);
            else 
            $selectedHeaders = array(
                $orderInfo->idFeehead
            );
            foreach($selectedHeaders as $headers){
                if(isset($headers)){
                    $subheaders = \App\FeeHead::where('idFeehead','=',$headers)->get()->toArray();
                    foreach($subheaders as $headerIds)
                        {
                            $stepFine = 0;
                            $stdtransaction_detail = new \App\StudentTransactionDetail();
                            $stdtransaction_detail->idStudent = $orderInfo->idStudent;
                            $stdtransaction_detail->idTransaction = $stdtransaction->idTransaction;
                            $stdtransaction_detail->idFeehead = $headerIds['idFeehead'];
                            $stdtransaction_detail->paymentDate = today_date();
                            $stdtransaction_detail->amountPaid = $headerIds['amount'];
                            $date = Carbon::parse($headerIds['toDate']);
                            $now = Carbon::now();
                            $diff = $date->diffInDays($now, false);
                            if ($diff > 0) {
                                if ($headerIds['fine'] != null && $headerIds['fine'] != 0.00) {
                                    $stepFine = ( $headerIds['fine'] * $diff);
                                } else
                                if ($headerIds['flatFine'] != null) {
                                    $stepFine = $stepFine + $headerIds['flatFine'];
                                }
                            }
                            $stdtransaction_detail->fine = 0;
                            $stdtransaction_detail->discount = 0.00;
                            $stdtransaction_detail->save();
                       }
                }
            }
            if($totalDiscount >0){
                $stdtransaction->discount = $totalDiscount;
                $stdtransaction->update(); 
            }
            return response()->json(['message' => 'Payment Done']);
        }else{
            return response()->json(['message' => 'Failed to verify your payment.']);
        }
    }




    public function easebuzzStatus(Request $request) {
        if($request->get("order_id") != null){
            $orderInfo = DB::table('order_receipts')->where('idOrder', $request->get('order_id'))->first();
            return response()->json(['message' => 'Payment Done']);
            DB::table('order_receipts')->where('idOrder', $request->get('order_id'))->update(['isSaved'=>'Y']);
            $response = Cashfree::verifyEasebuzzTransaction($orderInfo);
            if ($response->status == "success") {
                if($orderInfo->type != null){
                    $stdtransaction = new \App\ShopTransaction();
                    $stdtransaction->idStudent = $orderInfo->idStudent;
                    $stdtransaction->idFinancialYear = $orderInfo->idFinancialYear;
                    $stdtransaction->paymentDate = today_date();
                    $stdtransaction->totalPaid = $orderInfo->order_amount;
                    $stdtransaction->paymentMode = 'Online';
                    $stdtransaction->receiptNo = 'RCPONL' . $orderInfo->idOrder;
                    $stdtransaction->idSchool = $orderInfo->idSchool;
                    $stdtransaction->status = 'Success';
                    $stdtransaction->discount = 0.00;
                    $stdtransaction->save();
    
                    $selectedHeaders = json_decode($orderInfo->feeheads, true);
                    foreach($selectedHeaders as $headers){
                        if($headers['qty'] > 0){
                            $stdtransaction_detail = new \App\ShopTransactionDetail();
                            $stdtransaction_detail->idStudent = $orderInfo->idStudent;
                            $stdtransaction_detail->idTransaction = $stdtransaction->idTransaction;
                            $stdtransaction_detail->idProduct = $headers['idProduct'];
                            $stdtransaction_detail->qty = $headers['qty'];
                            $product =  \App\Product::where('idProduct',$headers['idProduct'])->first();
                            $price = $headers['qty'] * $product->salePrice;
                            $stdtransaction_detail->paymentDate = today_date();
                            $stdtransaction_detail->unitPrice = $product->salePrice;
                            $stdtransaction_detail->amountPaid = $price;
                            $stdtransaction_detail->discount = 0.00;
                            $stdtransaction_detail->save();
                        }
                    }
                    DB::table('order_cart')->where('idStudent','=',$orderInfo->idStudent)->delete();
    
                }else{
                    $stdtransaction = new \App\StudentTransaction();
                    $stdtransaction->idStudent = $orderInfo->idStudent;
                    $stdtransaction->idFinancialYear = $orderInfo->idFinancialYear;
                    $stdtransaction->paymentDate = today_date();
                    $stdtransaction->totalPaid = $orderInfo->order_amount;
                    $stdtransaction->paymentMode = 'Online';
                    $stdtransaction->receiptNo = 'RCPONL' . $orderInfo->idOrder;
                    $stdtransaction->idSchool = $orderInfo->idSchool;
                    $stdtransaction->status = 'Success';
                    $stdtransaction->penaltyAmount = 0.00;
                    $stdtransaction->fine = $orderInfo->fine_amount;
                    $stdtransaction->discount = 0.00;
                    $stdtransaction->save();
                    
                    $totalFine = 0;
                    $totalDiscount = 0;
                    //for loop for headers
                    $totalDiscount=0;
                    if($orderInfo->isMultipleFeehead == "Y")
                    $selectedHeaders = json_decode($orderInfo->feeheads, true);
                    else 
                    $selectedHeaders = array(
                        $orderInfo->idFeehead
                    );
                    foreach($selectedHeaders as $headers){
                        if(isset($headers)){
                            $subheaders = \App\FeeHead::where('idFeehead','=',$headers)->get()->toArray();
                            foreach($subheaders as $headerIds)
                                {
                                    $stepFine = 0;
                                    $stdtransaction_detail = new \App\StudentTransactionDetail();
                                    $stdtransaction_detail->idStudent = $orderInfo->idStudent;
                                    $stdtransaction_detail->idTransaction = $stdtransaction->idTransaction;
                                    $stdtransaction_detail->idFeehead = $headerIds['idFeehead'];
                                    $stdtransaction_detail->paymentDate = today_date();
                                    $stdtransaction_detail->amountPaid = $headerIds['amount'];
                                    $date = Carbon::parse($headerIds['toDate']);
                                    $now = Carbon::now();
                                    $diff = $date->diffInDays($now, false);
                                    if ($diff > 0) {
                                        if ($headerIds['fine'] != null && $headerIds['fine'] != 0.00) {
                                            $stepFine = ( $headerIds['fine'] * $diff);
                                        } else
                                        if ($headerIds['flatFine'] != null) {
                                            $stepFine = $stepFine + $headerIds['flatFine'];
                                        }
                                    }
                                    $stdtransaction_detail->fine = 0;
                                    $stdtransaction_detail->discount = 0.00;
                                    $stdtransaction_detail->save();
                               }
                        }
                    }
                    if($totalDiscount >0){
                        $stdtransaction->discount = $totalDiscount;
                        $stdtransaction->update(); 
                    }
                }
                return response()->json(['message' => 'Payment Done']);
            }
        }
        else{
            return response()->json(['message' => 'Failed to verify your payment.']);
        }
    }

    public function cashfreePaymentStatus(Request $request) {
        $response = $this->checkPaymentStatus($request->get('order_id'));
        if ($response['order_status'] == "PAID") {
            $orderInfo = DB::table('order_receipts')->where('order_id', $request->get('order_id'))->first();

            if($orderInfo->type != null){
                $stdtransaction = new \App\ShopTransaction();
                $stdtransaction->idStudent = $orderInfo->idStudent;
                $stdtransaction->idFinancialYear = $orderInfo->idFinancialYear;
                $stdtransaction->paymentDate = today_date();
                $stdtransaction->totalPaid = $orderInfo->order_amount;
                $stdtransaction->paymentMode = 'Online';
                $stdtransaction->receiptNo = 'RCPONL' . $orderInfo->idOrder;
                $stdtransaction->idSchool = $orderInfo->idSchool;
                $stdtransaction->status = 'Success';
                $stdtransaction->discount = 0.00;
                $stdtransaction->save();

                $selectedHeaders = json_decode($orderInfo->feeheads, true);
                foreach($selectedHeaders as $headers){
                    if($headers['qty'] > 0){
                        $stdtransaction_detail = new \App\ShopTransactionDetail();
                        $stdtransaction_detail->idStudent = $orderInfo->idStudent;
                        $stdtransaction_detail->idTransaction = $stdtransaction->idTransaction;
                        $stdtransaction_detail->idProduct = $headers['idProduct'];
                        $stdtransaction_detail->qty = $headers['qty'];
                        $product =  \App\Product::where('idProduct',$headers['idProduct'])->first();
                        $price = $headers['qty'] * $product->salePrice;
                        $stdtransaction_detail->paymentDate = today_date();
                        $stdtransaction_detail->unitPrice = $product->salePrice;
                        $stdtransaction_detail->amountPaid = $price;
                        $stdtransaction_detail->discount = 0.00;
                        $stdtransaction_detail->save();
                    }
                }
                DB::table('order_cart')->where('idStudent','=',$orderInfo->idStudent)->delete();

            }else{
                $stdtransaction = new \App\StudentTransaction();
                $stdtransaction->idStudent = $orderInfo->idStudent;
                $stdtransaction->idFinancialYear = $orderInfo->idFinancialYear;
                $stdtransaction->paymentDate = today_date();
                $stdtransaction->totalPaid = $orderInfo->order_amount;
                $stdtransaction->paymentMode = 'Online';
                $stdtransaction->receiptNo = 'RCPONL' . $orderInfo->idOrder;
                $stdtransaction->idSchool = $orderInfo->idSchool;
                $stdtransaction->status = 'Success';
                $stdtransaction->penaltyAmount = 0.00;
                $stdtransaction->fine = $orderInfo->fine_amount;
                $stdtransaction->discount = 0.00;
                $stdtransaction->save();
                
                $totalFine = 0;
                $totalDiscount = 0;
                //for loop for headers
                $totalDiscount=0;
                if($orderInfo->isMultipleFeehead == "Y")
                $selectedHeaders = json_decode($orderInfo->feeheads, true);
                else 
                $selectedHeaders = array(
                    $orderInfo->idFeehead
                );
                foreach($selectedHeaders as $headers){
                    if(isset($headers)){
                        $subheaders = \App\FeeHead::where('idFeehead','=',$headers)->get()->toArray();
                        foreach($subheaders as $headerIds)
                            {
                                $stepFine = 0;
                                $stdtransaction_detail = new \App\StudentTransactionDetail();
                                $stdtransaction_detail->idStudent = $orderInfo->idStudent;
                                $stdtransaction_detail->idTransaction = $stdtransaction->idTransaction;
                                $stdtransaction_detail->idFeehead = $headerIds['idFeehead'];
                                $stdtransaction_detail->paymentDate = today_date();
                                $stdtransaction_detail->amountPaid = $headerIds['amount'];
                                $date = Carbon::parse($headerIds['toDate']);
                                $now = Carbon::now();
                                $diff = $date->diffInDays($now, false);
                                if ($diff > 0) {
                                    if ($headerIds['fine'] != null && $headerIds['fine'] != 0.00) {
                                        $stepFine = ( $headerIds['fine'] * $diff);
                                    } else
                                    if ($headerIds['flatFine'] != null) {
                                        $stepFine = $stepFine + $headerIds['flatFine'];
                                    }
                                }
                                $stdtransaction_detail->fine = 0;
                                $stdtransaction_detail->discount = 0.00;
                                $stdtransaction_detail->save();
                           }
                    }
                }
                if($totalDiscount >0){
                    $stdtransaction->discount = $totalDiscount;
                    $stdtransaction->update(); 
                }
            }
            return response()->json(['message' => 'Payment Done']);
        }else{
            return response()->json(['message' => 'Failed to verify your payment.']);
        }
    }

    function checkPaymentStatus($orderId) {
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => "https://api.cashfree.com/pg/orders/" . $orderId,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_HTTPHEADER => [
                "Accept: application/json",
                "Content-Type: application/json",
                "x-api-version: 2022-01-01",
                "x-client-id: 1928412d1f5bed99a3fb8e3528148291",
                "x-client-secret: 5de10b32c7b12616eaf0576da075c2d173c28ed9"
            ],
        ]);
        $response = curl_exec($curl);
        $info = curl_getinfo($curl, CURLINFO_HEADER_OUT);
        $err = curl_error($curl);
        curl_close($curl);
        if ($err) {
            return "";
        } else {
            $result = json_decode($response, true);
            return $result;
        }
    }


    public function printExtraReceipt($id){
        $transaction = \App\StudentExtraTransaction::where('idTransaction', '=', $id)->first();
        $student = \App\AdmEntry::where('idStudent', '=', $transaction->idStudent)->first();
        $school = \App\School::where('idSchool', '=',  $student->idSchool)->first();
        $pdf = PDF::loadView('schools.transaction.print_receipt_extra', ['margin_top' => 20], compact('transaction', 'school', 'student', 'feetotal'));
        return $pdf->stream('feereceipt.pdf');
    }

    public function getFeewiseExtraData($id,$idStudent) {
        $feeheader_ids = array_map('intval', explode(',', $id));
        //return $feeheader_ids;
        $student = \App\AdmEntry::where('idStudent', '=', $idStudent)->first();
        $selectedHeaders = \App\ExtraFeehead::whereIn('idExtraFeehead', $feeheader_ids)->get();
        $totalAmount = 0;
        for ($i = 0; $i < sizeof($selectedHeaders); $i++) {
            $headerObject = $selectedHeaders[$i];
            $totalAmount = $totalAmount + $headerObject['amount'] ;
        }
        return $totalAmount;
    }

    /*


    @else
@section('script')
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>

<script>
function toogleDetails(){
    $("#show_details").toggle();
}    

document.getElementById('submit-btn').onclick = function (e) {
        var testamt =  $('input[name="payableAmount"]').val();
        var zeropad = '00';
        var amttobepaid  = testamt +  zeropad;
        var adata = $('#feesubmission').serializeArray();
        $("#submit-btn").prop('disabled', true);
        var adata = $('#feesubmission').serializeArray();
        adata.push({name: 'amount', value: amttobepaid});

        $.ajax({
            method: 'post',
            url: "{!!url('student/generate-order-cashfree')!!}",
            data: adata,
            success:function(data){
              //  console.log(data);
              var options = {
                    key: "rzp_live_4gUv0qKqI3I7an",
                    amount: amttobepaid,
                    name: 'SchoolMis.Com',
                    image: 'https://online-login.online/storage/schools/135/logo_135.jpeg',
                    order_id: data.id,
                    handler : function (response){
                          console.log(response);
                          $.ajaxSetup({
                            headers: {
                                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                            }
                            });
                          $.ajax({
                            url: "{{url('/student/razorpay/update') }}",
                            type: "POST",
                            data: {isPaid : 1, razorpay_payment_id:response.razorpay_payment_id,razorpay_order_id:response.razorpay_order_id,razorpay_signature:response.razorpay_signature},
                            success: function (data) {
                                $("#submit-btn").prop('disabled', false);
                                window.location.href = "{{url('student/payfees')}}";
                            }
                        });
                    },
                    prefill: {
                        "name": "{{Auth::guard('student')->user()->firstName}}",
                        "email": "info.mhw@gmail.com",
                        "contact" :"{{Auth::guard('student')->user()->mobile}}"
                    },
                }
                window.rzp1 = new Razorpay(options);
                rzp1.open();
                rzp1.on('payment.failed', function (response){
                     console.log(response);
                     $.ajaxSetup({
                            headers: {
                                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                            }
                            });
                     $.ajax({
                            url: "{{url('/student/razorpay/update') }}",
                            type: "POST",
                            data: {isPaid : 0,idOrder:data.id,status:'failed',reason: response.error.description},
                            dataType: "json",
                            success: function (data) {
                                if(response.error.description)
                                alert(response.error.description);
                                else 
                                window.location.href = "{{url('student/payfees')}}";
                            }
                        });
                    $("#submit-btn").prop('disabled', false);
                });
                rzp1.open();
            },
             error: function(data){
                    
                }
        }); 
    }
    // Saving form data
var isValid=0;     

$(document).ready(function(){
 $('.otherpaymode').hide(); 
 $('#paymode').change(function() {
        var val = $(this).val();
        if((val == 'Cheque')){
           $('.otherpaymode').show();
        }else if(val == 'DD'){
           $('.otherpaymode').show();
        }else{
           $('.otherpaymode').hide();
        }
    });
});

var feeheaderIds = [];
$('.feeclass').change(function() {
    feeheaderIds = [];
    $("input:checkbox[name='selectedHeaders[]']:checked").each(function () {
            feeheaderIds.push($(this).val());
    });
    if(feeheaderIds.length>0)
    $.ajax({
            url: "{{url('/student/feeheaders') }}"+'/' +feeheaderIds + "/students/"+{{$student->idStudent}},
            type: "GET",
            dataType: "json",
                success:function(data) {
                     $('input[name="payableAmount"]').val(data);
                }
            });
    else    $('input[name="payableAmount"]').val(" ");      
});

function calculatePenalty(){
        var penaltyAmt = parseFloat($('#penalty').val());
        console.log(penaltyAmt);
        $('#penaltyAmt').text(penaltyAmt.toFixed(2));
    }
    
var sum = 0;
var discount = 0;
var fine = 0;
// iterate through each td based on class and add the values
$(".amt").each(function() {

    var value = $(this).text();
    // add only if the value is number
    if(!isNaN(value) && value.length != 0) {
        sum += parseFloat(value);
    }
    $('#total_fee').text(sum.toFixed(2));
    
});

$(".discount").each(function() {

    var value = Number($(this).text());
    // add only if the value is number
    if(!isNaN(value) && value.length != 0) {
        discount += parseFloat(value);
    }
   $('#total_discount').text(discount.toFixed(2));
});
$(".fine").each(function() {

    var value = Number($(this).text());
    // add only if the value is number
    if(!isNaN(value) && value.length != 0) {
        fine += parseFloat(value);
    }
    $('#total_fine').text(fine.toFixed(2));
});
 var ftotal = parseFloat($('#total_fee').text()); 
 var tdiscount = parseFloat($('#total_discount').text());
 var tfine = parseFloat($('#total_fine').text());
 var paidtot = parseFloat($('#total_paid').text());
 var fbalance = parseFloat(ftotal+paidtot);
 $('#total_balance').text(fbalance.toFixed(2));
 var feetotal = parseFloat(ftotal);
 $('#feetotal').val(feetotal.toFixed(2));
 
 var distotal = parseFloat($('#total_discount').text()); 
 $('#discounttotal').val(distotal.toFixed(2));

 var tf = parseFloat($('#total_fine').text()); 
 $('#finetotal').val(tf.toFixed(2));
 
 var baltotal = parseFloat(ftotal+tfine-tdiscount);
 $('#balance_total').text(baltotal.toFixed(2));
</script>
@stop
@endif*/

}

Copyright © 2021 - 2025 IMMREX7