IMMREX7

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

<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Database\QueryException;
use PDF;
use Session;
use \App\Http\SendNotificationApi;
use Illuminate\Support\Facades\Crypt;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;
use App\Http\Cashfree;
use GuzzleHttp\Exception\RequestException;
use App\Http\PaymentCalculation;
use Illuminate\Support\Str;

class TransactionController extends Controller {

    private function fetchLessTransaction($data,$idSchool,$idFinancialYear){
        $transaction = DB::table('lesser_transaction')
        ->where('idSchool', $idSchool)
        ->where('idFinancialYear',$idFinancialYear);
        if($data == "bounced")
        $transaction = $transaction->where('status','Bounced');
        else if($data == "tcheque")
        $transaction = $transaction->where(function($query) {
            $query->whereNull('status');
            $query->orWhere('status', '=', 'Cleared');
            $query->orWhere('status', '=', 'In-Process');
            $query->orWhere('status', '=', 'Success');
            $query->orWhere('status', '=', 'Bounced');
        });
        else
        $transaction = $transaction->where(function($query) {
            $query->whereNull('status');
            $query->orWhere('status', '=', 'Cleared');
            $query->orWhere('status', '=', 'In-Process');
            $query->orWhere('status', '=', 'Success');
        });
        if($data == "collection") return $transaction = $transaction->sum('totalPaid');
        if($data == "cash") return $transaction = $transaction->where('paymentMode','Cash')->sum('totalPaid');
        if($data == "cheque") return $transaction = $transaction->where('paymentMode','Cheque')->sum('totalPaid');
        if($data == "tcheque") return $transaction = $transaction->where('paymentMode','Cheque')->sum('totalPaid');
        if($data == "bounced") return $transaction = $transaction->where('paymentMode','Cheque')->sum('totalPaid');
        if($data == "online") return $transaction = $transaction->whereNotIn('paymentMode',['Cheque','Cash'])->sum('totalPaid');
    }
    private function fetchTransaction($data,$idSchool,$idFinancialYear){
        $transaction = DB::table('student_transaction')
        ->where('idSchool', $idSchool)
        ->where('idFinancialYear', $idFinancialYear);
        if($data == "bounced")
        $transaction = $transaction->where('status','Bounced');
        else if($data == "tcheque")
        $transaction = $transaction->where(function($query) {
            $query->whereNull('status');
            $query->orWhere('status', '=', 'Cleared');
            $query->orWhere('status', '=', 'In-Process');
            $query->orWhere('status', '=', 'Success');
            $query->orWhere('status', '=', 'Bounced');
        });
        else
        $transaction = $transaction->where(function($query) {
            $query->whereNull('status');
            $query->orWhere('status', '=', 'Cleared');
            $query->orWhere('status', '=', 'In-Process');
            $query->orWhere('status', '=', 'Success');
        });
        if($data == "collection") return $transaction = $transaction->sum('totalPaid');
        if($data == "cash") return $transaction = $transaction->where('paymentMode','Cash')->sum('totalPaid');
        if($data == "cheque") return $transaction = $transaction->where('paymentMode','Cheque')->sum('totalPaid');
        if($data == "tcheque") return $transaction = $transaction->where('paymentMode','Cheque')->sum('totalPaid');
        if($data == "bounced") return $transaction = $transaction->where('paymentMode','Cheque')->sum('totalPaid');
        if($data == "online") return $transaction = $transaction->whereNotIn('paymentMode',['Cheque','Cash'])->sum('totalPaid');
    }

    public function financialOpenDashboard($id) {
        $data = [];
        $school = DB::table('student_payment_session')->where('uhid', '=',$id)->first();
        $financialYear = DB::table('financial_years')->where('idSchool',$school->idSchool)->where('idFinancialYear',$school->idStudent)->first();
        $classes = DB::table('classes')->where('idSchool', $school->idSchool)->get();
        $data['total_collection'] = $this->fetchTransaction("collection",$school->idSchool,$school->idStudent) + $this->fetchLessTransaction("collection",$school->idSchool,$school->idStudent);
        $data['cash'] = $this->fetchTransaction("cash",$school->idSchool,$school->idStudent) + $this->fetchLessTransaction("cash",$school->idSchool,$school->idStudent);
        $data['cheque'] = $this->fetchTransaction("cheque",$school->idSchool,$school->idStudent) + $this->fetchLessTransaction("cheque",$school->idSchool,$school->idStudent);
        $data['online'] = $this->fetchTransaction("online",$school->idSchool,$school->idStudent) + $this->fetchLessTransaction("online",$school->idSchool,$school->idStudent);
        $data['tcheque'] = $this->fetchTransaction("tcheque",$school->idSchool,$school->idStudent) + $this->fetchLessTransaction("tcheque",$school->idSchool,$school->idStudent);
        $data['bounced'] = $this->fetchTransaction("bounced",$school->idSchool,$school->idStudent) + $this->fetchLessTransaction("bounced",$school->idSchool,$school->idStudent);
        $data['estimated_fees'] = 0;
        $data['overdue_fees'] = 0;
         
         $classesArr = DB::table('classes')->where('idSchool', $school->idSchool)->get()->pluck('idClass')->toArray();
         foreach($classesArr as $key =>$value){
             $data['class_'.$value] = 0;
             $data['overdue_class_'.$value] = 0;
         }
         $students = DB::table('students')->select('idClass','idSection','idStudent','idFinancialYear','studentType','idSchool')->whereIn('idClass',$classesArr)->where('idFinancialYear',$school->idStudent)->where('idSchool', $school->idSchool)->get();
         foreach($students as $student){
             if($student->idSchool == 25){
                 //fetch plan
                 $plan = 'Plan A';
                 $header = \App\StudentTransaction::select('feeheadLabel')->join('student_transaction_details','student_transaction.idTransaction','=','student_transaction_details.idTransaction')
                             ->join('feeheads','student_transaction_details.idFeehead','=','feeheads.idFeehead')
                             ->where('student_transaction.idStudent', '=', $student->idStudent)
                             ->where('student_transaction.idFinancialYear',$student->idFinancialYear)
                             ->whereIn('feeheadLabel',['Plan A','Plan B','Plan C'])
                             ->where(function($query) {
                                 $query->whereNull('student_transaction.status');
                                 $query->orWhere('student_transaction.status', '=', 'In-Process');
                                 $query->orWhere('student_transaction.status', '=', 'Cleared');
                                 $query->orWhere('student_transaction.status', '=', 'Success');
                             })->first();
                 if($header != null){
                     if (str_contains($header->feeheadLabel, 'Plan A')) {
                         $plan = 'Plan A';
                     }else if (str_contains($header->feeheadLabel, 'Plan B')) {
                         $plan = 'Plan B';
                     }else if (str_contains($header->feeheadLabel, 'Plan C')) {
                         $plan = 'Plan C';
                     }
                 }
                 $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();
                 $data['estimated_fees'] = $data['estimated_fees'] + $feeheads->sum('amount');   
                 $data['class_'.$student->idClass] = $data['class_'.$student->idClass] + $feeheads->sum('amount');   
             }else if($student->idSchool == 140 || $student->idSchool == 135 || $student->idSchool == 159 || $student->idSchool == 160 || $student->idSchool == 139){
                 $plan = 'Plan A';
                 $header = \App\StudentTransaction::select('feeheadLabel')->join('student_transaction_details','student_transaction.idTransaction','=','student_transaction_details.idTransaction')
                             ->join('feeheads','student_transaction_details.idFeehead','=','feeheads.idFeehead')
                             ->where('student_transaction.idStudent', '=', $student->idStudent)
                             ->where('student_transaction.idFinancialYear',$student->idFinancialYear)
                             ->where(function($query) {
                                 $query->whereNull('student_transaction.status');
                                 $query->orWhere('student_transaction.status', '=', 'In-Process');
                                 $query->orWhere('student_transaction.status', '=', 'Cleared');
                                 $query->orWhere('student_transaction.status', '=', 'Success');
                             })->first();
                 if($header != null){
                     if (str_contains($header->feeheadName, 'Plan A')) {
                         $plan = 'Plan A';
                     }else if (str_contains($header->feeheadName, 'Plan B')) {
                         $plan = 'Plan B';
                     }
                 }
                 $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');
                 $p_feeheads = DB::table('feeheads')->where('idClass', '=', $student->idClass)
                         ->where('idSection', '=', $student->idSection)
                         ->where('studentCategory', '=', 'All')
                         ->where('idFinancialYear','=', $student->idFinancialYear)
                         ->where('feeheadName', 'LIKE', 'P%')
                         ->whereNull('idStudent');   
                 $admission_feeheads = DB::table('feeheads')->where('idClass', '=', $student->idClass)
                         ->where('idSection', '=', $student->idSection)
                         ->where('studentCategory', '=', $student->studentType)
                         ->where('idFinancialYear','=', $student->idFinancialYear)
                         ->where('feeheadName', 'LIKE', 'Admission%')
                         ->whereNull('idStudent');       
                 $feeheads = DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                         ->where('idFinancialYear','=', $student->idFinancialYear)
                         ->where('feeheadName', 'LIKE', $plan.'%')
                         ->union($class_feeheads)
                         ->union($p_feeheads)
                         ->union($admission_feeheads)
                         ->union($allcat_feeheads)
                         ->orderBy('idFeehead','ASC')
                         ->orderBy('toDate')
                         ->get();       
                 $data['estimated_fees'] = $data['estimated_fees'] + $feeheads->sum('amount');
                 $amount = getOverdue($student,$plan); 
                 $data['overdue_fees'] = $data['overdue_fees'] + $amount;   
                 $data['overdue_class_'.$student->idClass] = $data['overdue_class_'.$student->idClass] + $amount;
                 $data['class_'.$student->idClass] = $data['class_'.$student->idClass] + $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');
                 $allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                         ->where('idSection', '=', $student->idSection)
                         ->where('studentCategory', '=', 'All')
                         ->where('idFinancialYear','=',$student->idFinancialYear)
                         ->whereNull('idStudent');
                 $feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                         ->where('idFinancialYear','=', $student->idFinancialYear)
                         ->union($class_feeheads)
                         ->union($allcat_feeheads)
                         ->orderBy('toDate')
                         ->get();
                 $data['estimated_fees'] = $data['estimated_fees'] + $feeheads->sum('amount');   
                 $data['class_'.$student->idClass] = $data['class_'.$student->idClass] + $feeheads->sum('amount');
             }
         }
        $idSchool =   $school->idSchool;
        $idFinancialYear = $school->idStudent;
        return view('schools.financial-dashboard-open',compact('data','financialYear','classes','idSchool','idFinancialYear'));
     }

