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/SwiftController.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 \App\Http\SendNotificationApi;
use App\Http\Cashfree;
use Carbon\Carbon;
use App\Http\PaymentCalculation;

class SwiftController extends Controller {

    public function getFeeDetails($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'){
            $fetchSession = \App\FinancialYear::where('idFinancialYear','>=',$student->idFinancialYear)->get();
            $fy = array();
            $paymodes = [];
            $summary = [
                "feeTotal" => 0,
                "discount" => 0,
                "fine" => 0,
                "additional" => 0,
                "penaltyAmt" => 0,
                "paidFine" => 0,
                "totalAmount" => 0,
                "balance" => 0,
                "outstanding" =>0,
                "paidfees" => 0
            ];

            $plan = "";
            $transaction = new \Illuminate\Database\Eloquent\Collection; //Create empty collection which we know has the merge() method
            $paidfees = \App\StudentTransaction::where('idStudent', '=', $id)->where('idFinancialYear','=',$student->idFinancialYear)->get();
            $lessfees = \App\LesserTransaction::where('idStudent', '=', $id)->where('idFinancialYear','=',$student->idFinancialYear)->get();
            $transaction = $transaction->merge($lessfees);
            $transaction = $transaction->merge($paidfees);

            if($school->idSchool == 25){
                if($paidfees->count() > 0){
                    foreach($paidfees as $paidfee){
                        $transactions = \App\StudentTransactionDetail::where('idTransaction','=',$paidfee->idTransaction)->get();
                        foreach($transactions as $var){
                            $header = \DB::table('feeheads')->where('idFeehead',$var->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;
                    }
                }
            }else if($student->idSchool == 140 || $student->idSchool == 135 || $student->idSchool == 159 || $student->idSchool == 160 || $student->idSchool == 139){
                if($paidfees->count() > 0){
                    foreach($paidfees as $paidfee){
                        $transactions = \App\StudentTransactionDetail::where('idTransaction','=',$paidfee->idTransaction)->get();
                        foreach($transactions as $var){
                            $header = \DB::table('feeheads')->where('idFeehead',$var->idFeehead)->first();
                            if (str_contains($header->feeheadName, 'Full Payment')) {
                                $plan = 'Full';
                                break;
                            }else if (str_contains($header->feeheadName, 'First Installment')){
                                $plan = 'Installment';
                                break;
                            }
                        }

                        if($plan != '') break;
                    }
                }
            }
            
            if($school->idSchool == 25){
                if($plan == "" || $plan == "Plan A"){
                    $plana_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 A%')
                    ->whereNull('idStudent');
                        //   ->get();
                    $plana_allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                                                    ->where('idSection', '=', $student->idSection)
                                                    ->where('studentCategory', '=', 'All')
                                                    ->where('idFinancialYear', '=', $student->idFinancialYear)
                                                    ->where('feeheadLabel', 'LIKE', 'Plan A%')
                                                    ->whereNull('idStudent');
                                            //   ->get();
                    $plana_feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                                                    ->where('idFinancialYear', '=', $student->idFinancialYear)
                                                    ->where('feeheadLabel', 'LIKE', 'Plan A%')
                                                    ->union($plana_class_feeheads)
                                                    ->union($plana_allcat_feeheads)
                                                    ->orderBy('toDate')
                                                    ->get();
                    $afeetotal = $plana_feeheads->sum('amount');

                    array_push($paymodes,array(
                    'feeheadName' => 'Fees in Full Payment',
                    'isPaid' => 'Plan A',
                    'amount'=> floatval($afeetotal)
                    ));
                }
                if($plan == "" || $plan == "Plan B"){
                $planb_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 B%')
                                            ->whereNull('idStudent');
                                            //   ->get();
                                            $planb_allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                                                    ->where('idSection', '=', $student->idSection)
                                                    ->where('studentCategory', '=', 'All')
                                                    ->where('idFinancialYear', '=', $student->idFinancialYear)
                                                    ->where('feeheadLabel', 'LIKE', 'Plan B%')
                                                    ->whereNull('idStudent');
                                            //   ->get();
                                            $planb_feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                                                    ->where('idFinancialYear', '=', $student->idFinancialYear)
                                                    ->where('feeheadLabel', 'LIKE', 'Plan B%')
                                                    ->union($planb_class_feeheads)
                                                    ->union($planb_allcat_feeheads)
                                                    ->orderBy('toDate')
                                                    ->get();
                                            $bfeetotal = $planb_feeheads->sum('amount');
                                            
                                            array_push($paymodes,array(
                                                'feeheadName' => 'Fees in Terms',
                                                'isPaid' => 'Plan B',
                                                'amount' => floatval($bfeetotal)
                                            ));
                                        }
                                        if($plan == "" || $plan == "Plan C"){
                $planc_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 C%')
                                            ->whereNull('idStudent');
                                            //   ->get();
                                            $planc_allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                                                    ->where('idSection', '=', $student->idSection)
                                                    ->where('studentCategory', '=', 'All')
                                                    ->where('idFinancialYear', '=', $student->idFinancialYear)
                                                    ->where('feeheadLabel', 'LIKE', 'Plan C%')
                                                    ->whereNull('idStudent');
                                            //   ->get();
                                            $planc_feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                                                    ->where('idFinancialYear', '=', $student->idFinancialYear)
                                                    ->where('feeheadLabel', 'LIKE', 'Plan C%')
                                                    ->union($planc_class_feeheads)
                                                    ->union($planc_allcat_feeheads)
                                                    ->orderBy('toDate')
                                                    ->get();
                                            $cfeetotal = $planc_feeheads->sum('amount');   
                                           
                                            array_push($paymodes,array(
                                                'feeheadName' => 'Fees in Installments',
                                                'isPaid' => 'Plan C',
                                                'amount'=> floatval($cfeetotal)
                                            ));  
                                        } 
                if($request->get('paymode') == null){
                    if($plan == ""){
                        $summary['feeTotal'] = floatval($afeetotal);
                        $summary['totalAmount'] = floatval($afeetotal);
                    }else{
                        foreach($paymodes as $modes){
                            $summary['feeTotal'] = floatval($modes['amount']);
                            $summary['totalAmount'] = floatval($modes['amount']);
                        }
                    }
                }
            }else if($student->idSchool == 140 || $student->idSchool == 135 || $student->idSchool == 159 || $student->idSchool == 160 || $student->idSchool == 139){
                $plana_class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                    ->where('idSection', '=', $student->idSection)
                    ->where('idFinancialYear', '=', $student->idFinancialYear)
                    ->where('studentCategory', '=', $student->studentType)
                    ->whereNull('idStudent');
                        //   ->get();
                $plana_allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                        ->where('idSection', '=', $student->idSection)
                        ->where('studentCategory', '=', 'All')
                        ->where('idFinancialYear', '=', $student->idFinancialYear)
                        ->whereNull('idStudent');
                                            //   ->get();
                $plana_feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                        ->where('idFinancialYear', '=', $student->idFinancialYear)
                                                    ->union($plana_class_feeheads)
                                                    ->union($plana_allcat_feeheads)
                                                    ->orderBy('toDate')
                                                    ->get();
                $a_full = 0;
                $a_installment = 0;
                foreach($plana_feeheads as $afee){
                    if(str_contains($afee->feeheadName, "Admission")){
                        $already_paid_feehead = \App\StudentTransactionDetail::where('idStudent', '=', $id)
                                    ->where('idFeehead', '=', $afee->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 == null){ 
                            array_push($paymodes,array(
                                'feeheadName' => 'Admission Fee',
                                'isPaid' => 'Admission',
                                'amount'=> floatval($afee->amount)
                            ));
                            break;
                        }else{
                            $a_full = $a_full + $afee->amount;
                            $a_installment = $a_installment + $afee->amount;
                        }
                    }else if(str_contains($afee->feeheadName, "Full Payment")){
                        $a_full = $a_full + $afee->amount;
                    }else if(str_contains($afee->feeheadName, "First Installment") || str_contains($afee->feeheadName, "Second Installment")){
                        $a_installment = $a_installment + $afee->amount;
                    }else{
                        $a_full = $a_full + $afee->amount;
                        $a_installment = $a_installment + $afee->amount;
                    }
                }

                if($plan == ""){
                    array_push($paymodes,array(
                        'feeheadName' => 'Full Payment',
                        'isPaid' => '1',
                        'amount'=> floatval($a_full)
                    ));
    
                    array_push($paymodes,array(
                        'feeheadName' => 'Fees in Installment',
                        'isPaid' => '2',
                        'amount'=> floatval($a_installment)
                    ));
                }else{
                    if($plan == "Full"){
                        array_push($paymodes,array(
                            'feeheadName' => 'Full Payment',
                            'isPaid' => '1',
                            'amount'=> floatval($a_full)
                        ));
                        $summary['feeTotal'] = floatval($a_full);
                        $summary['totalAmount'] = floatval($a_full);
                    }else{
                        array_push($paymodes,array(
                            'feeheadName' => 'Fees in Installment',
                            'isPaid' => '2',
                            'amount'=> floatval($a_installment)
                        ));
                        $summary['feeTotal'] = floatval($a_installment);
                        $summary['totalAmount'] = floatval($a_installment);
                    }
                }

            }else{
                $plana_class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                ->where('idSection', '=', $student->idSection)
                ->where('idFinancialYear', '=', $student->idFinancialYear)
                ->where('studentCategory', '=', $student->studentType)
                ->whereNull('idStudent');
                //   ->get();
                $plana_allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                                        ->where('idSection', '=', $student->idSection)
                                        ->where('studentCategory', '=', 'All')
                                        ->where('idFinancialYear', '=', $student->idFinancialYear)
                                        ->whereNull('idStudent');
                                //   ->get();
                $plana_feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                                        ->where('idFinancialYear', '=', $student->idFinancialYear)
                                        ->union($plana_class_feeheads)
                                        ->union($plana_allcat_feeheads)
                                        ->orderBy('toDate')
                                        ->get();
                $afeetotal = $plana_feeheads->sum('amount');

                array_push($paymodes,array(
                    'feeheadName' => 'Fees',
                    'isPaid' => 'Full',
                    'amount'=> floatval($afeetotal)
                ));
                $summary['feeTotal'] = floatval($afeetotal);
                $summary['totalAmount'] = floatval($afeetotal);
            }

            foreach($fetchSession as $session){
                    $promotions = \App\AdmEntry::where('idSchool', '=', $student->idSchool)
                    ->where('father_mobile','=',$student->father_mobile)
                    ->where('father_fname','=',$student->father_fname)
                    ->where('ecNo','=',$student->ecNo)
                    ->where('idFinancialYear','=',$session->idFinancialYear)
                    ->first();
                if($promotions != null)
                array_push($fy,array(
                    "id" => $promotions->idStudent,
                    "yearName" => $session->financialYearName,
                    "idFinancialYear" => $promotions->idFinancialYear
                ));
            }

            if($school->idSchool == 25){
                //->where('feeheadLabel', 'LIKE', 'Plan C%')
                $feeheaders = PaymentCalculation::calculateFee($student,$request);
                $k =0;
                foreach($feeheaders as $var){
                    $summary['feeTotal'] = $summary['feeTotal'] + $var['amount'];
                    $summary['discount'] = $summary['discount'] + $var['discount'];
                    $summary['fine'] = $summary['fine'] + $var['fine'];
                    $summary['paidFine'] = $summary['paidFine'] + $var['transaction']['paid_fine'];
                    $summary['totalAmount'] = $summary['totalAmount'] + $var['total_amount'];
                    $summary['balance'] = $summary['balance'] + $var['balance'];
                    $summary['paidfees'] = $summary['paidfees'] + $var['transaction']['paid'];
                    if($var['isPaid'] == "Partial Paid"){
                        $feeheaders[$k]['isEnabled'] = false;
                    }
                    $k++;
                }
                $discountfees = DB::table('student_discounts')->where('idStudent', '=', $student->idStudent)->where('isActive', 'Y')->get();
                if($request->get('paymode') != null){
                    return json_encode(array(
                        "fees" => $feeheaders,
                        "paidFee" => $transaction,
                        "paymode" => [],
                        "discount" => $discountfees,
                        "summary" => $summary
                    )); 
                }else{
                    return json_encode(array(
                        "forceFee" => $fy,
                        "paymode" => $paymodes
                    )); 
                } 
            }else if($student->idSchool == 140 || $student->idSchool == 135 || $student->idSchool == 159 || $student->idSchool == 160 || $student->idSchool == 139)
            {
                if($request->get('paymode') != null){
                $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);
                });           
                foreach($transaction as $transact){
                    $feeHead = \App\StudentTransactionDetail::join('feeheads', 'student_transaction_details.idFeehead', '=', 'feeheads.idFeehead')->where('idTransaction', '=', $transact->idTransaction)->first();
                    if($feeHead != null)
                    if($feeHead->idFinancialYear > 244){
                        if(str_contains($feeHead->feeheadName, "Full Payment") || $feeHead->feeheadName == "Plan A (Full Payment)"){
                            $transaction[] = json_decode(json_encode (array(
                                "type" => "book",
                                "idTransaction" => floatval($transact->idTransaction."00"),
                                "receiptNo" => "BOOK".$transact->idTransaction."MH",
                                "totalPaid" => "0.00",
                                "paymentDate" => $transact->paymentDate,
                                "paymentMode" => $transact->paymentMode,
                                "fine" => $transact->fine
                            )), FALSE);
                            break;
                        }                    
                    }
                }
                $discountfees = DB::table('student_discounts')->where('idStudent', '=', $id)->where('idFinancialYear','=',$student->idFinancialYear)->where('isActive', 'Y')->get();
                $feeheaders=array();
                $isPaid = 0;
                foreach($feeheads as $key => $value)
                {

                    $headerObject=json_decode($value,true);
                    $discount = 0;
                    foreach($discountfees as $items){
                        if($items->idFeehead == $headerObject['idFeehead']){
                            $headerObject['amount'] = $headerObject['amount'] - $items->amount;
                            $summary['discount'] = $summary['discount'] + $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'])
                        {
                            $fee_transaction = \App\StudentTransaction::where('idTransaction',$already_paid_feehead->idTransaction)->first();
                            $headerFine = \App\StudentTransactionDetail::where('idFeehead',$headerObject['idFeehead'])->where('idTransaction',$already_paid_feehead->idTransaction)->first();
                            if($headerFine != null){
                                $headerObject['fine'] = $headerFine->fine;
                                $headerObject['amount'] = $headerObject['amount'] + $headerFine->fine;
                            }
                            $summary['paidfees'] = $summary['paidfees'] + $already_paid_feehead->amountPaid;
                            $headerObject['isPaid']='Paid';
                            $isPaid++;
                        }else if($already_paid_feehead->amountPaid > $headerObject['amount'])
                        {
                            $fee_transaction = \App\StudentTransaction::where('idTransaction',$already_paid_feehead->idTransaction)->first();
                            $headerFine = \App\StudentTransactionDetail::where('idFeehead',$headerObject['idFeehead'])->where('idTransaction',$already_paid_feehead->idTransaction)->first();
                            if($headerFine != null){
                                $headerObject['fine'] = $headerFine->fine;
                                $headerObject['amount'] = $headerObject['amount'] + $headerFine->fine;
                            }
                            $summary['paidfees'] = $summary['paidfees'] + $already_paid_feehead->amountPaid;
                            $headerObject['isPaid']='Paid';
                            $isPaid++;
                        }
                        else{
                            $partial_paid =  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)
                            ->where('idFeehead', $headerObject['idFeehead'])
                            ->where(function($query) {
                                $query->whereNull('lesser_transaction.status');
                                $query->orWhere('lesser_transaction.status', '=', 'Cleared');
                                $query->orWhere('lesser_transaction.status', '=', 'In-Process');
                                $query->orWhere('lesser_transaction.status', '=', 'Success');
                            })
                            ->select(DB::raw('SUM(totalPaid) as totalPaid'), DB::raw('SUM(lesser_transaction_details.fine) as fine'))
                            ->first();
                                if(isset($partial_paid->totalPaid)){        
                                    $partialAmount=0;    
                                    $partialAmount=$partialAmount+$partial_paid->totalPaid;
                                    $summary['paidfees'] = $summary['paidfees'] + $partialAmount;
                                    if($partialAmount > 0)    
                                        {
                                            $headerObject['isPaid']='Partial Paid';
                                            $isPaid++;
                                        } 
                                    elseif($partialAmount > $headerObject['amount']  )    
                                    {
                                        $headerObject['isPaid']='Paid';
                                        $isPaid++;
                                    } 
                                    else $headerObject['isPaid']='Due';
                                }
                            else  $headerObject['isPaid']='Due'; 
                        }
                    } else{
                        $partial_paid =  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)
                            ->where('idFeehead', $headerObject['idFeehead'])
                            ->where(function($query) {
                                $query->whereNull('lesser_transaction.status');
                                $query->orWhere('lesser_transaction.status', '=', 'Cleared');
                                $query->orWhere('lesser_transaction.status', '=', 'In-Process');
                                $query->orWhere('lesser_transaction.status', '=', 'Success');
                            })
                            ->select(DB::raw('SUM(totalPaid) as totalPaid'), DB::raw('SUM(lesser_transaction_details.fine) as fine'))
                            ->first(); 
                        if($partial_paid  == null) {
                            $headerObject['isPaid']='Due'; 
                        }
                        else{
                            if(isset($partial_paid->totalPaid)){        
                                $partialAmount=0;    
                                $partialAmount=$partialAmount+$partial_paid->totalPaid;
                                $summary['paidfees'] = $summary['paidfees'] + $partialAmount;
                                if($partialAmount > 0 && $partialAmount < $headerObject['amount'] )    
                                    {
                                        $headerObject['isPaid']='Partial Paid';
                                        $isPaid++;
                                    } 
                                elseif($partialAmount > $headerObject['amount']  )    
                                {
                                    $headerObject['fine'] = $partialAmount - $headerObject['amount'];
                                    $headerObject['amount'] = $partialAmount;
                                    $headerObject['isPaid']='Paid';
                                    $isPaid++;
                                } 
                                else $headerObject['isPaid']='Due';
                            }else  $headerObject['isPaid']='Due'; 
                        }  
                    }  
                    
                    if(str_contains($headerObject['feeheadName'], "Full Payment")){
                        $startDate = Carbon::parse($headerObject['fromDate']);
                        $now = Carbon::now();
                        $dueDiff = $startDate->diffInDays($now, false);
                        $headerObject['isEnabled'] = ($dueDiff > -1);
                        if($dueDiff > -1){
                            $startDate = Carbon::parse($headerObject['toDate']);
                            $now = Carbon::now();
                            $dueDiff = $startDate->diffInDays($now, false);
                            if($dueDiff >= 1)
                            $headerObject['isEnabled'] = false;
                        }
                        array_push($feeheaders,$headerObject);
                        
                    }else{
                        $startDate = Carbon::parse($headerObject['fromDate']);
                        $now = Carbon::now();
                        $dueDiff = $startDate->diffInDays($now, false);
                        $headerObject['isEnabled'] = ($dueDiff > -1);
                        if($dueDiff > -1){
                            $endDate = Carbon::parse($headerObject['toDate']);
                            $now = Carbon::now();
                            $endDiff = $endDate->diffInDays($now, false);
                            $headerObject['isEnabled'] = ($endDiff < 0);
                            if($endDiff < 0){
                                $headerObject['isEnabled'] = true;
                            }
                        }
                        if(!str_contains($headerObject['feeheadName'], "environment")){
                            //if($student->idSchool == 135) $headerObject['isEnabled'] = false;
                        }
                        array_push($feeheaders,$headerObject);
                    }
                }
                
                $feePayment = array();
                    //return json_encode($feeheaders);
                    foreach($feeheaders as $headers){
                        if(str_contains($headers['feeheadName'], "Admission") && $headers['isPaid'] == "Due"){
                            $summary['balance'] = $summary['feeTotal'] - $summary['paidfees'];
                            return json_encode(array(
                                "fees" => [$headers],
                                "paidFee" => $transaction,
                                "discount" => $discountfees,
                                "paymode" => [],
                                "summary" => $summary
                            )); 
                        }else{
                            if(str_contains($headers['feeheadName'], "environment")){
                                array_push($feePayment,$headers);
                            }
                            if(str_contains($headers['feeheadName'], "Admission") && $headers['isPaid'] == "Paid"){
                                array_push($feePayment,$headers);
                            }
                            if(str_contains($headers['feeheadName'], "P1") && $headers['isPaid'] == "Paid"){
                                array_push($feePayment,$headers);
                            }
                            if(str_contains($headers['feeheadName'], "Full Payment") && $request->get('paymode') == 1){
                                array_push($feePayment,$headers);
                            }else if(str_contains($headers['feeheadName'], "First Installment") && $request->get('paymode') == 2 && $headers['isPaid'] == "Due"){
                                array_push($feePayment,$headers);
                            }else if(str_contains($headers['feeheadName'], "First Installment") && $request->get('paymode') == 2 && $headers['isPaid'] == "Paid"){
                                array_push($feePayment,$headers);
                            }
                        }
                    }

                    $isFirstPaid = 0;
                    if($student->idSchool == 140 || $student->idSchool == 135){
                        foreach($feeheaders as $headers){
                            if(str_contains($headers['feeheadName'], "First Installment") && $request->get('paymode') == 2 && $headers['isPaid'] == "Paid"){
                                $isFirstPaid++;
                            }
                            if(str_contains($headers['feeheadName'], "Second Installment") && $request->get('paymode') == 2 && $isFirstPaid > 0 &&  $headers['isPaid'] == "Due"){
                                array_push($feePayment,$headers);
                            }
                        }
                    }

                    foreach($feeheaders as $headers){
                        if(str_contains($headers['feeheadName'], "First Installment") && $request->get('paymode') == 2 && $headers['isPaid'] == "Due" && $student->idSchool == 140){
                            $summary['balance'] = $summary['feeTotal'] - $summary['paidfees'];
                            return json_encode(array(
                                "fees" => $feePayment,
                                "paidFee" => $transaction,
                                "discount" => $discountfees,
                                "paymode" => [],
                                "summary" => $summary
                            )); 
                        }else if(str_contains($headers['feeheadName'], "P1")  && $request->get('paymode') == 2 && $headers['isPaid'] == "Due"){
                            $headers['isForceCheck'] = true;
                            $summary['balance'] = $summary['feeTotal'] - $summary['paidfees'];
                            array_push($feePayment,$headers);
                            return json_encode(array(
                                "fees" => $feePayment,
                                "paidFee" => $transaction,
                                "discount" => $discountfees,
                                "paymode" => [],
                                "summary" => $summary
                            )); 
                        }else if(str_contains($headers['feeheadName'], "P1")  && $request->get('paymode') == 1 && $headers['isPaid'] == "Due" ){
                            $headers['isForceCheck'] = true;
                            $summary['balance'] = $summary['feeTotal'] - $summary['paidfees'];
                            array_push($feePayment,$headers);
                            return json_encode(array(
                                "fees" => $feePayment,
                                "paidFee" => $transaction,
                                "discount" => $discountfees,
                                "paymode" => [],
                                "summary" => $summary
                            )); 
                        }else if(str_contains($headers['feeheadName'], "P2")  && $request->get('paymode') == 2 && $headers['isPaid'] == "Due"){
                            $headers['isForceCheck'] = true;
                            $summary['balance'] = $summary['feeTotal'] - $summary['paidfees'];
                            array_push($feePayment,$headers);
                            return json_encode(array(
                                "fees" => $feePayment,
                                "paidFee" => $transaction,
                                "discount" => $discountfees,
                                "paymode" => [],
                                "summary" => $summary
                            )); 
                        }else if(str_contains($headers['feeheadName'], "P2")  && $request->get('paymode') == 1 && $headers['isPaid'] == "Due"){
                            $headers['isForceCheck'] = true;
                            $summary['balance'] = $summary['feeTotal'] - $summary['paidfees'];
                            array_push($feePayment,$headers);
                            return json_encode(array(
                                "fees" => $feePayment,
                                "paidFee" => $transaction,
                                "discount" => $discountfees,
                                "paymode" => [],
                                "summary" => $summary
                            )); 
                        }
                    }

                    return json_encode(array(
                        "fees" => $feePayment,
                        "paidFee" => $transaction,
                        "discount" => $discountfees,
                        "paymode" => [],
                        "summary" => $summary
                    )); 
                }else{
                    return json_encode(array(
                        "forceFee" => $fy,
                        "paymode" => $paymodes
                    )); 
                } 
            }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);
                });
            }
            
            
            
            
            
            $discountfees = DB::table('student_discounts')->where('idStudent', '=', $id)->where('isActive', 'Y')->get();
            $feeheaders=array();
            foreach($feeheads as $key => $value)
            {
                 $headerObject=json_decode($value,true);
                 $discount = 0;
                 $headerObject['isEnabled'] = true;
                 foreach($discountfees as $items){
                    if($items->idFeehead == $headerObject['idFeehead']){
                        $headerObject['amount'] = $headerObject['amount'] - $items->amount;
                        $summary['discount'] = $summary['discount'] + $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['isEnabled'] = false;
                        $summary['paidfees'] = $summary['paidfees'] + $already_paid_feehead->amountPaid;
                        $headerObject['isPaid']='Paid';
                    }else{
                        $partial_paid =  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)
                        ->where('idFeehead', $headerObject['idFeehead'])
                        ->where(function($query) {
                            $query->whereNull('lesser_transaction.status');
                            $query->orWhere('lesser_transaction.status', '=', 'Cleared');
                            $query->orWhere('lesser_transaction.status', '=', 'In-Process');
                            $query->orWhere('lesser_transaction.status', '=', 'Success');
                        })
                        ->select(DB::raw('SUM(totalPaid) as totalPaid'), DB::raw('SUM(lesser_transaction_details.fine) as fine'))
                        ->first();
                            if(isset($partial_paid->totalPaid)){ 
                                $headerObject['isEnabled'] = false;
                                $summary['paidfees'] = $summary['paidfees'] + $partial_paid->totalPaid;

                                $partialAmount=0;    
                                $partialAmount=$partialAmount+$partial_paid->totalPaid;
                                        
                                if($partialAmount >0)    
                                    $headerObject['isPaid']='Partial Paid'; 
                                else  $headerObject['isPaid']='Due';
                            }
                        else  $headerObject['isPaid']='Due'; 
                        }
                } else {
                    $already_less_feehead = \App\LesserTransactionDetail::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_less_feehead){
                        $partial_paid_less =  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)
                        ->where('idFeehead', $headerObject['idFeehead'])
                        ->where(function($query) {
                            $query->whereNull('lesser_transaction.status');
                            $query->orWhere('lesser_transaction.status', '=', 'Cleared');
                            $query->orWhere('lesser_transaction.status', '=', 'In-Process');
                            $query->orWhere('lesser_transaction.status', '=', 'Success');
                        })
                        ->select(DB::raw('SUM(totalPaid) as totalPaid'), DB::raw('SUM(lesser_transaction_details.fine) as fine'))
                        ->first();

                        $headerObject['isEnabled'] = false;
                        $summary['paidfees'] = $summary['paidfees'] + $partial_paid_less->totalPaid;

                        $partialAmount=0;    
                        $partialAmount=$partialAmount+$partial_paid_less->totalPaid;
                                
                        if($partialAmount >0)    
                            $headerObject['isPaid']='Partial Paid'; 
                        else  $headerObject['isPaid']='Due';
                    }else
                    $headerObject['isPaid']='Due'; 
                    array_push($feeheaders,$headerObject);
                }
            }
            $summary['balance'] = $summary['feeTotal'] - $summary['paidfees'];
            if($request->get('paymode') != null){
                return json_encode(array(
                    "fees" => $feeheaders,
                    "paidFee" => $transaction,
                    "paymode" => [],
                    "discount" => $discountfees,
                    "summary" => $summary
                )); 
            }else{
                return json_encode(array(
                    "forceFee" => $fy,
                    "paymode" => $paymodes
                )); 
            }            
        }else{
            return json_encode(array());
        }
    }

    public function getFeeTransaction(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;
        $order = [];

        if(isset($request->type)){
            return json_encode(["message" => "Visit School Counter to Pay", "result" => 0]);
            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($student->idSchool == 25){
                $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);
            }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;
                }
                if($student->idSchool == 140 || $student->idSchool == 135 || $student->idSchool == 159 || $student->idSchool == 160 || $student->idSchool == 139){
                    foreach($feeheads as $idfee){
                        $totalHeaders = $totalHeaders + 1;
                        $details =  \App\FeeHead::where('idFeehead', '=', $idfee)->first();
                        if(str_contains($details->feeheadName, "Full Payment")){
                            $mainFee++;
                        }
                        if(str_contains($details->feeheadName, "Installment")){
                            $mainFee++;
                            if(str_contains($details->feeheadName, "Second Installment"))
                            $data['installment'] = $data['installment'] + 1;
                        }
                        if(str_contains($details->feeheadName, "Admission")){
                            $mainFee = 2;
                        }
                        if(str_contains($details->feeheadName, "P1")){
                            $mainFee++;
                        }
                        if(str_contains($details->feeheadName, "P2")){
                            $data['p2'] = 1;
                        }
                        $totalAmount = $details->amount;
                        $fineAmount = 0;
                        $lastDate = Carbon::parse($details->toDate); 
                        $diff = $lastDate->diffInDays(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;
                                    }
                                }
                            }
                        }
                    }
            
                
            
                    if($student->idSchool != 160){
                        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['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;           
        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();
        $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["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));
    }

    public function getExtraFeeDetails($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'){
            $fetchSession = \App\FinancialYear::where('idFinancialYear','>=',$student->idFinancialYear)->get();
            $fy = array();
            $paymodes = [];
            $summary = [
                "feeTotal" => 0,
                "discount" => 0,
                "fine" => 0,
                "additional" => 0,
                "penaltyAmt" => 0,
                "paidFine" => 0,
                "totalAmount" => 0,
                "balance" => 0,
                "outstanding" =>0,
                "paidfees" => 0
            ];
            $class_feeheads = \App\ExtraFeehead::whereNull('idClass')->where('extra_feehead.idSchool', '=', $student->idSchool)
                        ->where('extra_feehead.type', '=', 'Online')
                        ->where('extra_feehead.idFinancialYear','=', $student->idFinancialYear);
            $feeheads = \App\ExtraFeehead::where('idClass', '=', $student->idClass)
                        ->where('extra_feehead.idSchool', '=', $student->idSchool)
                        ->where('extra_feehead.type', '=', 'Online')
                        ->where('extra_feehead.idFinancialYear','=', $student->idFinancialYear)
                        ->union($class_feeheads)
                        ->get(); 
            $i=0;  
            $afeetotal  = 0;
            foreach($feeheads as $headers) {
                $paidHeaders= \App\StudentExtraTransaction::leftJoin('student_transaction_extra_details', 'student_transaction_extra.idTransaction', '=', 'student_transaction_extra_details.idTransaction')->where('student_transaction_extra.idStudent', '=', $student->idStudent)->where('idFeehead', '=', $headers->idExtraFeehead)->where(function($query) {
                                $query->whereNull('student_transaction_extra.status');
                                $query->orWhere('student_transaction_extra.status', '=', 'In-Process');
                                $query->orWhere('student_transaction_extra.status', '=', 'Cleared');
                                $query->orWhere('student_transaction_extra.status', '=', 'Success');
                            })->get()->toArray();
                $stepDiscount=0;            
                $feeheads[$i]['discount'] = 0;
                $afeetotal = $afeetotal + $headers->amount - $stepDiscount;
                $feeheads[$i]['isEnabled']=true;
                if(sizeof($paidHeaders)>0){
                    $feeheads[$i]['isEnabled']=false;
                    $summary['paidfees'] = $summary['paidfees'] + $headers->amount;
                    $feeheads[$i]['status']="Paid";
                }else $feeheads[$i]['status']="Due";
                
                $i++;
                            
            }    
            array_push($paymodes,array(
                'feeheadName' => 'Fees',
                'isPaid' => 'Full',
                'amount'=> $afeetotal
            ));
            $summary['feeTotal'] = $afeetotal;
            $summary['totalAmount'] = $afeetotal;   
            $summary['balance'] = $summary['feeTotal'] - $summary['paidfees']; 
            foreach($fetchSession as $session){
                $promotions = \App\AdmEntry::where('idSchool', '=', $student->idSchool)
                ->where('father_mobile','=',$student->father_mobile)
                ->where('father_fname','=',$student->father_fname)
                ->where('ecNo','=',$student->ecNo)
                ->where('idFinancialYear','=',$session->idFinancialYear)
                ->first();
                if($promotions != null)
                array_push($fy,array(
                    "id" => $promotions->idStudent,
                    "yearName" => $session->financialYearName,
                    "idFinancialYear" => $promotions->idFinancialYear
                ));
            }
            $discountfees = [];      
            $paidfees = \App\StudentExtraTransaction::select('student_transaction_extra.*','student_transaction_extra_details.idFeehead')
                        ->leftJoin('student_transaction_extra_details', 'student_transaction_extra.idTransaction', '=', 'student_transaction_extra_details.idTransaction')
                        ->where('student_transaction_extra.idStudent', '=', $id)->get();

            if($request->get('paymode') != null){
                return json_encode(array(
                    "fees" => $feeheads,
                    "paidFee" => $paidfees,
                    "paymode" => [],
                    "discount" => $discountfees,
                    "summary" => $summary
                )); 
            }else{
                return json_encode(array(
                    "forceFee" => $fy,
                    "paymode" => $paymodes
                )); 
            }  
        }
    }

    public function getBusFeeDetails($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'){
            $fetchSession = \App\FinancialYear::where('idFinancialYear','>=',$student->idFinancialYear)->get();
            $fy = array();
            foreach($fetchSession as $session){
                $promotions = \App\AdmEntry::where('idSchool', '=', $student->idSchool)
                ->where('father_mobile','=',$student->father_mobile)
                ->where('father_fname','=',$student->father_fname)
                ->where('ecNo','=',$student->ecNo)
                ->where('idFinancialYear','=',$session->idFinancialYear)
                ->first();
                if($promotions != null)
                array_push($fy,array(
                    "id" => $promotions->idStudent,
                    "yearName" => $session->financialYearName,
                    "idFinancialYear" => $promotions->idFinancialYear
                ));
            }
            $paymodes = [];
            $summary = [
                "feeTotal" => 0,
                "discount" => 0,
                "fine" => 0,
                "additional" => 0,
                "penaltyAmt" => 0,
                "paidFine" => 0,
                "totalAmount" => 0,
                "balance" => 0,
                "outstanding" =>0,
                "paidfees" => 0
            ];
            $stdtransport = \App\StudentTransport::where('student_transport.idFinancialYear', '=', $student->idFinancialYear)
                        ->where('student_transport.idStudent', '=', $student->idStudent)->first();
            
            if($request->get('paymode') != null){
                if($student->idSchool == 25){
                    $feeheads = \App\BusFeehead::where('idStop', '=', $stdtransport->idStop)
                    ->where('feeheadLabel', '=', $request->get('paymode'))
                    ->orderBy('toDate')
                    ->get();
                }else{
                    $feeheads = \App\BusFeehead::where('idStop', '=', $stdtransport->idStop)
                    ->orderBy('toDate')
                    ->get();
                }
            }else{
                if($student->idSchool == 25){
                    $paidfees = \App\BusTransaction::where('idStudent', '=', $student->idStudent)
                    ->where('idFinancialYear', '=', $student->idFinancialYear)
                    ->where(function($query) {
                        $query->whereNull('status');
                        $query->orWhere('status', '=', 'In-Process');
                        $query->orWhere('status', '=', 'Cleared');
                        $query->orWhere('status', '=', 'Success');
                    })->get();
                    $plan = '';
                    $lesserfees = \App\BusLesserTransaction::where('idStudent', '=', $student->idStudent)
                                    ->where('idFinancialYear', '=', $student->idFinancialYear)
                                    ->where(function($query) {
                                        $query->whereNull('status');
                                        $query->orWhere('status', '=', 'In-Process');
                                        $query->orWhere('status', '=', 'Cleared');
                                        $query->orWhere('status', '=', 'Success');
                                    })->get();
                    
                    if($paidfees->count() > 0){
                        foreach($paidfees as $paidfee){
                            $transactions = \App\BusTransactionDetail::where('idBusTransaction','=',$paidfee->idBusTransaction)->get();
                            foreach($transactions as $transaction){
                                $header = \DB::table('busfeeheads')->where('idBusFeehead',$transaction->idBusFeehead)->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($lesserfees->count() > 0){
                        foreach($lesserfees as $paidfee){
                            $transactions = \App\BusLesserTransactionDetail::where('idBusLesserTransaction','=',$paidfee->idBusLesserTransaction)->get();
                            foreach($transactions as $transaction){
                                $header = \DB::table('busfeeheads')->where('idBusFeehead',$transaction->idBusFeehead)->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 != '')
                    $feeheads = \App\BusFeehead::where('idStop', '=', $stdtransport->idStop)
                        ->where('feeheadLabel', '=', $plan)
                        ->orderBy('toDate')
                        ->get();
                    else
                    $feeheads = \App\BusFeehead::where('idStop', '=', $stdtransport->idStop)
                        ->orderBy('toDate')
                        ->get();
                }else{
                    $feeheads = \App\BusFeehead::where('idStop', '=', $stdtransport->idStop)
                    ->orderBy('toDate')
                    ->get();
                }
            }
            
            $i=0;  
            $afeetotal  = 0;
            $feetotal = [];
            $feetotal["plan_a"] = 0;
            $feetotal["plan_b"] = 0;
            $feetotal["plan_c"] = 0;
            $m=0;
            foreach($feeheads as $headers) {
                $startDate = Carbon::parse($headers->fromDate);
                $now = Carbon::now();
                $dueDiff = $startDate->diffInDays($now, false);
                $feeheads[$i]['isEnabled'] = ($dueDiff > -1);

                $paidHeaders= \App\BusTransactionDetail::where('idStudent', '=', $student->idStudent)->where('idBusFeehead', '=', $headers->idBusFeehead)->where(function($query) {
                                $query->whereNull('status');
                                $query->orWhere('status', '=', 'In-Process');
                                $query->orWhere('status', '=', 'Cleared');
                                $query->orWhere('status', '=', 'Success');
                            })->get()->toArray();
                $stepDiscount=0;            
                $isDiscount=\App\BusFeeDiscount::where('idStudent', '=', $student->idStudent)->where('idBusFeehead', '=', $headers->idBusFeehead)->where('isActive', '=', 'Y')->get();            
                foreach($isDiscount as $discount){
                    $stepDiscount=$stepDiscount+$discount->amount;
                }
                $feeheads[$i]['discount']=$stepDiscount;
                $afeetotal = $afeetotal + $headers->amount - $stepDiscount;
                if($student->idSchool == 25){
                    if (str_contains($headers->feeheadLabel, 'Plan A') ){
                        $feetotal["plan_a"] = $feetotal["plan_a"] + $headers->amount - $stepDiscount;
                    }
                    if (str_contains($headers->feeheadLabel, 'Plan B')){
                        $feetotal["plan_b"] = $feetotal["plan_b"] + $headers->amount - $stepDiscount;
                    }
                    if (str_contains($headers->feeheadLabel, 'Plan C')){
                        $feetotal["plan_c"] = $feetotal["plan_c"] + $headers->amount - $stepDiscount;
                    }
                }

                $lesspaidHeaders= \App\BusLesserTransactionDetail::where('idStudent', '=', $student->idStudent)->where('idBusFeehead', '=', $headers->idBusFeehead)->where(function($query) {
                    $query->whereNull('status');
                    $query->orWhere('status', '=', 'In-Process');
                    $query->orWhere('status', '=', 'Cleared');
                    $query->orWhere('status', '=', 'Success');
                })->get()->toArray();

                if(sizeof($lesspaidHeaders)>0){
                    $feeheads[$i]['isEnabled']=false;
                    $totalPaid = \App\BusLesserTransactionDetail::where('idStudent', '=', $student->idStudent)->where('idBusFeehead', '=', $headers->idBusFeehead)
                    ->where(function($query) {
                        $query->whereNull('status');
                        $query->orWhere('status', '=', 'In-Process');
                        $query->orWhere('status', '=', 'Cleared');
                        $query->orWhere('status', '=', 'Success');
                    })->sum('amountPaid');
                    $summary['paidfees'] = $summary['paidfees'] + $totalPaid;
                    if($totalPaid > $headers->amount){
                        $feeheads[$i]['status']="Paid";
                        $feeheads[$i]['isPaid']="Paid";
                    }else{
                        $m++;
                        $feeheads[$i]['status']="Partial Paid";
                        $feeheads[$i]['isPaid']="Partial Paid";
                    }
                    
                }else
                if(sizeof($paidHeaders)>0){
                    $feeheads[$i]['isEnabled']=false;
                    $summary['paidfees'] = $summary['paidfees'] + $headers->amount;
                    $feeheads[$i]['status']="Paid";
                    $feeheads[$i]['isPaid']="Paid";
                }else {
                    $feeheads[$i]['status']="Due";
                    $feeheads[$i]['isPaid']="Due";
                    $m++;
                    if($m > 1){
                        $feeheads[$i]['isEnabled'] = false;
                    }else $feeheads[$i]['isEnabled'] = true;
                }
                $i++;    
            }  

            $discountfees = \App\BusFeeDiscount::where('idStudent', '=', $id)->where('isActive', 'Y')->get();      
            $paidfees = \App\BusTransaction::select('bus_transaction.*',DB::raw('IFNULL(bus_transaction.excessAmountUsed,0.00) as excessAmount'))->where('idStudent', '=', $student->idStudent)
                            ->where(function($query) {
                                $query->whereNull('status');
                                $query->orWhere('status', '=', 'In-Process');
                                $query->orWhere('status', '=', 'Cleared');
                                $query->orWhere('status', '=', 'Success');
                            })->get();

            $lessfees = \App\BusLesserTransaction::select('bus_lesser_transaction.*',DB::raw('IFNULL(bus_lesser_transaction.excessAmountUsed,0.00) as excessAmount'))->where('idStudent', '=', $student->idStudent)
                            ->where(function($query) {
                                $query->whereNull('status');
                                $query->orWhere('status', '=', 'In-Process');
                                $query->orWhere('status', '=', 'Cleared');
                                $query->orWhere('status', '=', 'Success');
                            })->get();

            $combinedCollection = $paidfees->merge($lessfees);                

            if($student->idSchool == 25){
                if($feetotal["plan_a"] > 0)
                array_push($paymodes,array(
                    'feeheadName' => 'Fees in Full Payment',
                    'isPaid' => 'Plan A',
                    'amount'=>  $feetotal["plan_a"]
                ));
                if($feetotal["plan_b"] > 0)
                array_push($paymodes,array(
                    'feeheadName' => 'Fees in Term',
                    'isPaid' => 'Plan B',
                    'amount'=> $feetotal["plan_b"]
                ));
                if($feetotal["plan_c"] > 0)
                array_push($paymodes,array(
                    'feeheadName' => 'Fees in Installment',
                    'isPaid' => 'Plan C',
                    'amount'=> $feetotal["plan_c"]
                ));
            }else{
                array_push($paymodes,array(
                    'feeheadName' => 'Fees',
                    'isPaid' => 'Full',
                    'amount'=> $afeetotal
                ));
            }
            

            $summary['feeTotal'] = $afeetotal;
            $summary['totalAmount'] = $afeetotal;   
            $summary['balance'] = $summary['feeTotal'] - $summary['paidfees']; 

            if($request->get('paymode') != null){
                return json_encode(array(
                    "fees" => $feeheads,
                    "paidFee" => $combinedCollection,
                    "paymode" => [],
                    "discount" => $discountfees,
                    "summary" => $summary
                )); 
            }else{
                return json_encode(array(
                    "forceFee" => $fy,
                    "paymode" => $paymodes
                )); 
            }  
        }
    }

}

Copyright © 2021 - 2025 IMMREX7