    public function getPayNotification($id,Request $request){
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){

            if($student->idSchool == 25){
                return $this->royalNotification($student,$request);
            }else if($student->idSchool == 140 || $student->idSchool == 135){
                $plan = '';
                $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();
    
                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;
                    }
                }
                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('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()->toArray();
                $transaction = new \Illuminate\Database\Eloquent\Collection; //Create empty collection which we know has the merge() method
                
                $paidfees = \App\StudentTransaction::where('idStudent', '=', $id)->get();
                $lessfees = \App\LesserTransaction::where('idStudent', '=', $id)->get();
                
                $transaction = $transaction->merge($lessfees);
                $transaction = $transaction->merge($paidfees);
                
                $discountfees = DB::table('student_discounts')->where('idStudent', '=', $id)->where('isActive', 'Y')->get();
                $feeheaders=array();
                foreach($feeheads as $feehead)
                {
                     $headerObject = (array)$feehead;
                     $discount = 0;
                     foreach($discountfees as $items){
                        if($items->idFeehead == $headerObject['idFeehead']){
                            $headerObject['amount'] = $headerObject['amount'] - $items->amount;
                        }
                     }
                     $already_paid_feehead = \App\StudentTransactionDetail::where('idStudent', '=', $id)
                                        ->where('idFeehead', '=', $headerObject['idFeehead'])->where(function($query) {
                                    $query->whereNull('status');
                                    $query->orWhere('status', '=', 'In-Process');
                                    $query->orWhere('status', '=', 'Cleared');
                                    $query->orWhere('status', '=', 'Success');
                                })->first();
    
                    if($already_paid_feehead){                    
                        if($already_paid_feehead->amountPaid == $headerObject['amount'])
                                $headerObject['isPaid']='Paid';
                        else{
                            return response()->json(['message' => "There are some outstanding fees available please pay now."], 200, ['app-status' => 'success']);
                            break; 
                        }
                    } else  
                    {
                        return response()->json(['message' => "There are some outstanding fees available please pay now."], 200, ['app-status' => 'success']);
                        break; 
                    }
                }
            }else{
                $class_feeheads = \App\FeeHead::where('idClass', '=', $student->idClass)
                ->where('idSection', '=', $student->idSection)
                ->where('studentCategory', '=', $student->studentType)
                ->where('idFinancialYear','=',$student->idFinancialYear)
                ->whereNull('idStudent')
                ->get();
                $allcat_feeheads = \App\FeeHead::where('idClass', '=', $student->idClass)
                        ->where('idSection', '=', $student->idSection)
                        ->where('idFinancialYear','=',$student->idFinancialYear)
                        ->where('studentCategory', '=', 'All')
                        ->whereNull('idStudent')
                        ->get();
                $std_feeheads = \App\FeeHead::where('idStudent', '=', $student->idStudent)->where('idFinancialYear','=',$student->idFinancialYear)->get();
            
                $feeheads = new \Illuminate\Database\Eloquent\Collection; //Create empty collection which we know has the merge() method
                $feeheads = $feeheads->merge($class_feeheads);
                $feeheads = $feeheads->merge($std_feeheads);
                $feeheads = $feeheads->merge($allcat_feeheads)->sortBy('toDate', 1);
                $feeheads=$feeheads->sort(function ($a, $b) {
                    return strtotime($a->toDate) - strtotime($b->toDate);
                });
                
                $transaction = new \Illuminate\Database\Eloquent\Collection; //Create empty collection which we know has the merge() method
                $paidfees = \App\StudentTransaction::where('idStudent', '=', $id)->get();
                $lessfees = \App\LesserTransaction::where('idStudent', '=', $id)->get();
                $transaction = $transaction->merge($lessfees);
                $transaction = $transaction->merge($paidfees);
                
                foreach($feeheads as $key => $value)
                {
                    $headerObject=json_decode($value,true);
                    $already_paid_feehead = \App\StudentTransactionDetail::where('idStudent', '=', $id)
                                        ->where('idFeehead', '=', $headerObject['idFeehead'])->where(function($query) {
                                    $query->whereNull('status');
                                    $query->orWhere('status', '=', 'In-Process');
                                    $query->orWhere('status', '=', 'Cleared');
                                    $query->orWhere('status', '=', 'Success');
                                })->first();
                    if(!$already_paid_feehead){
                        return response()->json(['message' => "There are some outstanding fees available please pay now."], 200, ['app-status' => 'success']);
                        break; 
                    }
                }
            }
        }
        return response()->json(['message' => "Fully Paid.",'balance' => 0], 200, ['app-status' => 'success']);
                    
    }

    private function royalNotification($student,$request){
        $balance = PaymentCalculation::getOutstandingAmount($student,$request);
        //0 => force close //1 => Not force close
        //app-update => app update status //app-fee => outstanding amount //app-switch => profile Switch
        return response()->json(
            [
                'app-update' => "0",
                'app-update-version' => "1.06",
                'balance' => $balance,
                'priority' => "app-update",
                'message' => "There are some outstanding fees available please pay now.",
                'switch_profile' => $student->profileSwitch
            ], 200, ['app-status' => 'success']);
    }
    
    public function sendNotifications(Request $request){
        $id = array($request->ids);
        return SendNotificationApi::sendSingleNotification($id,$request->msg);
    }

    function fys(){
            $now = \Carbon\Carbon::now();
            $finyear = \App\FinancialYear::where('idSchool', '=', Auth::guard('teacher-api')->user()->idSchool)->get();
            foreach ($finyear as $fy) {
                $start_date = \Carbon\Carbon::parse($fy->startDate);
                $end_date = \Carbon\Carbon::parse($fy->endDate);
                if ($now->between($start_date, $end_date) == true || $end_date->diffInDays($now) == 0) {
                    return $fy->idFinancialYear;
                }
            }
        }

    public function addAttendance($id,$vid){
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        if (DB::table('attendance_conference')
            ->where('idStudent',$id)->where('idConference',$vid)->where('attendanceDate',Carbon::now()->format('Y-m-d'))->doesntExist()) {
        DB::table('attendance_conference')->insertGetId(
                            [
                                'idSchool' => $student->idSchool,
                                'idFinancialYear' => $this->fys(),
                                'idClass' =>$student->idClass,
                                'idSection' =>$student->idSection,
                                'idConference' =>$vid,
                                'idStudent' =>$id,
                                'attendanceDate' => Carbon::now()->format('Y-m-d')
                            ]
                        );
        }
        return response()->json(['success' => "Your attendance has been marked successfully"], 200, ['app-status' => 'success']);
    }
    
    public function addBirthdayWishes(Request $request){
         $reg_ids=DB::table('students')
                    ->join('parents', 'students.father_mobile', '=', 'parents.mobile')
                    ->select('parents.idFirebase')
                    ->where('students.idStudent',  $request->id)
                    ->get()->pluck('idFirebase')->toArray();
                    
        $user=Auth::guard('teacher-api')->user();    
        if($user){
            DB::table('birthday_response')->insert([
                [
                    'sender' => $user->firstName." ".$user->lastName."( Teacher )", 
                    'message' => $request->msg, 
                    'idStudent' => $request->id,
                    'idFy'=> $this->fys()
                ]
            ]);
         if(SendNotificationApi::sendSingleNotification( $reg_ids,$user->firstName." ".$user->lastName." : ".$request->msg))
        return response()->json(['success' => "Success"], 200, ['app-status' => 'success']);
        else return response()->json(['success' => "Failed"], 200, ['app-status' => 'success']);   
        }else{
        $student = \App\AdmEntry::where('idStudent', '=', $request->senderId)->first();       
        DB::table('birthday_response')->insert([
            [
                'sender' => $student->firstName." ".$student->lastName, 
                'message' => $request->msg, 
                'idStudent' => $request->id,
                'idFy'=>$student->idFinancialYear
            ]
        ]);  
        if(SendNotificationApi::sendSingleNotification( $reg_ids,$student->firstName." ".$student->lastName." : ".$request->msg))
        return response()->json(['success' => "Success"], 200, ['app-status' => 'success']);
        else return response()->json(['success' => "Failed"], 200, ['app-status' => 'success']);
        }
    }


    function juspayReturn(Request $request){
        $data = $request->get('order_id');
        if($data  != null){
            $order = $request->get('order_id');
            if($order  != null)
            {
                $response = json_decode($this->checkJusPayStatus($request->get('order_id')),true);
                $orderInfo = DB::table('order_receipts')->where('order_id',$order)->update(['notes' => json_encode($request->all())]);
                if ($response['status'] == "CHARGED" && $response['status_id'] == "21") {
                    $orderInfo = DB::table('order_receipts')->where('order_id', $order)->where('status','NA')->first();
                    DB::table('order_receipts')->where('order_id',$order)->update(['status' => $response['status']]);
                    if($orderInfo == null){
                        return response()->json(['message' => 'Payment Webhook Informations']);
                    }
                    if($orderInfo->type == "extra"){
                        $stdtransaction = new \App\StudentExtraTransaction();
                        $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->remarks = "";
                        if(DB::table('student_transaction')->where('paymentDate', today_date())->where('idStudent', $orderInfo->idStudent)->where('paymentMode', 'Online')->where('idFinancialYear', $orderInfo->idFinancialYear)->where('totalPaid', $orderInfo->order_amount)->doesntExist())
                            $stdtransaction->save();
                        else{
                            return response()->json(['message' => 'Payment Done']);
                        }
                        
                        $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\ExtraFeehead::where('idExtraFeehead','=',$headers)->get()->toArray();
                                foreach($subheaders as $headerIds)
                                    {
                                        $stepFine = 0;
                                        $stdtransaction_detail = new \App\StudentExtraTransactionDetail();
                                        $stdtransaction_detail->idStudent = $orderInfo->idStudent;
                                        $stdtransaction_detail->idTransaction = $stdtransaction->idTransaction;
                                        $stdtransaction_detail->idFeehead = $headerIds['idExtraFeehead'];
                                        $stdtransaction_detail->paymentDate = today_date();
                                        $stdtransaction_detail->amountPaid = $headerIds['amount'];
                                        $stdtransaction_detail->fine = 0;
                                        $stdtransaction_detail->discount = 0.00;
                                        $stdtransaction_detail->save();
                                   }
                            }
                        }

                        return redirect('student/extra-fees');
                    }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->remarks = "verifyPaymentRazarpay";
                        if(DB::table('student_transaction')->where('paymentDate', today_date())->where('idStudent', $orderInfo->idStudent)->where('paymentMode', 'Online')->where('idFinancialYear', $orderInfo->idFinancialYear)->where('totalPaid', $orderInfo->order_amount)->doesntExist())
                            $stdtransaction->save();
                        else{
                            return response()->json(['message' => 'Payment Done']);
                        }
                        
                        $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'] == "0.00"){
                                                if($now->format('M') != $date->format('M')){
                                                    $now->addMonth();
                                                    $months = $now->diffInMonths($date);
                                                    $stepFine = ($headerIds['flatFine'] * $months);
                                                }else{
                                                    $stepFine = $headerIds['flatFine'];
                                                }
                                            }else{
                                                $stepFine = $headerIds['fine'];
                                            }
                                        }
                                        $stdtransaction_detail->fine = $stepFine;
                                        $discountfees = DB::table('student_discounts')->where('idStudent', '=', $orderInfo->idStudent)->where('idFeehead', '=', $headerIds['idFeehead'])->where('isActive', 'Y')->first();
                                        if($discountfees != null){
                                            $stdtransaction_detail->discount = $discountfees->amount;
                                            $totalDiscount = $totalDiscount + $discountfees->amount;
                                        }else
                                        $stdtransaction_detail->discount = 0.00;
                                        $stdtransaction_detail->save();
                                   }
                            }
                        }
                        if($totalDiscount >0){
                            $stdtransaction->discount = $totalDiscount;
                            $stdtransaction->update(); 
                        }
                    }
                }
            }
        }

        if(Session::get('idStudent') != null)
        return redirect('student/payfees');
        else return response()->json(['message' => 'Payment Done']);
    }

    function checkJusPayStatus($orderId){
        $client = new Client();
        $response = $client->request('GET', 'https://api.juspay.in/orders/'.$orderId, ['headers' => ['Authorization' => 'Basic '.base64_encode("069A05342E3495E8B686A0AFAF425F:"), 'x-merchantid' => 'ROIN', 'version' => date('Y-m-d')]]);
        $data = $response->getBody();
        return $data;
    }

    function checkPaymentStatus($orderId){
        $curl = curl_init();
        $data = array(
            'appId' => '1928412d1f5bed99a3fb8e3528148291',
            'secretKey' => '5de10b32c7b12616eaf0576da075c2d173c28ed9',
            'orderId' => $orderId,
        );
        curl_setopt_array($curl, [
            CURLOPT_URL => "https://api.cashfree.com/api/v1/order/info/status",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $data
        ]);

        $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;
        }
    }

    function cornPayments(){
        $orderDetails = DB::table('order_receipts')->where('idSchool', 140)->where('status', "NA")->orderBy('idOrder','DESC')->paginate(1);
        //return response()->json(['message' => $orderDetails->items()]);
        foreach($orderDetails->items() as $order){
            $response = $this->checkPaymentStatus($order->order_id);
            if(isset($response["orderStatus"])){
                //return response()->json(['message' => $response]);
                DB::table('order_receipts')->where('order_id', $order->order_id)->update(['status' => $response['orderStatus'], 'order_note' => json_encode($response)]);
                if($response['orderStatus'] == "ACTIVE"){

                }else
                if ($response['txStatus'] == "SUCCESS" && $response['orderStatus'] == "PAID") {
                    $orderInfo = DB::table('order_receipts')->where('order_id', $order->order_id)->first();
                    if($orderInfo == null){
                        return response()->json(['message' => 'Payment Webhook Informations']);
                    }
                    $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->remarks = "cornPayments";
                    if(DB::table('student_transaction')->where('paymentDate', today_date())->where('idStudent', $orderInfo->idStudent)->where('paymentMode', 'Online')->where('idFinancialYear', $orderInfo->idFinancialYear)->where('totalPaid', $orderInfo->order_amount)->doesntExist())
                    $stdtransaction->save();
                    else{
                        return response()->json(['message' => 'Payment Webhook Exists']);
                    }
                    
                    $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);
                                        } 
                                        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(); 
                    }
                    DB::table('order_receipts')->where('order_id', $order->order_id)->update(['isSaved' => "Y"]);
                }
            }else DB::table('order_receipts')->where('order_id', $order->order_id)->update(['status' => "PA"]);
            
        }
        return "";
    }

    function cashfreeWebhook(Request $request){
        $orderInfo = DB::table('order_receipts')->where('idOrder','3411')->update(['notes' => json_encode($request->all())]);
        $data = $request->data;
        if($data  != null){
            $order = $data["order"];
            if($order  != null)
            {
                $response = $this->checkPaymentStatus($order["order_id"]);
                $orderInfo = DB::table('order_receipts')->where('order_id',$order["order_id"])->update(['notes' => json_encode($request->all())]);
                if ($response['txStatus'] == "SUCCESS" && $response['orderStatus'] == "PAID") {
                    $orderInfo = DB::table('order_receipts')->where('order_id', $order["order_id"])->where('status','NA')->first();
                    DB::table('order_receipts')->where('order_id',$order["order_id"])->update(['status' => $response['orderStatus']]);
                    if($orderInfo == null){
                        return response()->json(['message' => 'Payment Webhook Informations']);
                    }

                    if($orderInfo->type != null){
                        if($orderInfo->type == "Bus"){
                            $stdtransaction = new \App\BusTransaction();
                            $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->remarks = "cashfreeWebhook";
                            if(DB::table('bus_transaction')->where('paymentDate', today_date())->where('idStudent', $orderInfo->idStudent)->where('paymentMode', 'Online')->where('idFinancialYear', $orderInfo->idFinancialYear)->where('totalPaid', $orderInfo->order_amount)->doesntExist())
                                $stdtransaction->save();
                            else{
                                return response()->json(['message' => 'Payment Webhook Exists']);
                            }
                            
                            $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\BusFeehead::where('idBusFeehead','=',$headers)->get()->toArray();
                                        foreach($subheaders as $headerIds)
                                            {
                                                $stepFine = 0;
                                                $stdtransaction_detail = new \App\BusTransactionDetail();
                                                $stdtransaction_detail->idStudent = $orderInfo->idStudent;
                                                $stdtransaction_detail->idBusTransaction = $stdtransaction->idBusTransaction;
                                                $stdtransaction_detail->idBusFeehead = $headerIds['idBusFeehead'];
                                                $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);
                                                    }
                                                    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{
                            $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->remarks = "cashfreeWebhook";
                            $stdtransaction->fine = $orderInfo->fine_amount;
                            $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();
                                }
                            }
                        }
                    }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->remarks = "cashfreeWebhook";
                        if(DB::table('student_transaction')->where('paymentDate', today_date())->where('idStudent', $orderInfo->idStudent)->where('paymentMode', 'Online')->where('idFinancialYear', $orderInfo->idFinancialYear)->where('totalPaid', $orderInfo->order_amount)->doesntExist())
                            $stdtransaction->save();
                        else{
                            return response()->json(['message' => 'Payment Webhook Exists']);
                        }
                        
                        $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);
                                            }
                                            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.']);
                }
            }
        }
        return response()->json(['message' => 'Payment Webhook Information']);
    }

    function cashfreeReturn(Request $request){
        $orderInfo = DB::table('order_receipts')->where('idOrder','3411')->update(['notes' => json_encode($request->all())]);
        //return $this->cashfreeWebhook($request);
        return response()->json(['message' => 'Payment Webhook Information']);
    }

    function verifyCashfree(Request $request){
        $response = $this->checkPaymentStatus($request->idOrder);
        if ($response['txStatus'] == "SUCCESS" && $response['orderStatus'] == "PAID") {
            $orderInfo = DB::table('order_receipts')->where('order_id', $request->idOrder)->first();
            DB::table('order_receipts')->where('idOrder',$orderInfo->idOrder)->update(['notes' => json_encode($request->all())]);
            
            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->fine = $orderInfo->fine_amount;
                $stdtransaction->remarks = "cashfreeWebhook";

                $checkTransaction = \App\ShopTransaction::where('receiptNo','RCPONL' . $orderInfo->idOrder)->first();
                $status = DB::table('order_receipts')->where('idOrder',$orderInfo->idOrder)->where('status','PAID')->first();
                if($checkTransaction == null && $status == null){
                   // DB::table('order_receipts')->where('order_id',$order["order_id"])->update(['status' => $response['orderStatus']]);
                    //$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();
                        }
                    }
                }
            }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->remarks = "verifyCashfree";
                if(DB::table('student_transaction')->where('paymentDate', today_date())->where('idStudent', $orderInfo->idStudent)->where('paymentMode', 'Online')->where('idFinancialYear', $orderInfo->idFinancialYear)->where('totalPaid', $orderInfo->order_amount)->doesntExist()){
                    //$stdtransaction->save();
                }else{
                    return response()->json(['message' => 'Payment Done']);
                }
                
                $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);
                                    }
                                    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 getOrderToken($order,$amount,$idSudent,$phone) {
        $curl = curl_init();
        $data = array(
            'order_amount' => $amount,
            'order_currency' => 'INR',
            'orderId' => "Order000".$order,
            "order_meta" =>[
                "payment_methods" => "",
                "notify_url" => "https://online-login.online/cashfree/webhook",
                "return_url" => "https://online-login.online/cashfree/pg?cf_id={order_id}&cf_token={order_token}"
            ],
            "customer_details" => [
                "customer_id"=> strval($idSudent),
                "customer_email"=> "info@sppedtrackgps.in",
                "customer_phone"=> $phone
            ]
        );
        $postData = json_encode($data);
        curl_setopt_array($curl, [
            CURLOPT_URL => "https://api.cashfree.com/pg/orders",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $postData,
            CURLOPT_HTTPHEADER => [
                "Content-Type: application/json",
                "x-client-id: 1928412d1f5bed99a3fb8e3528148291",
                "x-client-secret: 5de10b32c7b12616eaf0576da075c2d173c28ed9",
                "x-api-version: 2022-01-01",
                "x-request-id: SPDTG"
            ],
        ]);

        $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;
        }
    }

    function getRazarpayToken($order,$amount) {
        $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' => (int)str_replace('.', '', $amount),'currency' => "INR" , 'receipt' => "Order000".$order,'payment_capture' => "1"] ]);
        $data =json_decode($response->getBody());
        $data->page_key = "rzp_live_4gUv0qKqI3I7an";
        $data->orderAmount = (int)str_replace('.', '', $amount);
        return $data;
    }

    function createJustPayCustomer($amount,$order) {
        /*try{
            $idObject = DB::table('order_receipts')->where('object_id',$objectId)->first();
            if($idObject == null){
                $client = new Client;
                $response = $client->request('POST', 'https://api.juspay.in/customers', [ 'headers' => ['Content-Type' => 'application/x-www-form-urlencoded','x-merchantid' => 'ROIN'],'auth' => ['069A05342E3495E8B686A0AFAF425F', ''],'form_params' =>  ['object_reference_id' => $objectId ,'mobile_number' => $mobile] ]);
                if($response->getStatusCode() == 200){
                    $data =json_decode($response->getBody());
                    DB::table('order_receipts')->where('idOrder',$idOrder)->update(
                        ["object_id" => $objectId]
                    );
                    return $data;
                }
            }else{
                $client2 = new Client;
                $response2 = $client2->request('GET', 'https://api.juspay.in/customers/'.$objectId.'?options.get_client_auth_token=true', [ 'headers' => [],'auth' => ['069A05342E3495E8B686A0AFAF425F', ''] ]);
                if($response2->getStatusCode() == 200){
                    $data =json_decode($response2->getBody());
                    DB::table('order_receipts')->where('idOrder',$idOrder)->update(
                        ["object_id" => $objectId]
                    );
                    return $data;
                }
            }
        }catch(RequestException $e){
            $client2 = new Client;
            $response2 = $client2->request('GET', 'https://api.juspay.in/customers/'.$objectId.'?options.get_client_auth_token=true', [ 'headers' => [],'auth' => ['069A05342E3495E8B686A0AFAF425F', ''] ]);
            if($response2->getStatusCode() == 200){
                $data =json_decode($response2->getBody());
                return $data;
            }
            return response()->json(['message'=>'Mobile Number or Password is incorrect',"code" => "404"]);
        }*/
        $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' => (int)str_replace('.', '', $amount),'currency' => "INR" , 'receipt' => "Order000".$order,'payment_capture' => "1"] ]);
        $data =json_decode($response->getBody());
        $data->page_key = "rzp_live_3pII9YBnGYch65";
        $data->orderAmount = (int)str_replace('.', '', $amount);
        return $data;
    }

    

    function getRazarpayStatus($idOrder) {
        $orderInfo = DB::table('order_receipts')->where('idSchool', 135)->where('isSaved','N')->orderBy('idOrder','DESC')->first();
        $client = new Client;
        $response = $client->request('GET', 'https://api.razorpay.com/v1/orders/'.$orderInfo->order_id.'/payments', [ 'headers' => ['Accept' => 'application/json'],'auth' => ['rzp_live_4gUv0qKqI3I7an', 'V0XtNlgExrR9eM8xlek987MO']]);
        $data = json_decode($response->getBody());
        if($data->count == 0){
            DB::table('order_receipts')->where('order_id', $orderInfo->order_id)->update(['notes' => "Unable to capture data", 'order_note' => "Failed",'isSaved' => 'Y']);
        }
        $items = $data->items;
        $data->idOrder = $orderInfo->order_id;
        $data->razorpay_payment_id = $items[0]->id;
        $data->razorpay_order_id = $items[0]->order_id;
        $data->paymentDate = date('Y-m-d', $items[0]->created_at);
        $data->isPaid = 1;

        DB::table('order_receipts')->where('order_id', $orderInfo->order_id)->update(['notes' => "Success", 'order_note' => json_encode($items), 'isSaved' => 'Y']);
        if ($items[0]->status == "captured") {
            $orderInfo = DB::table('order_receipts')->where('order_id', $data->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->remarks = "verifyPaymentRazarpay";
            if(DB::table('student_transaction')->where('paymentDate', today_date())->where('idStudent', $orderInfo->idStudent)->where('paymentMode', 'Online')->where('idFinancialYear', $orderInfo->idFinancialYear)->where('totalPaid', $orderInfo->order_amount)->doesntExist())
                $stdtransaction->save();
            else{
                return response()->json(['message' => 'Payment Done']);
            }
            
            $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);
                                } 
                                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 verifyPaymentRazarpay(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->remarks = "verifyPaymentRazarpay";
            if(DB::table('student_transaction')->where('paymentDate', today_date())->where('idStudent', $orderInfo->idStudent)->where('paymentMode', 'Online')->where('idFinancialYear', $orderInfo->idFinancialYear)->where('totalPaid', $orderInfo->order_amount)->doesntExist())
                $stdtransaction->save();
            else{
                return response()->json(['message' => 'Payment Done']);
            }
            
            $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);
                                }
                                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.']);
        }
    }

    private function checkIfFyEnded($student){
        $fy = DB::table('financial_years')->where('idFinancialYear',$student->idFinancialYear)->first();
        if($fy != null){
            try {
                $endDate = $fy->endDate;
                $currentDate = date('Y-m-d');
                Log::info($endDate.'-'.$currentDate);
                $currentDateTime = Carbon::parse($currentDate);
                $financialYearEndDateTime = Carbon::parse($endDate);
        
                return $currentDateTime->greaterThan($financialYearEndDateTime);
            } catch (\Carbon\Exceptions\InvalidFormatException $e) {
                // Handle invalid date formats
                return null; // Or throw an exception
            }
        }
        return null;
    }

    public function generateOrder(Request $request){
        $student = \App\AdmEntry::where('idStudent', '=', $request->id)->first();
        $payAmount = 0;
        $penaltyAmount = 0;
        $totalHeaders = 0;
        $order = [];

        if(isset($request->type)){
            //return json_encode([]);
            $penaltyAmount = 0;
            $isBook = false;
            $isUniform = false;
            $feeheads = json_decode($request->items,true);
            if($request->type == "canteen"){
                foreach($feeheads as $idfee){
                    $product =  \App\Food::select('id as idProduct','item_name as productName','pic as productImage', 'price as salePrice', 'idSchool', 'short_description as description','max_buy')->where('id',$idfee['idProduct'])->first();
                    if($product != null){
                        $price = $idfee['qty'] * $product->salePrice;
                        $payAmount = $payAmount + $price;
                    }
                }
                $order['purpose'] = 'Food';
            }else{
                foreach($feeheads as $idfee){
                    $product =  \App\Product::where('idProduct',$idfee['idProduct'])->first();
                    if($product != null){
                        $price = $idfee['qty'] * $product->salePrice;
                        $payAmount = $payAmount + $price;
                        if ($product->idProductCategory == 87) {
                            $isBook = true;
                        }
                        if ($product->idProductCategory == 86) {
                            $isUniform = true;
                        }
                        if (str_contains($product->productName, 'Books') || str_contains($product->productName, 'BOOKS')) {
                            $order['purpose'] = 'Books';
                            $isAfter = $this->checkIfFyEnded($student);
                            if ($isAfter != null) {
                                if ($isAfter){
                                    $feedback = [];
                                    return json_encode($feedback);
                                }
                            }
                        }
                        if (str_contains($product->productName, 'Uniform')) {
                            $order['purpose'] = 'Uniform';
                            $isAfter = $this->checkIfFyEnded($student);
                            if ($isAfter != null) {
                                if ($isAfter){
                                    $feedback = [];
                                    return json_encode($feedback);
                                }
                            }
                        }
                    }
                }
                $checkTransaction = DB::table('order_receipts')->where('idStudent',$request->id)->whereNotNull('created_at')->orderBy('idOrder','DESC')->first();
                if($checkTransaction != null){
                    $transactionCarbon = Carbon::parse($checkTransaction->created_at);
                    // Get the current time in the same timezone
                    $currentTime = Carbon::now('Asia/Kolkata');
                    // Calculate the difference in minutes
                    $minutesDifference = $currentTime->diffInMinutes($transactionCarbon);
                    if ($minutesDifference < 2) {
                        $feedback = [];
                        //return json_encode($feedback);
                    }
                }
            }
            
            

            if($isBook){
                //$penaltyAmount = $penaltyAmount + 150;
            }
            if($isUniform){
                //$penaltyAmount = $penaltyAmount + 150;
            }

            $payAmount = $payAmount + $penaltyAmount;
            $order['idStudent']=$student->idStudent;
            $order['idSchool']=$student->idSchool;
            $order['idFinancialYear']=$student->idFinancialYear;
            $order['idClass']= $student->idClass;
            $order['isMultipleFeehead'] = "Y";
            $order['idFeehead']= 0;
            if($request->type == "canteen")
            $order['type']= "Food";
            else 
            $order['type']= "Shop";
            $order['feeheads']=$request->items;
            $order['dateOfTransaction']=Carbon::now()->format('Y-m-d');
            $order['order_amount'] = $payAmount;
            $order['fine_amount'] = $penaltyAmount;
        }else{

            if(isset($request->mode)){
                $feeheads = json_decode($request->feeheads);
                foreach($feeheads as $idfee){
                    $totalHeaders = $totalHeaders + 1;
                    $details =  \App\BusFeehead::where('idBusFeehead', '=', $idfee)->first();
                    $totalAmount = $details->amount;
                    $fineAmount = 0;
                    $lastDate = Carbon::parse($details->toDate); 
                    $diff = $lastDate->diffInDays(Carbon::now(),false);
                    if($diff > 0){
                        if($details->fine != null)
                        $fineAmount = $diff * $details->fine + $fineAmount;
                        
                        if($details->flatFine != null){
                            $fineAmount = $details->flatFine + $fineAmount;
                        }
                    }
                    $payAmount = $payAmount + $totalAmount + $fineAmount;
                    $penaltyAmount = $penaltyAmount +  $fineAmount;
                    $isDiscount=\App\BusFeeDiscount::where('idStudent', '=', $student->idStudent)->where('idBusFeehead', '=', $details->idBusFeehead)->where('isActive', '=', 'Y')->get();            
                    foreach($isDiscount as $discount){
                        $payAmount= $payAmount - $discount->amount;
                    }
                }
        
                //Genrate Order ID
                $order['idStudent']=$student->idStudent;
                $order['idSchool']=$student->idSchool;
                $order['idFinancialYear']=$student->idFinancialYear;
                $order['idClass']= $student->idClass;
                if($totalHeaders > 1)
                $order['isMultipleFeehead'] = "Y";
                else  $order['isMultipleFeehead'] = "N";
        
                $order['idFeehead']=$feeheads[0];
                $order['purpose']= "Bus";
                $order['type']= "Bus";
                $order['feeheads']=$request->feeheads;
                $order['dateOfTransaction']=Carbon::now()->format('Y-m-d');
                $order['order_amount'] = $payAmount;
                $order['fine_amount'] = $penaltyAmount;
            }else{
                $feeheads = json_decode($request->feeheads);
                foreach($feeheads as $idfee){
                    $totalHeaders = $totalHeaders + 1;
                    $details =  \App\FeeHead::where('idFeehead', '=', $idfee)->first();
                    $totalAmount = $details->amount;
                    $fineAmount = 0;
                    $lastDate = Carbon::parse($details->toDate.' 23:59:59'); 
                    $diff = $lastDate->diffInDays(Carbon::now(),false);
                    if($diff > 0){
                        if($details->fine != null)
                        $fineAmount = $diff * $details->fine + $fineAmount;
                        
                        if($details->flatFine != null){
                            $fineAmount = $details->flatFine + $fineAmount;
                        }
                    }
                    $payAmount = $payAmount + $totalAmount + $fineAmount;
                    $penaltyAmount = $penaltyAmount +  $fineAmount;
                }
        
                //Genrate Order ID
                $order['idStudent']=$student->idStudent;
                $order['idSchool']=$student->idSchool;
                $order['idFinancialYear']=$student->idFinancialYear;
                $order['idClass']= $student->idClass;
                if($totalHeaders > 1)
                $order['isMultipleFeehead'] = "Y";
                else  $order['isMultipleFeehead'] = "N";
        
                $order['idFeehead']=$feeheads[0];
                $order['feeheads']=$request->feeheads;
                $order['dateOfTransaction']=Carbon::now()->format('Y-m-d');
                $order['order_amount'] = $payAmount;
                $order['fine_amount'] = $penaltyAmount;
            }
        }
        
        $order['created_at'] = Carbon::now()->format('Y-m-d H:i:m');
        $order['corn_run'] = "N";
        $idOrder = DB::table('order_receipts')->insertGetId($order);
        $orderDetails = DB::table('order_receipts')->where('idOrder',$idOrder)->first();
        $response =  Cashfree::initiateEaseBuzzOrder($orderDetails, $student);
        $idOrder = DB::table('order_receipts')->where('idOrder',$idOrder)->update(
            ["order_id" => $response->data]
        );
        $keyService = DB::table('pg_keys')->where('purpose',$order['purpose'])->where('idSchool',$student->idSchool)->first();
        $feedback["id"] = $response->data;
        $feedback["appId"] =$order['purpose'];
        $feedback["result"] = "1";
        $feedback["message"] = "Generate Message";
        return json_encode($feedback);

        /*
        $idOrder = DB::table('order_receipts')->insertGetId($order);
        $mobile = $student->contactPersonMobile;
        if($mobile == null || $mobile == ""){
            $mobile = $student->father_mobile;
        }
        //Generate order Token
        $response =  $this->getOrderToken($idOrder,$payAmount,$student->idStudent,$mobile);
        //return json_encode($mobile);
        $idOrder = DB::table('order_receipts')->where('idOrder',$idOrder)->update(
            ["order_id" => $response["order_id"]]
        );
        return json_encode($response);*/
    }

    public function generateAmchaPayOrder(Request $request){
        $student = \App\AdmEntry::where('idStudent', '=', $request->id)->first();
        $feeheads = json_decode($request->feeheads);
        $payAmount = 0;
        $penaltyAmount = 0;
        $totalHeaders = 0;
        $order = [];

        if(isset($request->type)){
            return json_encode(["errorMessage" => "Visit School Counter to Pay"]);
            foreach($feeheads as $idfee){
                $totalHeaders = $totalHeaders + 1;
                $details =  \App\ExtraFeehead::where('idExtraFeehead', '=', $idfee)->first();
                $totalAmount = $details->amount;
                $fineAmount = 0;
                $payAmount = $payAmount + $totalAmount + $fineAmount;
                $penaltyAmount = $penaltyAmount +  $fineAmount;
            }
        }else{
                foreach($feeheads as $idfee){
                    $totalHeaders = $totalHeaders + 1;
                    $details =  \App\FeeHead::where('idFeehead', '=', $idfee)->first();
                    $totalAmount = $details->amount;
                    $fineAmount = 0;
                    $lastDate = Carbon::parse($details->toDate); 
                    $diff = $lastDate->diffInDays(Carbon::now(),false);
                    if($diff > 0){
                        if($details->fine != null)
                        $fineAmount = $diff * $details->fine + $fineAmount;
                        
                        if($details->flatFine != null){
                            $fineAmount = $details->flatFine + $fineAmount;
                        }
                    }
                    $payAmount = $payAmount + $totalAmount + $fineAmount;
                    $penaltyAmount = $penaltyAmount +  $fineAmount;
                }
            
        }
        
        
                //Genrate Order ID
                $order['idStudent']=$student->idStudent;
                $order['idSchool']=$student->idSchool;
                $order['idFinancialYear']=$student->idFinancialYear;
                $order['idClass']= $student->idClass;
                if($totalHeaders > 1)
                $order['isMultipleFeehead'] = "Y";
                else  $order['isMultipleFeehead'] = "N";
        
                $order['idFeehead']=$feeheads[0];
                $order['feeheads']=$request->feeheads;
                $order['dateOfTransaction']=Carbon::now()->format('Y-m-d');
                $order['order_amount'] = $payAmount;
                $order['fine_amount'] = $penaltyAmount;
                $order['purpose'] = "Fees";
                if(isset($request->type))
                $order['type'] = $request->type;
        $order['created_at'] = Carbon::now()->format('Y-m-d H:i:m');
        $order['corn_run'] = "N";
        $idOrder = DB::table('order_receipts')->insertGetId($order);
        $orderDetails = DB::table('order_receipts')->where('idOrder',$idOrder)->first();
        $response =  Cashfree::initiateEaseBuzzOrder($orderDetails, $student);
        $idOrder = DB::table('order_receipts')->where('idOrder',$idOrder)->update(
            ["order_id" => $response->data]
        );
        $keyService = DB::table('pg_keys')->where('purpose',$order['purpose'])->where('idSchool',$student->idSchool)->first();
        $feedback["id"] = $response->data;
        $feedback["appId"] =$order['purpose'];
        $feedback["result"] = "1";
        $feedback["message"] = "Generate Message";
        return json_encode($feedback);
    }

    public function generateJusPayOrder(Request $request){
        $student = \App\AdmEntry::where('idStudent', '=', $request->id)->first();
        $feeheads = json_decode($request->feeheads);
        $payAmount = 0;
        $penaltyAmount = 0;
        $totalHeaders = 0;
        if(isset($request->type)){
            
            if($request->gateway == null){
                return json_encode([]);
            }
            
            if($request->type == "Bus"){
                $id = "";
                foreach($feeheads as $idfee){
                    $totalHeaders = $totalHeaders + 1;
                    if($totalHeaders < count($feeheads))
                    $id=$id.$idfee.",";
                    else $id=$id.$idfee;
                }
                $payAmount = PaymentCalculation::calculateBusRoyal($id, $student->idStudent,$request);
                $feeheader_ids = array_map('intval', explode(',', $id));
                $selectedHeaders = \App\BusFeehead::whereIn('idBusFeehead', $feeheader_ids)->get()->toArray();
                foreach($selectedHeaders as $feeheaders) {
                    $headerObject = (array)$feeheaders;
                    $penaltyAmount = $penaltyAmount + PaymentCalculation::calculateBusFine($headerObject, $student);
                }
                
            }else{
                foreach($feeheads as $idfee){
                    $totalHeaders = $totalHeaders + 1;
                    $details =  \App\ExtraFeehead::where('idExtraFeehead', '=', $idfee)->first();
                    $totalAmount = $details->amount;
                    $fineAmount = 0;
                    $payAmount = $payAmount + $totalAmount + $fineAmount;
                    $penaltyAmount = $penaltyAmount +  $fineAmount;
                }
            }
        }else{

            if($request->gateway == null){
                return json_encode([]);
            }
            //check for outstanding amount
            $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){
                    if(PaymentCalculation::getOutstandingAmount($studentSession,$request) > 0){
                        return json_encode(["errorMessage" => "Your previous session amount is pending.Please contact school for further action."]);
                    } 
                }
            }

            $id = "";
            foreach($feeheads as $idfee){
                $totalHeaders = $totalHeaders + 1;
                if($totalHeaders < count($feeheads))
                $id=$id.$idfee.",";
                else $id=$id.$idfee;
            }
            $payAmount = PaymentCalculation::calculateRoyal($id, $student->idStudent,$request);
            $penaltyAmount = PaymentCalculation::calculateFineRoyal($id, $student->idStudent,$request);
            /*foreach($feeheads as $idfee){
                $totalHeaders = $totalHeaders + 1;
                $details =  \App\FeeHead::where('idFeehead', '=', $idfee)->first();
                $discountfees = DB::table('student_discounts')->where('idStudent', '=', $request->id)->where('idFeehead', '=', $idfee)->where('isActive', 'Y')->first();
                $totalAmount = $details->amount;
                $fineAmount = 0;
                $lastDate = Carbon::parse($details->toDate); 
                $diff = $lastDate->diffInDays(Carbon::now(),false);
                $now = Carbon::now();
                if($diff > 0){
                    if($details->fine != null)
                    $fineAmount = $diff * $details->fine + $fineAmount;
                    
                    if($details->flatFine != null)
                    {
                        if($now->format('M') != $lastDate->format('M')){
                            $now->addMonth();
                            $months = $now->diffInMonths($lastDate);
                            if($months > 0){
                                $fineAmount = $fineAmount + ($details->flatFine * $months);
                            }
                        }else{
                            $fineAmount = $details->flatFine + $fineAmount;
                        }
                    }
                }
                if($discountfees != null)
                $payAmount = $payAmount + $totalAmount + $fineAmount - $discountfees->amount;
                else $payAmount = $payAmount + $totalAmount + $fineAmount;

                $penaltyAmount = $penaltyAmount +  $fineAmount;
            }*/
        }
        //Genrate Order ID
        $order = [];
        $order['idStudent']=$student->idStudent;
        $order['idSchool']=$student->idSchool;
        $order['idFinancialYear']=$student->idFinancialYear;
        $order['idClass']= $student->idClass;
        if($totalHeaders > 1)
        $order['isMultipleFeehead'] = "Y";
        else  $order['isMultipleFeehead'] = "N";

        $order['idFeehead']=$feeheads[0];
        $order['feeheads']=$request->feeheads;
        $order['dateOfTransaction']=Carbon::now()->format('Y-m-d');
        $order['order_amount'] = $payAmount;
        $order['fine_amount'] = $penaltyAmount;
        $order['purpose'] = "Fees";
        if(isset($request->type))
        $order['type'] = $request->type;

        $idOrder = DB::table('order_receipts')->insertGetId($order);
        $mobile = $student->contactPersonMobile;
        if($mobile == null || $mobile == ""){
            $mobile = $student->father_mobile;
        }
        //Generate order Token
        $response["phoneNumber"] = $mobile;
        $response["transaction_id"] = $idOrder;
        /*$objectId = $student->idStudent.$student->idFinancialYear.$student->idSchool;
        $response = $this->createJustPayCustomer(sprintf('%0.2f', $payAmount),$idOrder);
        $idOrder = DB::table('order_receipts')->where('idOrder',$idOrder)->update(
            ["order_id" => $response->id]
        );*/
        $totalAmount = $payAmount;
        /*$postData = [
            'order_id' => 'rcptid' .$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'
        ];
        //DB::table('order_receipts')->where('idOrder', $idOrder)->update(['order_id' => 'rcptid'. $idOrder]);
        //return $this->juspaySession($postData);
        /*
        $response->customerPhone = $student->contactPersonMobile;
        $response->customerEmail = "info@sppedtrackgps.in";
        return json_encode($response);*/
        $orderDetails = DB::table('order_receipts')->where('idOrder',$idOrder)->first();
        $response =  Cashfree::initiateEaseBuzzOrder($orderDetails, $student);
        $idOrder = DB::table('order_receipts')->where('idOrder',$idOrder)->update(
            ["order_id" => $response->data]
        );
        $keyService = DB::table('pg_keys')->where('purpose',$order['purpose'])->where('idSchool',$student->idSchool)->first();
        $feedback["id"] = $response->data;
        $feedback["appId"] =$keyService->key_value;
        $feedback["result"] = "1";
        $feedback["message"] = "Generate Message";
        return json_encode($feedback);
    }

    public function verifyJusPayment(Request $request){
        $order = $request->idOrder;
        $response = json_decode($this->checkJusPayStatus($request->idOrder),true);
        $orderInfo = DB::table('order_receipts')->where('order_id',$order)->update(['notes' => json_encode($request->all())]);
        if ($response['status'] == "CHARGED" && $response['status_id'] == "21") {
            $orderInfo = DB::table('order_receipts')->where('order_id', $request->idOrder)->first();
            if($orderInfo->type == "extra"){
                $stdtransaction = new \App\StudentExtraTransaction();
                $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->remarks = "verifyPaymentRazarpay";
                if(DB::table('student_transaction')->where('paymentDate', today_date())->where('idStudent', $orderInfo->idStudent)->where('paymentMode', 'Online')->where('idFinancialYear', $orderInfo->idFinancialYear)->where('totalPaid', $orderInfo->order_amount)->doesntExist())
                    $stdtransaction->save();
                else{
                    return response()->json(['message' => 'Payment Done']);
                }
                
                $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\ExtraFeehead::where('idExtraFeehead','=',$headers)->get()->toArray();
                        foreach($subheaders as $headerIds)
                            {
                                $stepFine = 0;
                                $stdtransaction_detail = new \App\StudentExtraTransactionDetail();
                                $stdtransaction_detail->idStudent = $orderInfo->idStudent;
                                $stdtransaction_detail->idTransaction = $stdtransaction->idTransaction;
                                $stdtransaction_detail->idFeehead = $headerIds['idExtraFeehead'];
                                $stdtransaction_detail->paymentDate = today_date();
                                $stdtransaction_detail->amountPaid = $headerIds['amount'];
                                $stdtransaction_detail->fine = 0;
                                $stdtransaction_detail->discount = 0.00;
                                $stdtransaction_detail->save();
                           }
                    }
                }
            }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->remarks = "verifyPaymentRazarpay";
                if(DB::table('student_transaction')->where('paymentDate', today_date())->where('idStudent', $orderInfo->idStudent)->where('paymentMode', 'Online')->where('idFinancialYear', $orderInfo->idFinancialYear)->where('totalPaid', $orderInfo->order_amount)->doesntExist())
                    $stdtransaction->save();
                else{
                    return response()->json(['message' => 'Payment Done']);
                }
                
                $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);
                                    } 
                                    if ($headerIds['flatFine'] != null) {
                                        $stepFine = $stepFine + $headerIds['flatFine'];
                                    }
                                }
                                $stdtransaction_detail->fine = 0;
                                $discountfees = DB::table('student_discounts')->where('idStudent', '=', $orderInfo->idStudent)->where('idFeehead', '=', $headerIds['idFeehead'])->where('isActive', 'Y')->first();
                                if($discountfees != null){
                                    $stdtransaction_detail->discount = $discountfees->amount;
                                    $totalDiscount = $totalDiscount + $discountfees->amount;
                                }else
                                $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 juspaySession($postData){
        $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($postData)]);
        $data = $response->getBody()->getContents();
        return $data;
    }

    public function generateCashfreeToken(Request $request){
        return response()->json(['message' => 'Failed to verify your payment.'],404);
        $student = \App\AdmEntry::where('idStudent', '=', $request->id)->first();
        $feeheads = json_decode($request->feeheads);
        $payAmount = 0;
        $penaltyAmount = 0;
        $totalHeaders = 0;
        foreach($feeheads as $idfee){
            $totalHeaders = $totalHeaders + 1;
            $details =  \App\FeeHead::where('idFeehead', '=', $idfee)->first();
            $totalAmount = $details->amount;
            $fineAmount = 0;
            $lastDate = Carbon::parse($details->toDate); 
            $diff = $lastDate->diffInDays(Carbon::now(),false);
            if($diff > 0){
                if($details->fine != null)
                $fineAmount = $diff * $details->fine + $fineAmount;
                
                if($details->flatFine != null){
                    $fineAmount = $details->flatFine + $fineAmount;
                }
            }
            $payAmount = $payAmount + $totalAmount + $fineAmount;
            $penaltyAmount = $penaltyAmount +  $fineAmount;
        }

        //Genrate Order ID
        $order = [];
        $order['idStudent']=$student->idStudent;
        $order['idSchool']=$student->idSchool;
        $order['idFinancialYear']=$student->idFinancialYear;
        $order['idClass']= $student->idClass;
        if($totalHeaders > 1)
        $order['isMultipleFeehead'] = "Y";
        else  $order['isMultipleFeehead'] = "N";

        $order['idFeehead']=$feeheads[0];
        $order['feeheads']=$request->feeheads;
        $order['dateOfTransaction']=Carbon::now()->format('Y-m-d');
        $order['order_amount'] = $payAmount;
        $order['fine_amount'] = $penaltyAmount;
        $idOrder = DB::table('order_receipts')->insertGetId($order);

        //Generate order Token
        $response =  $this->getRazarpayToken($idOrder,sprintf('%0.2f', $payAmount));
        $idOrder = DB::table('order_receipts')->where('idOrder',$idOrder)->update(
            ["order_id" => $response->id]
        );
        //return $response;
        //$response["orderId"] = "Order000".$idOrder;
        //$response["orderAmount"] = $payAmount;
        //$response["appId"] = "143716426076ea107390a3e6d6617341";
        //$response["orderCurrency"] = "INR";
        $response->customerPhone = $student->contactPersonMobile;
        $response->customerEmail = "info@sppedtrackgps.in";
        //return response()->json(['message' => 'Failed to verify your payment.'],404);
        return json_encode($response);
    }


    public function easebuzzReturn(Request $request){
        Log::info(json_encode($request->all()));
        return  response()->json(['status' => 1], 200, ['app-status' => 'success']);
    }

    public function validatePassPay($id){
        $orderInfo = DB::table('order_receipts')->where('idOrder', $id)->first();
        if($orderInfo != null){
            $res = Cashfree::verifyEasebuzzTransaction($orderInfo);
            $response = $res->msg;
            if(isset($response->status)){
                    if($response->status == "success"){
                        if($orderInfo != null){
                            DB::table('order_receipts')->where('idOrder', $id)->update(['isSaved'=>'Y']);
                            if($response->status == "success"){
                                if($orderInfo->type != null){
                                    if($orderInfo->type == "Bus"){
                                        $stdtransaction = new \App\BusTransaction();
                                        $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->remarks = "cashfreeWebhook";
                                        if(DB::table('bus_transaction')->where('paymentDate', today_date())->where('idStudent', $orderInfo->idStudent)->where('paymentMode', 'Online')->where('idFinancialYear', $orderInfo->idFinancialYear)->where('totalPaid', $orderInfo->order_amount)->doesntExist())
                                            $stdtransaction->save();
                                        else{
                                            return response()->json(['message' => 'Payment Webhook Exists']);
                                        }
                                        
                                        $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\BusFeehead::where('idBusFeehead','=',$headers)->get()->toArray();
                                                    foreach($subheaders as $headerIds)
                                                        {
                                                            $stepFine = 0;
                                                            $stdtransaction_detail = new \App\BusTransactionDetail();
                                                            $stdtransaction_detail->idStudent = $orderInfo->idStudent;
                                                            $stdtransaction_detail->idBusTransaction = $stdtransaction->idBusTransaction;
                                                            $stdtransaction_detail->idBusFeehead = $headerIds['idBusFeehead'];
                                                            $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);
                                                                }
                                                                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']);
                                    }
                                    if($orderInfo->type == "extra"){
                                        $stdtransaction = new \App\StudentExtraTransaction();
                                        $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->remarks = "verifyPaymentRazarpay";
                                        if(DB::table('student_transaction')->where('paymentDate', today_date())->where('idStudent', $orderInfo->idStudent)->where('paymentMode', 'Online')->where('idFinancialYear', $orderInfo->idFinancialYear)->where('totalPaid', $orderInfo->order_amount)->doesntExist())
                                            $stdtransaction->save();
                                        else{
                                            return response()->json(['message' => 'Payment Done']);
                                        }
                                        
                                        $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\ExtraFeehead::where('idExtraFeehead','=',$headers)->get()->toArray();
                                                foreach($subheaders as $headerIds)
                                                    {
                                                        $stepFine = 0;
                                                        $stdtransaction_detail = new \App\StudentExtraTransactionDetail();
                                                        $stdtransaction_detail->idStudent = $orderInfo->idStudent;
                                                        $stdtransaction_detail->idTransaction = $stdtransaction->idTransaction;
                                                        $stdtransaction_detail->idFeehead = $headerIds['idExtraFeehead'];
                                                        $stdtransaction_detail->paymentDate = today_date();
                                                        $stdtransaction_detail->amountPaid = $headerIds['amount'];
                                                        $stdtransaction_detail->fine = 0;
                                                        $stdtransaction_detail->discount = 0.00;
                                                        $stdtransaction_detail->save();
                                                }
                                            }
                                        }
                                    }else if($orderInfo->type == "Food"){
                                        $stdtransaction = new \App\FoodTransaction();
                                        $stdtransaction->idStudent = $orderInfo->idStudent;
                                        $stdtransaction->idFinancialYear = $orderInfo->idFinancialYear;
                                        $stdtransaction->paymentDate = today_date();
                                        $stdtransaction->totalPaid = $orderInfo->order_amount;
                                        $stdtransaction->paymentMode = 'Online';
                                        $stdtransaction->receiptNo = 'FCPWNL' . $orderInfo->idOrder;
                                        $stdtransaction->idSchool = $orderInfo->idSchool;
                                        $stdtransaction->status = 'Success';
                                        $stdtransaction->discount = 0.00;
                                        $stdtransaction->fine = $orderInfo->fine_amount;
                                        $stdtransaction->remarks = "";
                        
                                        $checkTransaction = \App\FoodTransaction::where('receiptNo','FCPWNL' . $orderInfo->idOrder)->first();
                                        $status = DB::table('order_receipts')->where('idOrder',$orderInfo->idOrder)->where('status','PAID')->first();
                                        if($checkTransaction == null && $status == null){
                                            //DB::table('order_receipts')->where('order_id',$orderInfo->idOrder)->update(['status' => $response->status]);
                                            $stdtransaction->save();
                                            $selectedHeaders = json_decode($orderInfo->feeheads, true);
                                            foreach($selectedHeaders as $headers){
                                                if($headers['qty'] > 0){
                                                    $stdtransaction_detail = new \App\FoodTransactionDetail();
                                                    $stdtransaction_detail->idStudent = $orderInfo->idStudent;
                                                    $stdtransaction_detail->idTransaction = $stdtransaction->idTransaction;
                                                    $stdtransaction_detail->idProduct = $headers['idProduct'];
                                                    $stdtransaction_detail->qty = $headers['qty'];
                                                    $product =  \App\Food::select('id as idProduct','item_name as productName','pic as productImage', 'price as salePrice', 'idSchool', 'short_description as description','max_buy')->where('id',$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();
                                                }
                                            }
                                        }      
                                    }
                                    else{
                                        $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 = 'RCPWNL' . $orderInfo->idOrder;
                                        $stdtransaction->idSchool = $orderInfo->idSchool;
                                        $stdtransaction->status = 'Success';
                                        $stdtransaction->discount = 0.00;
                                        $stdtransaction->fine = $orderInfo->fine_amount;
                                        $stdtransaction->remarks = "";
                        
                                        $checkTransaction = \App\ShopTransaction::where('receiptNo','RCPWNL' . $orderInfo->idOrder)->first();
                                        $status = DB::table('order_receipts')->where('idOrder',$orderInfo->idOrder)->where('status','PAID')->first();
                                        if($checkTransaction == null && $status == null){
                                            //DB::table('order_receipts')->where('order_id',$orderInfo->idOrder)->update(['status' => $response->status]);
                                            $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();
                                                }
                                            }
                                        }
                                    }                        
                                }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 = 'RCPWNL' . $orderInfo->idOrder;
                                    $stdtransaction->idSchool = $orderInfo->idSchool;
                                    $stdtransaction->status = 'Success';
                                    $stdtransaction->penaltyAmount = 0.00;
                                    $stdtransaction->fine = $orderInfo->fine_amount;
                                    $stdtransaction->discount = 0.00;
                                    $stdtransaction->remarks = "";
                                    if(DB::table('student_transaction')->where('paymentDate', today_date())->where('idStudent', $orderInfo->idStudent)->where('paymentMode', 'Online')->where('idFinancialYear', $orderInfo->idFinancialYear)->where('totalPaid', $orderInfo->order_amount)->doesntExist()){
                                        $stdtransaction->idWebhook = $orderInfo->idOrder;
                                        $stdtransaction->save();
                                    }else{
                                        return response()->json(['message' => 'Payment Done']);
                                    }
                                    
                                    $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($orderInfo->idSchool == 25){
                                                        if( $diff > 0){
                                                            if($headerIds['fine'] == "0.00"){
                                                                if($now->format('M') != $date->format('M')){
                                                                    $now->addMonth();
                                                                    $months = $now->diffInMonths($date);
                                                                    $stepFine = ($headerIds['flatFine'] * $months);
                                                                }else{
                                                                    $stepFine = $headerIds['flatFine'];
                                                                }
                                                            }else{
                                                                $stepFine = $headerIds['fine'];
                                                            }
                                                        }
                                                        $stdtransaction_detail->fine = $stepFine;
                                                    }else{
                                                        if ($diff > 0) {
                                                            if ($headerIds['fine'] != null && $headerIds['fine'] != 0.00) {
                                                                $stepFine = ( $headerIds['fine'] * $diff);
                                                            }
                                                            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(['status' => 1, 'message' => "Saved"], 200, ['app-status' => 'success']);
    }

    public function validatePay(){
        $items = DB::table('order_receipts')->whereNotNull('created_at')->whereNotNull('purpose')->where('corn_run','N')->get();
        $id = "";
        foreach($items as $item){
            $id = $item->idOrder;
            $orderInfo = DB::table('order_receipts')->where('idOrder', $item->idOrder)->first();
            $time1 = Carbon::now();
            $time2 = Carbon::parse($item->created_at);
            $keyService = DB::table('pg_keys')->where('purpose',$orderInfo->purpose)->where('idSchool',$orderInfo->idSchool)->first();
            Log::info( $item->idOrder);
            if($keyService == null) DB::table('order_receipts')->where('idOrder', $item->idOrder)->update(['corn_run'=>'Y']);
            if($orderInfo->isSaved == 'Y') 
            DB::table('order_receipts')->where('idOrder', $item->idOrder)->update(['corn_run'=>'Y']);
            if ($time1->diffInMinutes($time2) > 10 && $orderInfo->isSaved == 'N'){
                $res = Cashfree::verifyEasebuzzTransaction($orderInfo);
                DB::table('order_receipts')->where('idOrder', $item->idOrder)->update(['order_note'=>json_encode($res)]);
                DB::table('order_receipts')->where('idOrder', $item->idOrder)->update(['corn_run'=>'Y']);
                $response = $res->msg;
                if(isset($response->status)){
                    if($response->status == "success"){
                        if($orderInfo != null){
                            if($orderInfo->isSaved == 'Y')  return response()->json(['status' => 1, 'message' => "Duplicate Entry"], 200, ['app-status' => 'success']);
                            DB::table('order_receipts')->where('idOrder', $item->idOrder)->update(['isSaved'=>'Y']);
                            if($response->status == "success"){
                                if($orderInfo->type != null){
                                    if($orderInfo->type == "Bus"){
                                        $stdtransaction = new \App\BusTransaction();
                                        $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->remarks = "cashfreeWebhook";
                                        if(DB::table('bus_transaction')->where('paymentDate', today_date())->where('idStudent', $orderInfo->idStudent)->where('paymentMode', 'Online')->where('idFinancialYear', $orderInfo->idFinancialYear)->where('totalPaid', $orderInfo->order_amount)->doesntExist())
                                            $stdtransaction->save();
                                        else{
                                            return response()->json(['message' => 'Payment Webhook Exists']);
                                        }
                                        
                                        $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\BusFeehead::where('idBusFeehead','=',$headers)->get()->toArray();
                                                    foreach($subheaders as $headerIds)
                                                        {
                                                            $stepFine = 0;
                                                            $stdtransaction_detail = new \App\BusTransactionDetail();
                                                            $stdtransaction_detail->idStudent = $orderInfo->idStudent;
                                                            $stdtransaction_detail->idBusTransaction = $stdtransaction->idBusTransaction;
                                                            $stdtransaction_detail->idBusFeehead = $headerIds['idBusFeehead'];
                                                            $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);
                                                                }
                                                                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']);
                                    }
                                    if($orderInfo->type == "extra"){
                                        $stdtransaction = new \App\StudentExtraTransaction();
                                        $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->remarks = "verifyPaymentRazarpay";
                                        if(DB::table('student_transaction')->where('paymentDate', today_date())->where('idStudent', $orderInfo->idStudent)->where('paymentMode', 'Online')->where('idFinancialYear', $orderInfo->idFinancialYear)->where('totalPaid', $orderInfo->order_amount)->doesntExist())
                                            $stdtransaction->save();
                                        else{
                                            return response()->json(['message' => 'Payment Done']);
                                        }
                                        
                                        $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\ExtraFeehead::where('idExtraFeehead','=',$headers)->get()->toArray();
                                                foreach($subheaders as $headerIds)
                                                    {
                                                        $stepFine = 0;
                                                        $stdtransaction_detail = new \App\StudentExtraTransactionDetail();
                                                        $stdtransaction_detail->idStudent = $orderInfo->idStudent;
                                                        $stdtransaction_detail->idTransaction = $stdtransaction->idTransaction;
                                                        $stdtransaction_detail->idFeehead = $headerIds['idExtraFeehead'];
                                                        $stdtransaction_detail->paymentDate = today_date();
                                                        $stdtransaction_detail->amountPaid = $headerIds['amount'];
                                                        $stdtransaction_detail->fine = 0;
                                                        $stdtransaction_detail->discount = 0.00;
                                                        $stdtransaction_detail->save();
                                                }
                                            }
                                        }
                                    }else if($orderInfo->type == "Food"){
                                        $stdtransaction = new \App\FoodTransaction();
                                        $stdtransaction->idStudent = $orderInfo->idStudent;
                                        $stdtransaction->idFinancialYear = $orderInfo->idFinancialYear;
                                        $stdtransaction->paymentDate = today_date();
                                        $stdtransaction->totalPaid = $orderInfo->order_amount;
                                        $stdtransaction->paymentMode = 'Online';
                                        $stdtransaction->receiptNo = 'FCPWNL' . $orderInfo->idOrder;
                                        $stdtransaction->idSchool = $orderInfo->idSchool;
                                        $stdtransaction->status = 'Success';
                                        $stdtransaction->discount = 0.00;
                                        $stdtransaction->fine = $orderInfo->fine_amount;
                                        $stdtransaction->remarks = "";
                        
                                        $checkTransaction = \App\FoodTransaction::where('receiptNo','FCPWNL' . $orderInfo->idOrder)->first();
                                        $status = DB::table('order_receipts')->where('idOrder',$orderInfo->idOrder)->where('status','PAID')->first();
                                        if($checkTransaction == null && $status == null){
                                            //DB::table('order_receipts')->where('order_id',$orderInfo->idOrder)->update(['status' => $response->status]);
                                            $stdtransaction->save();
                                            $selectedHeaders = json_decode($orderInfo->feeheads, true);
                                            foreach($selectedHeaders as $headers){
                                                if($headers['qty'] > 0){
                                                    $stdtransaction_detail = new \App\FoodTransactionDetail();
                                                    $stdtransaction_detail->idStudent = $orderInfo->idStudent;
                                                    $stdtransaction_detail->idTransaction = $stdtransaction->idTransaction;
                                                    $stdtransaction_detail->idProduct = $headers['idProduct'];
                                                    $stdtransaction_detail->qty = $headers['qty'];
                                                    $product =  \App\Food::select('id as idProduct','item_name as productName','pic as productImage', 'price as salePrice', 'idSchool', 'short_description as description','max_buy')->where('id',$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();
                                                }
                                            }
                                        }      
                                    }
                                    else{
                                        $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 = 'RCPWNL' . $orderInfo->idOrder;
                                        $stdtransaction->idSchool = $orderInfo->idSchool;
                                        $stdtransaction->status = 'Success';
                                        $stdtransaction->discount = 0.00;
                                        $stdtransaction->fine = $orderInfo->fine_amount;
                                        $stdtransaction->remarks = "";
                        
                                        $checkTransaction = \App\ShopTransaction::where('receiptNo','RCPWNL' . $orderInfo->idOrder)->first();
                                        $status = DB::table('order_receipts')->where('idOrder',$orderInfo->idOrder)->where('status','PAID')->first();
                                        if($checkTransaction == null && $status == null){
                                            //DB::table('order_receipts')->where('order_id',$orderInfo->idOrder)->update(['status' => $response->status]);
                                            $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();
                                                }
                                            }
                                        }
                                    }                        
                                }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 = 'RCPWNL' . $orderInfo->idOrder;
                                    $stdtransaction->idSchool = $orderInfo->idSchool;
                                    $stdtransaction->status = 'Success';
                                    $stdtransaction->penaltyAmount = 0.00;
                                    $stdtransaction->fine = $orderInfo->fine_amount;
                                    $stdtransaction->discount = 0.00;
                                    $stdtransaction->remarks = "";
                                    if(DB::table('student_transaction')->where('paymentDate', today_date())->where('idStudent', $orderInfo->idStudent)->where('paymentMode', 'Online')->where('idFinancialYear', $orderInfo->idFinancialYear)->where('totalPaid', $orderInfo->order_amount)->doesntExist()){
                                        $stdtransaction->idWebhook = $orderInfo->idOrder;
                                        $stdtransaction->save();
                                    }else{
                                        return response()->json(['message' => 'Payment Done']);
                                    }
                                    
                                    $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($orderInfo->idSchool == 25){
                                                        if( $diff > 0){
                                                            if($headerIds['fine'] == "0.00"){
                                                                if($now->format('M') != $date->format('M')){
                                                                    $now->addMonth();
                                                                    $months = $now->diffInMonths($date);
                                                                    $stepFine = ($headerIds['flatFine'] * $months);
                                                                }else{
                                                                    $stepFine = $headerIds['flatFine'];
                                                                }
                                                            }else{
                                                                $stepFine = $headerIds['fine'];
                                                            }
                                                        }
                                                        $stdtransaction_detail->fine = $stepFine;
                                                    }else{
                                                        if ($diff > 0) {
                                                            if ($headerIds['fine'] != null && $headerIds['fine'] != 0.00) {
                                                                $stepFine = ( $headerIds['fine'] * $diff);
                                                            }
                                                            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(['status' => 1, 'message' => "Webhook ".$id ], 200, ['app-status' => 'success']);
    }

    public function easebuzzWebhook(Request $request){
        Log::info(json_encode($request->all()));
        if($request->txnid != null && $request->status == "success"){
            $orderInfo = DB::table('order_receipts')->where('idOrder', $request->txnid)->first();
            if($orderInfo != null){
                if($orderInfo->isSaved == 'Y')  response()->json(['status' => 1], 200, ['app-status' => 'success']);
                $response = Cashfree::verifyEasebuzzTransaction($orderInfo);
                DB::table('order_receipts')->where('idOrder', $request->txnid)->update(['isSaved'=>'Y']);
                if($response->status == "success"){
                    if($orderInfo->type != null){
                        if($orderInfo->type == "Bus"){
                            $stdtransaction = new \App\BusTransaction();
                            $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->remarks = "cashfreeWebhook";
                            if(DB::table('bus_transaction')->where('paymentDate', today_date())->where('idStudent', $orderInfo->idStudent)->where('paymentMode', 'Online')->where('idFinancialYear', $orderInfo->idFinancialYear)->where('totalPaid', $orderInfo->order_amount)->doesntExist())
                                $stdtransaction->save();
                            else{
                                return response()->json(['message' => 'Payment Webhook Exists']);
                            }
                            
                            $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\BusFeehead::where('idBusFeehead','=',$headers)->get()->toArray();
                                        foreach($subheaders as $headerIds)
                                            {
                                                $stepFine = 0;
                                                $stdtransaction_detail = new \App\BusTransactionDetail();
                                                $stdtransaction_detail->idStudent = $orderInfo->idStudent;
                                                $stdtransaction_detail->idBusTransaction = $stdtransaction->idBusTransaction;
                                                $stdtransaction_detail->idBusFeehead = $headerIds['idBusFeehead'];
                                                $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);
                                                    }
                                                    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']);
                        }
                        if($orderInfo->type == "extra"){
                            $stdtransaction = new \App\StudentExtraTransaction();
                            $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->remarks = "verifyPaymentRazarpay";
                            if(DB::table('student_transaction')->where('paymentDate', today_date())->where('idStudent', $orderInfo->idStudent)->where('paymentMode', 'Online')->where('idFinancialYear', $orderInfo->idFinancialYear)->where('totalPaid', $orderInfo->order_amount)->doesntExist())
                                $stdtransaction->save();
                            else{
                                return response()->json(['message' => 'Payment Done']);
                            }
                            
                            $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\ExtraFeehead::where('idExtraFeehead','=',$headers)->get()->toArray();
                                    foreach($subheaders as $headerIds)
                                        {
                                            $stepFine = 0;
                                            $stdtransaction_detail = new \App\StudentExtraTransactionDetail();
                                            $stdtransaction_detail->idStudent = $orderInfo->idStudent;
                                            $stdtransaction_detail->idTransaction = $stdtransaction->idTransaction;
                                            $stdtransaction_detail->idFeehead = $headerIds['idExtraFeehead'];
                                            $stdtransaction_detail->paymentDate = today_date();
                                            $stdtransaction_detail->amountPaid = $headerIds['amount'];
                                            $stdtransaction_detail->fine = 0;
                                            $stdtransaction_detail->discount = 0.00;
                                            $stdtransaction_detail->save();
                                       }
                                }
                            }
                        }else if($orderInfo->type == "Food"){
                            $stdtransaction = new \App\FoodTransaction();
                            $stdtransaction->idStudent = $orderInfo->idStudent;
                            $stdtransaction->idFinancialYear = $orderInfo->idFinancialYear;
                            $stdtransaction->paymentDate = today_date();
                            $stdtransaction->totalPaid = $orderInfo->order_amount;
                            $stdtransaction->paymentMode = 'Online';
                            $stdtransaction->receiptNo = 'FCPWNL' . $orderInfo->idOrder;
                            $stdtransaction->idSchool = $orderInfo->idSchool;
                            $stdtransaction->status = 'Success';
                            $stdtransaction->discount = 0.00;
                            $stdtransaction->fine = $orderInfo->fine_amount;
                            $stdtransaction->remarks = "";
            
                            $checkTransaction = \App\FoodTransaction::where('receiptNo','FCPWNL' . $orderInfo->idOrder)->first();
                            $status = DB::table('order_receipts')->where('idOrder',$orderInfo->idOrder)->where('status','PAID')->first();
                            if($checkTransaction == null && $status == null){
                                //DB::table('order_receipts')->where('order_id',$orderInfo->idOrder)->update(['status' => $response->status]);
                                $stdtransaction->save();
                                $selectedHeaders = json_decode($orderInfo->feeheads, true);
                                foreach($selectedHeaders as $headers){
                                    if($headers['qty'] > 0){
                                        $stdtransaction_detail = new \App\FoodTransactionDetail();
                                        $stdtransaction_detail->idStudent = $orderInfo->idStudent;
                                        $stdtransaction_detail->idTransaction = $stdtransaction->idTransaction;
                                        $stdtransaction_detail->idProduct = $headers['idProduct'];
                                        $stdtransaction_detail->qty = $headers['qty'];
                                        $product =  \App\Food::select('id as idProduct','item_name as productName','pic as productImage', 'price as salePrice', 'idSchool', 'short_description as description','max_buy')->where('id',$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();
                                    }
                                }
                            }      
                        }
                        else{
                            $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 = 'RCPWNL' . $orderInfo->idOrder;
                            $stdtransaction->idSchool = $orderInfo->idSchool;
                            $stdtransaction->status = 'Success';
                            $stdtransaction->discount = 0.00;
                            $stdtransaction->fine = $orderInfo->fine_amount;
                            $stdtransaction->remarks = "";
            
                            $checkTransaction = \App\ShopTransaction::where('receiptNo','RCPWNL' . $orderInfo->idOrder)->first();
                            $status = DB::table('order_receipts')->where('idOrder',$orderInfo->idOrder)->where('status','PAID')->first();
                            if($checkTransaction == null && $status == null){
                                //DB::table('order_receipts')->where('order_id',$orderInfo->idOrder)->update(['status' => $response->status]);
                                $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();
                                    }
                                }
                            }
                        }                        
                    }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 = 'RCPWNL' . $orderInfo->idOrder;
                        $stdtransaction->idSchool = $orderInfo->idSchool;
                        $stdtransaction->status = 'Success';
                        $stdtransaction->penaltyAmount = 0.00;
                        $stdtransaction->fine = $orderInfo->fine_amount;
                        $stdtransaction->discount = 0.00;
                        $stdtransaction->remarks = "";
                        if(DB::table('student_transaction')->where('paymentDate', today_date())->where('idStudent', $orderInfo->idStudent)->where('paymentMode', 'Online')->where('idFinancialYear', $orderInfo->idFinancialYear)->where('totalPaid', $orderInfo->order_amount)->doesntExist()){
                            $stdtransaction->idWebhook = $orderInfo->idOrder;
                            $stdtransaction->save();
                        }else{
                            return response()->json(['message' => 'Payment Done']);
                        }
                        
                        $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($orderInfo->idSchool == 25){
                                            if( $diff > 0){
                                                if($headerIds['fine'] == "0.00"){
                                                    if($now->format('M') != $date->format('M')){
                                                        $now->addMonth();
                                                        $months = $now->diffInMonths($date);
                                                        $stepFine = ($headerIds['flatFine'] * $months);
                                                    }else{
                                                        $stepFine = $headerIds['flatFine'];
                                                    }
                                                }else{
                                                    $stepFine = $headerIds['fine'];
                                                }
                                            }
                                            $stdtransaction_detail->fine = $stepFine;
                                        }else{
                                            if ($diff > 0) {
                                                if ($headerIds['fine'] != null && $headerIds['fine'] != 0.00) {
                                                    $stepFine = ( $headerIds['fine'] * $diff);
                                                }
                                                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(['status' => 1], 200, ['app-status' => 'success']);
    }

    public function verifyEasebuzz(Request $request){
        $data = json_decode(urldecode($request->result),true);
        if($data != null){
            if($data["txnid"] != null && $data["status"] == "success"){
                $orderInfo = DB::table('order_receipts')->where('idOrder', $data["txnid"])->first();
                if($orderInfo != null){
                    if($orderInfo->isSaved == 'Y')  return response()->json(['message' => 'Payment Done']);
                    $response = Cashfree::verifyEasebuzzTransaction($orderInfo);
                    DB::table('order_receipts')->where('idOrder', $data["txnid"])->update(['isSaved'=>'Y']);
                    if($response->status == "success"){
                        if(isset($request->isReceipt)){
                            if($orderInfo->type == null){
                                try{
                                    $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 = 'RCPWNL' . $orderInfo->idOrder;
                                    $stdtransaction->idSchool = $orderInfo->idSchool;
                                    $stdtransaction->status = 'Success';
                                    $stdtransaction->penaltyAmount = 0.00;
                                    $stdtransaction->fine = $orderInfo->fine_amount;
                                    $stdtransaction->discount = 0.00;
                                    $stdtransaction->remarks = "";
                                    if(DB::table('student_transaction')->where('paymentDate', today_date())->where('idStudent', $orderInfo->idStudent)->where('paymentMode', 'Online')->where('idFinancialYear', $orderInfo->idFinancialYear)->where('totalPaid', $orderInfo->order_amount)->doesntExist()){
                                        $stdtransaction->idWebhook = $orderInfo->idOrder;
                                        $stdtransaction->save();
                                    }else{
                                        return response()->json(['message' => 'Payment Done']);
                                    }
                                    
                                    $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($orderInfo->idSchool == 25){
                                                        if( $diff > 0){
                                                            if($headerIds['fine'] == "0.00"){
                                                                if($now->format('M') != $date->format('M')){
                                                                    $now->addMonth();
                                                                    $months = $now->diffInMonths($date);
                                                                    $stepFine = ($headerIds['flatFine'] * $months);
                                                                }else{
                                                                    $stepFine = $headerIds['flatFine'];
                                                                }
                                                            }else{
                                                                $stepFine = $headerIds['fine'];
                                                            }
                                                        }
                                                        $stdtransaction_detail->fine = $stepFine;
                                                    }else{
                                                        if ($diff > 0) {
                                                            if ($headerIds['fine'] != null && $headerIds['fine'] != 0.00) {
                                                                $stepFine = ( $headerIds['fine'] * $diff);
                                                            }
                                                            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']);
                                }catch(\Exception $e){
                                    return response()->json(['message' => 'Payment Done','exception' => $e->getMessage()]);
                                }
                            }
                        }
                        return response()->json(['message' => 'Payment Done']);
                    }
                }
            }
        }
        return response()->json(['message' => 'Failed to verify your payment.']);
    }

    public function generateEasebuzz(Request $request){
        $student = \App\AdmEntry::where('idStudent', '=', $request->id)->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 json_encode($feedback);
            }
        }

        $feeheads = json_decode($request->feeheads);
        $payAmount = 0;
        $penaltyAmount = 0;
        $totalHeaders = 0;
        $mainFee = 0;
        $data['installment'] = 0;
        $data['p2'] = 0;
        $totalDiscount= 0;
        foreach($feeheads as $idfee){
            $totalHeaders = $totalHeaders + 1;
            $details =  \App\FeeHead::where('idFeehead', '=', $idfee)->first();
            $lesser = DB::table('lesser_transaction_details')->join('feeheads', 'lesser_transaction_details.idFeehead', '=', 'feeheads.idFeehead')
            ->where('lesser_transaction_details.idStudent', '=', $request->id)
            ->where('lesser_transaction_details.idFeehead', $idfee)->get();
            if(count($lesser) > 0){
                $feedback["result"] = "0";
                $feedback["message"] = "Visit school for partial payment.";
                return json_encode($feedback);
            }
            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(Carbon::now(),false);
            if($diff > 0){
                if($details->fine != null)
                $fineAmount = $diff * $details->fine + $fineAmount;
                
                if($details->flatFine != null){
                    $fineAmount = $details->flatFine + $fineAmount;
                }
            }
            $payAmount = $payAmount + $totalAmount + $fineAmount;
            $penaltyAmount = $penaltyAmount +  $fineAmount;
            $discountfees = DB::table('student_discounts')->where('idStudent', '=', $request->id)->where('idFeehead', $idfee)->where('isActive', 'Y')->first();
            if($discountfees != null){
                $totalDiscount = $totalDiscount + $discountfees->amount;
            }
        }
        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;
                        }else if($header->feeheadName == "Plan B (Second Installment)"){
                            $mainFee = 3;
                            break;
                        }
                    }
                }
            }
        }else if($data['p2'] == 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($header->feeheadName ==  "P2(Miscellaneous charges)"){
                            $mainFee = 3;
                            break;
                        }
                    }
                }
            }
        }
       

        if($student->idSchool != 160 && $student->idSchool != 39){
            if($mainFee < 2){
                if($data['installment'] > 0 && $data['p2'] == 1){

                }else if($data['installment'] > 0 && $data['p2'] == 0){
                    $feedback["result"] = "0";
                    $feedback["message"] = "Plese select the fee installment or full payment to pay amount with P2.";
                    return json_encode($feedback);
                }else{
                    $feedback["result"] = "0";
                    $feedback["message"] = "Plese select the fee installment or full payment to pay amount with P1.";
                    return json_encode($feedback);
                }
            }
        }else{
            if($student->idSchool == 140){
                if($mainFee > 2 && $data['p2'] == 1){
                    
                }else 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 json_encode($feedback);
                }
            }
        }        

        //Genrate Order ID
        $order = [];
        $order['idStudent']=$student->idStudent;
        $order['idSchool']=$student->idSchool;
        $order['idFinancialYear']=$student->idFinancialYear;
        $order['idClass']= $student->idClass;
        if($totalHeaders > 1)
        $order['isMultipleFeehead'] = "Y";
        else  $order['isMultipleFeehead'] = "N";

        if($totalDiscount > 0)
        $payAmount = $payAmount - $totalDiscount;

        $order['idFeehead']=$feeheads[0];
        $order['feeheads']=$request->feeheads;
        $order['dateOfTransaction']=Carbon::now()->format('Y-m-d');
        $order['order_amount'] = $payAmount;
        $order['fine_amount'] = $penaltyAmount;
        $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['created_at'] = Carbon::now()->format('Y-m-d H:i:m');
        $order['corn_run'] = "N";
        $idOrder = DB::table('order_receipts')->insertGetId($order);
        $orderDetails = DB::table('order_receipts')->where('idOrder',$idOrder)->first();
        //Generate order Token
        $response =  Cashfree::initiateEaseBuzzOrder($orderDetails, $student);
        $idOrder = DB::table('order_receipts')->where('idOrder',$idOrder)->update(
            ["order_id" => $response->data]
        );
        $keyService = DB::table('pg_keys')->where('purpose',$order['purpose'])->where('idSchool',$student->idSchool)->first();
        $link_id = $this->generateLink($orderDetails->idOrder);
        $feedback["id"] = $response->data;
        $feedback["appId"] =$keyService->key_value;
        $feedback["result"] = "1";
        $feedback["payment_link"] = 'https://online-login.online/payment-link/'.$link_id;
        $feedback["message"] = "Generate Message";
        return json_encode($feedback);
    }

    private function generateLink($idOrder){
        $orderDetails = DB::table('order_receipts')->where('idOrder',$idOrder)->first();
        $uid = $this->guidv4();
        $payment_link =  $uid.'-'.$orderDetails->idStudent;
        $idOrder = DB::table('order_receipts')->where('idOrder',$idOrder)->update(
            ["payment_id" => $payment_link]
        );
        return $payment_link;
    }

    function guidv4($data = null) {
        // Generate 16 bytes (128 bits) of random data or use the data passed into the function.
        $data = $data ?? random_bytes(16);
        assert(strlen($data) == 16);
    
        // Set version to 0100
        $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
        // Set bits 6-7 to 10
        $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
    
        // Output the 36 character UUID.
        return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
    }

    function getRoyalRazarpayStatus($idOrder) {
        $orderInfo = DB::table('order_receipts')->where('idSchool', 25)->where('isSaved','N')->orderBy('idOrder','DESC')->first();
        $client = new Client;
        $response = $client->request('GET', 'https://api.razorpay.com/v1/orders/'.$orderInfo->order_id.'/payments', [ 'headers' => ['Accept' => 'application/json'],'auth' => ['rzp_live_3pII9YBnGYch65', '1GDg04NimKEWNFMqW8OJeGAa']]);
        $data = json_decode($response->getBody());
        if($data->count == 0){
            DB::table('order_receipts')->where('order_id', $orderInfo->order_id)->update(['notes' => "Unable to capture data", 'order_note' => "Failed",'isSaved' => 'Y']);
        }
        $items = $data->items;
        $data->idOrder = $orderInfo->order_id;
        $data->razorpay_payment_id = $items[0]->id;
        $data->razorpay_order_id = $items[0]->order_id;
        $data->paymentDate = date('Y-m-d', $items[0]->created_at);
        $data->isPaid = 1;

        DB::table('order_receipts')->where('order_id', $orderInfo->order_id)->update(['notes' => "Success", 'order_note' => json_encode($items), 'isSaved' => 'Y']);
        if ($items[0]->status == "captured") {
            $orderInfo = DB::table('order_receipts')->where('order_id', $data->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->remarks = "verifyPaymentRazarpay";
            if(DB::table('student_transaction')->where('paymentDate', today_date())->where('idStudent', $orderInfo->idStudent)->where('paymentMode', 'Online')->where('idFinancialYear', $orderInfo->idFinancialYear)->where('totalPaid', $orderInfo->order_amount)->doesntExist())
                $stdtransaction->save();
            else{
                return response()->json(['message' => 'Payment Done']);
            }
            
            $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);
                                } 
                                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 verifyRoyalPaymentRazarpay(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();
            
            if($orderInfo->type == "extra"){
                $stdtransaction = new \App\StudentExtraTransaction();
                $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->remarks = "verifyPaymentRazarpay";
                if(DB::table('student_transaction')->where('paymentDate', today_date())->where('idStudent', $orderInfo->idStudent)->where('paymentMode', 'Online')->where('idFinancialYear', $orderInfo->idFinancialYear)->where('totalPaid', $orderInfo->order_amount)->doesntExist())
                    $stdtransaction->save();
                else{
                    return response()->json(['message' => 'Payment Done']);
                }
                
                $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\ExtraFeehead::where('idExtraFeehead','=',$headers)->get()->toArray();
                        foreach($subheaders as $headerIds)
                            {
                                $stepFine = 0;
                                $stdtransaction_detail = new \App\StudentExtraTransactionDetail();
                                $stdtransaction_detail->idStudent = $orderInfo->idStudent;
                                $stdtransaction_detail->idTransaction = $stdtransaction->idTransaction;
                                $stdtransaction_detail->idFeehead = $headerIds['idExtraFeehead'];
                                $stdtransaction_detail->paymentDate = today_date();
                                $stdtransaction_detail->amountPaid = $headerIds['amount'];
                                $stdtransaction_detail->fine = 0;
                                $stdtransaction_detail->discount = 0.00;
                                $stdtransaction_detail->save();
                           }
                    }
                }
            }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->remarks = "verifyPaymentRazarpay";
                if(DB::table('student_transaction')->where('paymentDate', today_date())->where('idStudent', $orderInfo->idStudent)->where('paymentMode', 'Online')->where('idFinancialYear', $orderInfo->idFinancialYear)->where('totalPaid', $orderInfo->order_amount)->doesntExist())
                    $stdtransaction->save();
                else{
                    return response()->json(['message' => 'Payment Done']);
                }
                
                $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);
                                    } 
                                    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 billDeskCheckSum(Request $request){
        $student = \App\AdmEntry::where('idStudent', '=', $request->id)->first();
        if($request->pay==1)
        $transactionId='O'.$student->idStudent."F".Carbon::now()->timestamp;
        elseif($request->pay==3)
        $transactionId='O'.$student->idStudent."H".Carbon::now()->timestamp;
        else $transactionId='O'.$student->idStudent."T".Carbon::now()->timestamp;
                
                $feeheaders=array();
                $selectedHeaders=explode(',', $request->feeHeaders);
                
                //Calculate Payable Amount
                $chqbounce = \App\FailedTransaction::where('idStudent', '=', $student->idStudent)
                ->where('idFinancialYear', '=', $student->idFinancialYear)
                ->where('status', '=', 'Bounced')
                ->where('chqFineStatus', '=', '0')
                ->get();

                $penaltyAmount = 0;
                $amountDiscount = 0;
                $chqIds=array();
                
                if (isset($chqbounce)) {
                    foreach ($chqbounce as $chqFine)
                       {
                           $penaltyAmount = $penaltyAmount + $chqFine->chequeBounceCharge;
                            array_push($chqIds, $chqFine->idFailedTransaction);
                       }
                }
        
                
                $totalAmount = 0;
                $lessPaid = 0;
                $totalDays=array();
                $fineheads=\DB::table('northfines')->where('idSchool', '=', $student->idSchool)->where('idFinancialYear', '=', $student->idFinancialYear)->get();  
                $flatfine=0;
                $perDay=array();
                foreach($fineheads as $fine){
                 if($fine->isFlat==1)
                      $flatfine=$fine->amount;
                else{
                      array_push($perDay,$fine); 
                     } 
                 }
                  $now = Carbon::now(); 
                //Match the feeheaders with the selected one's
                foreach($selectedHeaders as $cartHeaders){
                    $parent=\App\NorthFeeHead::where('idFeehead', $cartHeaders)->where('isParent', '0')->first();
                    if($parent != null){
                        $totalFine=0; 
                        $date = Carbon::parse($parent->toDate); 
                        $diff = $date->diffInDays($now,false);
                        
                        if( $diff < 0){
                        $totalFine=0;
                        }
                        if($parent->fine== 'flat' && $diff > 0){
                            $totalFine=$flatfine;
                        }elseif($parent->fine == 'per' && $diff > 0){
                            if($diff > 0){
                                                 foreach($perDay as $per){
                                                    if($per->days <= $diff){
                                                        $totalFine=$per->amount;
                                                        break;
                                                    } 
                                                 }
                                             }
                        }
                    
                        if($request->pay==1)
                        $child_feeheads = \App\NorthFeeHead::where('idStudent', '=', $student->idStudent)->where('isParent', $cartHeaders)->where('idType', 'fee')->get();
                        elseif($request->pay==3)
                        $child_feeheads = \App\NorthFeeHead::where('idStudent', '=', $student->idStudent)->where('isParent', $cartHeaders)->where('idType', 'hostel')->get();
                        else
                        $child_feeheads = \App\NorthFeeHead::where('idStudent', '=', $student->idStudent)->where('isParent', $cartHeaders)->where('idType', 'bus')->get();
                        
                        //return response()->json(['success' => $child_feeheads,'cartitems' => $cartHeaders], 200, ['app-status' => 'success']);
                        if(count($child_feeheads) == 0){
                            $totalAmount=$totalAmount + ( $parent->amount - $parent->discount );
                            //return response()->json(['success' => $totalAmount], 200, ['app-status' => 'success']);
                        }else{
                            foreach($child_feeheads as $headers)   { 
                                $totalAmount=$totalAmount + ( $headers->amount - $headers->discount );
                            }
                        }
                        $totalAmount=$totalAmount+$totalFine;
                    }
                }
                
                $totalAmount = $totalAmount + $penaltyAmount;
        
         //return response()->json(['success' => $totalAmount], 200, ['app-status' => 'success']);
        
        $hash = array();
        if($request->pay==1)
        {
            $data = array('CustomerID' => $transactionId, 'Message' => 'NA', 'TxnAmount' => $totalAmount, 'CurrencyType' => 'INR', 'TypeField1' => 'R', 'SecurityID' => 'aspcs', 'TypeField2' => 'F', 'txtadditional1' => $student->idStudent, 'txtadditional2' =>  strval($student->ecNo), 'txtadditional3' => 'app', 'txtadditional4' => $request->feeHeaders, 'txtadditional5' => 'NA', 'txtadditional6' => 'NA', 'txtadditional7' => 'NA', 'RU' => 'https://online-login.online/gateway/returnbilldesk.php');
            $hash = $this->hashCalculate($data,$request->pay);
        }elseif($request->pay==3)
        {
            //$data = array('CustomerID' => $transactionId, 'Message' => 'NA', 'TxnAmount' => $totalAmount, 'CurrencyType' => 'INR', 'TypeField1' => 'R', 'SecurityID' => 'ykentphsfe', 'TypeField2' => 'F', 'txtadditional1' => $student->idStudent, 'txtadditional2' => strval($student->ecNo), 'txtadditional3' => 'app', 'txtadditional4' => $request->feeHeaders, 'txtadditional5' => 'NA', 'txtadditional6' => 'NA', 'txtadditional7' => 'NA', 'RU' => 'https://online-login.online/gateway/returnbilldesk.php');
            $data = array('CustomerID' => $transactionId, 'Message' => 'NA', 'TxnAmount' => $totalAmount, 'CurrencyType' => 'INR', 'TypeField1' => 'R', 'SecurityID' => 'aspcshfee', 'TypeField2' => 'F', 'txtadditional1' => $student->idStudent, 'txtadditional2' => strval($student->ecNo), 'txtadditional3' => 'app', 'txtadditional4' => $request->feeHeaders, 'txtadditional5' => 'NA', 'txtadditional6' => 'NA', 'txtadditional7' => 'NA', 'RU' => 'https://online-login.online/gateway/returnbilldesk.php');
            $hash = $this->hashCalculate($data,$request->pay);
        }else {
            //$data = array('CustomerID' => $transactionId, 'Message' => 'NA', 'TxnAmount' => $totalAmount, 'CurrencyType' => 'INR', 'TypeField1' => 'R', 'SecurityID' => 'ykenttrfee', 'TypeField2' => 'F', 'txtadditional1' => $student->idStudent, 'txtadditional2' => strval($student->ecNo), 'txtadditional3' => 'app', 'txtadditional4' => $request->feeHeaders, 'txtadditional5' => 'NA', 'txtadditional6' => 'NA', 'txtadditional7' => 'NA', 'RU' => 'https://online-login.online/gateway/returnbilldesk.php');
            $data = array('CustomerID' => $transactionId, 'Message' => 'NA', 'TxnAmount' => $totalAmount, 'CurrencyType' => 'INR', 'TypeField1' => 'R', 'SecurityID' => 'aspcstfee', 'TypeField2' => 'F', 'txtadditional1' => $student->idStudent, 'txtadditional2' => strval($student->ecNo), 'txtadditional3' => 'app', 'txtadditional4' => $request->feeHeaders, 'txtadditional5' => 'NA', 'txtadditional6' => 'NA', 'txtadditional7' => 'NA', 'RU' => 'https://online-login.online/gateway/returnbilldesk.php');
            $hash = $this->hashTransportCalculate($data);
        }
        
        
        //return response()->json(['success' => $data], 200, ['app-status' => 'success']);
        
        if($hash && $this-> addTransaction($student,$transactionId,$totalAmount,$selectedHeaders,$penaltyAmount
        ,$chqIds,0,0)==1){
            if($request->pay==1)
          return response()->json(['success' => "SUCCESS","hash"=>$hash,"financialYear"=>$student->ecNo,"email"=>"test@gmail.com","phoneNumber"=>"7620656789","referenceId"=>$transactionId,"amount"=>$totalAmount,"headers"=>$request->feeHeaders,"mode"=>"pay"], 200, ['app-status' => 'success']);   
          elseif($request->pay==3)
          return response()->json(['success' => "SUCCESS","hash"=>$hash,"financialYear"=>$student->ecNo,"email"=>"test@gmail.com","phoneNumber"=>"7620656789","referenceId"=>$transactionId,"amount"=>$totalAmount,"headers"=>$request->feeHeaders,"mode"=>"hostel"], 200, ['app-status' => 'success']);   
          else return response()->json(['success' => "SUCCESS","hash"=>$hash,"financialYear"=>$student->ecNo,"email"=>"test@gmail.com","phoneNumber"=>"7620656789","referenceId"=>$transactionId,"amount"=>$totalAmount,"headers"=>$request->feeHeaders,"mode"=>"bus"], 200, ['app-status' => 'success']);   
        }else{
        return response()->json(['success' => "Failed"], 200, ['app-status' => 'success']);
        }
        
        
    }
    
    function addTransaction($request,$transactionId,$totalAmount,$selectedHeaders
    ,$penaltyAmount,$penaltyID,$accessAmount,$accessIDs) {
        $onlineData=array();
        $onlineData['idStudent']=$request->idStudent;
        $onlineData['idFinancialYear']=$request->idFinancialYear;
        $onlineData['idReference']=$transactionId;
        $onlineData['onlineTransactionId']=$transactionId;
        $onlineData['code']=0;
        $date = Carbon::now();
        $onlineData['created_at']=$date;
        $onlineData['paymentDate']=$date->format('Y-m-d');
        $onlineData['payableAmount']=$totalAmount;
        $onlineData['amount']=$totalAmount;
        $onlineData['accessAmount']=$accessAmount;
        $onlineData['penaltyAmount']=$penaltyAmount;
        $onlineData['idFeehead']=json_encode($selectedHeaders);
        $onlineData['penaltyID']=json_encode($penaltyID);
        $onlineData['accessID']=$accessIDs;
        $insertTransaction=DB::table('student_transaction_online')->insert(
            $onlineData
        );
        if($insertTransaction)  return 1;
        else return 0;
    }
    
    function hashCalculate($input,$isBus){
	/* Columns used for hash calculation, Donot add or remove values from $hash_columns array */
	$hash_columns = ['CustomerID', 'Message','TxnAmount','Message','Message','Message', 'CurrencyType','Message', 'TypeField1', 'SecurityID', 'Message','Message','TypeField2', 'txtadditional1', 'txtadditional2', 'txtadditional3', 'txtadditional4', 'txtadditional5', 'txtadditional6',  'txtadditional7', 'RU'];
	/*Sort the array before hashing*/
	//sort($hash_columns);

	/*Create a | (pipe) separated string of all the $input values which are available in $hash_columns*/
	if($isBus==1)
	$hash_data='ASPCS';
	elseif($isBus==3) $hash_data = 'ASPCSHFEE';
	else $hash_data = 'ASPCSTFEE';
	
	foreach ($hash_columns as $column) {
		if (isset($input[$column])) {
			if (strlen($input[$column]) > 0) {
				$hash_data .= '|' . trim($input[$column]);
			}else{
			    $hash_data .= '|' . 'NA';
			}
		}
	}
		if($isBus==3)
	$checksum = hash_hmac('sha256',$hash_data,'D4oiuL6drtAx8A15r3IluOuXLuKWBmzO', false);
	elseif($isBus==1)
	$checksum = hash_hmac('sha256',$hash_data,'3MZYkfUVPdW0', false);
	else
	$checksum = hash_hmac('sha256',$hash_data,'tMOaMSP14Aj3AgK5U63YUfl4trCbw34D', false); 
	$checksum = strtoupper($checksum);
	
	 return $checksum;
    }

    function hashTransportCalculate($input){
        /* Columns used for hash calculation, Donot add or remove values from $hash_columns array */
        $hash_columns = ['CustomerID', 'Message','TxnAmount','Message','Message','Message', 'CurrencyType','Message', 'TypeField1', 'SecurityID', 'Message','Message','TypeField2', 'txtadditional1', 'txtadditional2', 'txtadditional3', 'txtadditional4', 'txtadditional5', 'txtadditional6',  'txtadditional7', 'RU'];
        /*Sort the array before hashing*/
        //sort($hash_columns);
    
        /*Create a | (pipe) separated string of all the $input values which are available in $hash_columns*/
        $hash_data = 'ASPCSTFEE';
        foreach ($hash_columns as $column) {
            if (isset($input[$column])) {
                if (strlen($input[$column]) > 0) {
                    $hash_data .= '|' . trim($input[$column]);
                }else{
                    $hash_data .= '|' . 'NA';
                }
            }
        }
            $checksum = hash_hmac('sha256',$hash_data,'tMOaMSP14Aj3AgK5U63YUfl4trCbw34D', false); 
            $checksum = strtoupper($checksum);
         return $checksum;
    }
    
    function getHeroMotocrop($start,$end){
        if($start == "0") return  response()->json(['data' =>array()], 200, ['app-status' => 'success']);
        $from = date('Y-m-d',strtotime($start));
        $to = date('Y-m-d',strtotime($end));
        $deviceData=DB::table('attandance')->select('attandance.Enrollment_Number as Tag_No','attandance.date as Date','attandance.TimeStamp as In')->where('attandance.status', '=', 'IN')->where('attandance.Device_ID', '=', 555)->whereBetween('attandance.date', [$from, $to])->groupBy('attandance.Enrollment_Number')->get();
        for($i=0;$i<sizeof($deviceData);$i++){
            $outTime=DB::table('attandance')->where('attandance.Enrollment_Number', $deviceData[$i]->Tag_No)->where('attandance.status',  'OUT')->where('attandance.Device_ID', 555)->where('attandance.date', $deviceData[$i]->Date)->latest()
                ->first();
            if($outTime != null)    
            $deviceData[$i]->Out= $outTime->TimeStamp;
            else $deviceData[$i]->Out= "Not Available";
        }
        return  response()->json(['data' => $deviceData], 200, ['app-status' => 'success']);
    }

    

    /*
    
    public function billDeskCheckSum(Request $request){
        $student = \App\AdmEntry::where('idStudent', '=', $request->id)->first();
        if($request->pay==1)
        $transactionId='O'.$student->idStudent."F".Carbon::now()->timestamp;
        else $transactionId='O'.$student->idStudent."T".Carbon::now()->timestamp;
                //Get headers
                $class_feeheads = \App\FeeHead::where('idClass', '=', $student->idClass)
                        ->where('idSection', '=', $student->idSection)
                        ->where('studentCategory', '=', $student->studentType)
                        ->whereNull('idStudent')
                        ->get();
                $allcat_feeheads = \App\FeeHead::where('idClass', '=', $student->idClass)
                        ->where('idSection', '=', $student->idSection)
                        ->where('studentCategory', '=', 'All')
                        ->whereNull('idStudent')
                        ->get();
                $std_feeheads = \App\FeeHead::where('idStudent', '=', $student->idStudent)->get();
             
                $feeheads = new \Illuminate\Database\Eloquent\Collection; //Create empty collection which we know has the merge() method
                $feeheads = $feeheads->merge($class_feeheads);
                $feeheads = $feeheads->merge($std_feeheads);
                $feeheads = $feeheads->merge($allcat_feeheads)->sortBy('fromDate', 1);
                $feeheaders=array();
                $selectedHeaders=explode(',', $request->feeHeaders);
                
                foreach($feeheads as $key => $value)
                {
                    array_push($feeheaders,$value);
                }
                
                //Calculate Payable Amount
                $chqbounce = \App\FailedTransaction::where('idStudent', '=', $student->idStudent)
                ->where('idFinancialYear', '=', $student->idFinancialYear)
                ->where('status', '=', 'Bounced')
                ->where('chqFineStatus', '=', '0')
                ->get();

                $penaltyAmount = 0;
                $amountDiscount = 0;
                $chqIds=array();
                
                if (isset($chqbounce)) {
                    foreach ($chqbounce as $chqFine)
                       {
                           $penaltyAmount = $penaltyAmount + $chqFine->chequeBounceCharge;
                            array_push($chqIds, $chqFine->idFailedTransaction);
                       }
                }
        
                $excess_transaction = DB::table('excess_transaction')
                                ->join('student_transaction', 'excess_transaction.idTransaction', '=', 'student_transaction.idTransaction')
                                ->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');
                                })
                                ->where('excess_transaction.isActive', '=', 'Y')
                                ->orderBy('excess_transaction.idTransaction', 'desc')->first();
        
                $excessAmount = 0;
                $excessIds = array();
                if (isset($excess_transaction))
                {
                    $excessAmount = $excess_transaction->excessAmount;
                    $student_transaction = DB::table('student_transaction')
                        ->select('idTransaction')
                        ->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');
                        })
                        ->get()->toArray();
                        foreach ($student_transaction as $transaction)
                            array_push($excessIds, $transaction->idTransaction);
                }
                
                $excess_transaction = DB::table('excess_transaction')
                        ->whereIn('idTransaction', $excessIds)
                        ->where('isActive', '=', 'Y')
                        ->orderBy('idTransaction', 'desc')->first();
                $totalAmount = 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', $selectedHeaders)
                        ->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;
                        
                
                
                //Match the feeheaders with the selected one's
                for($i=0;$i<sizeof($feeheaders);$i++){
                    $headerObject=json_decode($feeheaders[$i],true);
                    foreach($selectedHeaders as $cartHeaders)
                    if($headerObject['idFeehead'] ==$cartHeaders ) {
                        
                        
                        $stepFine = 0;
                        $stepDiscount = 0;
                        $stepAmount = 0;
                        $headerObject = $feeheaders[$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) {
                                $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 + $penaltyAmount;
        $totalAmount = $totalAmount - $lessPaid;
        
        $excessAmountUsed=0;
        
        if($totalAmount < $excessAmount)
        {
            $totalAmount= 0;
            $excessAmountUsed=$excessAmount-$totalAmount;
        }
        else
        {
            $totalAmount= $totalAmount-$excessAmount;
            $excessAmountUsed=$excessAmount;
        }
        
         //return response()->json(['success' => "Failed"], 200, ['app-status' => 'success']);
        
        if(sizeof($selectedHeaders) > 1 && isset($lesser_transaction->totalPaid)){
            return response()->json(['success' => "lesser"], 200, ['app-status' => 'success']);
        }else
        if($request->pay==1)
        $data = array('CustomerID' => $transactionId, 'Message' => 'NA', 'TxnAmount' => $totalAmount, 'CurrencyType' => 'INR', 'TypeField1' => 'R', 'SecurityID' => 'aspcs', 'TypeField2' => 'F', 'txtadditional1' => $student->idStudent, 'txtadditional2' => $student->idFinancialYear, 'txtadditional3' => 'app', 'txtadditional4' => $request->feeHeaders, 'txtadditional5' => 'NA', 'txtadditional6' => 'NA', 'txtadditional7' => 'NA', 'RU' => 'http://online-login.online/gateway/returnbilldesk.php');
        else $data = array('CustomerID' => $transactionId, 'Message' => 'NA', 'TxnAmount' => $totalAmount, 'CurrencyType' => 'INR', 'TypeField1' => 'R', 'SecurityID' => 'ykenttrfee', 'TypeField2' => 'F', 'txtadditional1' => $student->idStudent, 'txtadditional2' => $student->idFinancialYear, 'txtadditional3' => 'app', 'txtadditional4' => $request->feeHeaders, 'txtadditional5' => 'NA', 'txtadditional6' => 'NA', 'txtadditional7' => 'NA', 'RU' => 'http://online-login.online/gateway/returnbilldesk.php');
        
        $hash = $this->hashCalculate($data,$request->pay);
        
        //return response()->json(['success' => "Failed"], 200, ['app-status' => 'success']);
        
        if($hash && $this-> addTransaction($student,$transactionId,$totalAmount,$selectedHeaders,$penaltyAmount
        ,$chqIds,$excessAmountUsed,isset($excess_transaction)?$excess_transaction->idExcessTransaction:"")==1){
            if($request->pay==1)
          return response()->json(['success' => "SUCCESS","hash"=>$hash,"financialYear"=>$student->idFinancialYear,"email"=>"test@gmail.com","phoneNumber"=>"7620656789","referenceId"=>$transactionId,"amount"=>$totalAmount,"headers"=>$request->feeHeaders,"mode"=>"pay"], 200, ['app-status' => 'success']);   
          else return response()->json(['success' => "SUCCESS","hash"=>$hash,"financialYear"=>$student->idFinancialYear,"email"=>"test@gmail.com","phoneNumber"=>"7620656789","referenceId"=>$transactionId,"amount"=>$totalAmount,"headers"=>$request->feeHeaders,"mode"=>"bus"], 200, ['app-status' => 'success']);   
        }else{
        return response()->json(['success' => "Failed"], 200, ['app-status' => 'success']);
        }
        
        
    }
    
    */
    
}

Copyright © 2021 - 2025 IMMREX7