IMMREX7

aku nok ndi : /home/spdtg/www/schoolmis/app/Http/
File Up :
aku nok ndi : /home/spdtg/www/schoolmis/app/Http/PaymentCalculation.php

<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace App\Http;

use Illuminate\Http\Request;
use Carbon\Carbon;
use DB;

class PaymentCalculation
{

    static function calculateRoyal($id, $studentId, Request $request)
    {
        $student = \App\AdmEntry::where('idStudent', '=', $studentId)->first();
        $outstandingAmount = 0;
        if ($id == "none") {
            if ($request->get('outstanding') != null) {
                if ($request->get('outstanding') > 0) {
                    $outstanding = DB::table('student_transaction_outstanding')->where('idStudent', $studentId)->where('idOutstanding', $request->get('outstanding'))->first();
                    if ($outstanding != null) {
                        return $outstanding->amount;
                    } else
                        return 0;
                }
            }
        } else if ($request->get('outstanding') != null) {
            if ($request->get('outstanding') > 0) {
                $outstanding = DB::table('student_transaction_outstanding')->where('idStudent', $studentId)->where('idOutstanding', $request->get('outstanding'))->first();
                if ($outstanding != null) {
                    $outstandingAmount = $outstanding->amount;
                }
            }
        }
        $feeheader_ids = array_map('intval', explode(',', $id));
        //return $feeheader_ids;
        $chqbounce = \App\StudentTransaction::where('idStudent', '=', $student->idStudent)
            ->where('idFinancialYear', '=', $student->idFinancialYear)
            ->where('status', '=', 'Bounced')
            ->where('chqFineStatus', '=', '0')
            ->get();

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

        $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;
        if (isset($excess_transaction))
            $excessAmount = $excess_transaction->excessAmount;
        $totalAmount = 0;
        $selectedHeaders = \App\FeeHead::whereIn('idFeehead', $feeheader_ids)->get()->toArray();
        foreach($selectedHeaders as $feeheaders) {
            $headerObject = (array)$feeheaders;
            $discountfees = DB::table('student_discounts')->where('idStudent', $student->idStudent)->where('idFeehead',$headerObject['idFeehead'])->where('isActive', 'Y')->get();
            $headerObject['total_amount'] = $headerObject['amount'];
            //check discount
            $headerObject['discount'] = 0;
            foreach($discountfees as $items){
                $headerObject['discount'] = $headerObject['discount'] + $items->amount;
                $headerObject['total_amount'] = $headerObject['total_amount']  - $items->amount;
            }
            //check fine added to this account
            $headerObject['fine'] = self::calculateFine($headerObject, $student);
            $headerObject['total_amount'] = $headerObject['total_amount'] + $headerObject['fine'];

            //check paid amount,discount,fine
            $headerObject['transaction'] = self::fetchTransaction($headerObject['idFeehead'],$student);
            if($headerObject['total_amount'] > $headerObject['transaction']['paid'])
            {
                $headerObject['extra_amount'] =  0;
                $headerObject['balance'] = $headerObject['total_amount'] - $headerObject['transaction']['paid'];
            }
            else {
                $headerObject['balance'] = 0;
                $headerObject['extra_amount'] = $headerObject['transaction']['paid'] - $headerObject['total_amount'];
            }
            $totalAmount = $totalAmount + $headerObject['balance'];
        }

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

    static function calculateBusRoyal($id, $studentId, Request $request)
    {
        $student = \App\AdmEntry::where('idStudent', '=', $studentId)->first();
        $feeheader_ids = array_map('intval', explode(',', $id));
        //return $feeheader_ids;
        $chqbounce = \App\BusTransaction::where('idStudent', '=', $student->idStudent)
            ->where('idFinancialYear', '=', $student->idFinancialYear)
            ->where('status', '=', 'Bounced')
            ->where('chqFineStatus', '=', '0')
            ->get();

        $penaltyAmount = 0;
        $amountDiscount = 0;
        if (isset($chqbounce)) {
            foreach ($chqbounce as $chqFine)
                $penaltyAmount = $penaltyAmount + $chqFine->chequeBounceCharge;
        }
        $excessAmount = 0;
        $totalAmount = 0;
        $selectedHeaders = \App\BusFeehead::whereIn('idBusFeehead', $feeheader_ids)->get()->toArray();
        foreach($selectedHeaders as $feeheaders) {
            $headerObject = (array)$feeheaders;
            $discountfees = \App\BusFeeDiscount::where('idStudent', $student->idStudent)->where('idBusFeehead',$headerObject['idBusFeehead'])->where('isActive', 'Y')->get();
            $headerObject['total_amount'] = $headerObject['amount'];
            //check discount
            $headerObject['discount'] = 0;
            foreach($discountfees as $items){
                $headerObject['discount'] = $headerObject['discount'] + $items->amount;
                $headerObject['total_amount'] = $headerObject['total_amount']  - $items->amount;
            }
            $headerObject['fine'] = self::calculateBusFine($headerObject, $student);
            $headerObject['total_amount'] = $headerObject['total_amount'] + $headerObject['fine'];

            //check paid amount,discount,fine
            $headerObject['transaction'] = self::fetchBusTransaction($headerObject['idBusFeehead'],$student);
            if($headerObject['total_amount'] > $headerObject['transaction']['paid'])
            {
                $headerObject['extra_amount'] =  0;
                $headerObject['balance'] = $headerObject['total_amount'] - $headerObject['transaction']['paid'];
            }
            else {
                $headerObject['balance'] = 0;
                $headerObject['extra_amount'] = $headerObject['transaction']['paid'] - $headerObject['total_amount'];
            }
            $totalAmount = $totalAmount + $headerObject['balance'];
        }

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

    static function calculateFineRoyal($id, $studentId, Request $request)
    {
        $student = \App\AdmEntry::where('idStudent', '=', $studentId)->first();
        $feeheader_ids = array_map('intval', explode(',', $id));
        //return $feeheader_ids;
        $chqbounce = \App\StudentTransaction::where('idStudent', '=', $student->idStudent)
            ->where('idFinancialYear', '=', $student->idFinancialYear)
            ->where('status', '=', 'Bounced')
            ->where('chqFineStatus', '=', '0')
            ->get();

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

        $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;
        if (isset($excess_transaction))
            $excessAmount = $excess_transaction->excessAmount;
        $totalAmount = 0;
        $selectedHeaders = \App\FeeHead::whereIn('idFeehead', $feeheader_ids)->get()->toArray();
        foreach($selectedHeaders as $feeheaders) {
            $headerObject = (array)$feeheaders;
            //check fine added to this account
            $penaltyAmount = $penaltyAmount + self::calculateFine($headerObject, $student);

        }
        return $penaltyAmount;
    }


    static function calculateFee($student, Request $request)
    {
        date_default_timezone_set('Asia/Kolkata');
        $summary = [
            "feeTotal" => 0,
            "discount" => 0,
            "fine" => 0,
            "additional" => 0,
            "penaltyAmt" => 0,
            "paidFine" => 0,
            "totalAmount" => 0,
            "balance" => 0,
            "paidfees" => 0
        ];
        //default plan
        $currentPlan = 'Plan A';
        if ($request->get('paymode') != '') {
            $currentPlan = $request->get('paymode');
        }
        $plan = \App\StudentTransactionDetail::join('student_transaction', 'student_transaction_details.idTransaction', '=', 'student_transaction.idTransaction')
            ->join('feeheads', 'student_transaction_details.idFeehead', '=', 'feeheads.idFeehead')
            ->where(function($query) {
                $query->whereNull('student_transaction.status');
                $query->orWhere('student_transaction.status', '=', 'Cleared');
                $query->orWhere('student_transaction.status', '=', 'In-Process');
                $query->orWhere('student_transaction.status', '=', 'Success');
            })
            ->where('student_transaction_details.idStudent', $student->idStudent)->first();
        if ($plan != null) {
            $currentPlan = $plan->feeheadLabel;
        } else {
            //lesser details
            $lessPlan = \App\LesserTransactionDetail::join('lesser_transaction', 'lesser_transaction_details.idLesserTransaction', '=', 'lesser_transaction.idLesserTransaction')
                ->join('feeheads', 'lesser_transaction_details.idFeehead', '=', 'feeheads.idFeehead')
                ->where(function($query) {
                    $query->whereNull('lesser_transaction.status');
                    $query->orWhere('lesser_transaction.status', '=', 'Cleared');
                    $query->orWhere('lesser_transaction.status', '=', 'In-Process');
                    $query->orWhere('lesser_transaction.status', '=', 'Success');
                })
                ->where('lesser_transaction_details.idStudent', $student->idStudent)->first();
            if ($lessPlan != null) {
                $currentPlan = $lessPlan->feeheadLabel;
            }
        }

        $class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
            ->where('idSection', '=', $student->idSection)
            ->where('idFinancialYear', '=', $student->idFinancialYear)
            ->where('studentCategory', '=', $student->studentType)
            ->where('feeheadLabel', 'LIKE', $currentPlan . '%')
            ->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', $currentPlan . '%')
            ->whereNull('idStudent');
        $outstanding = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
            ->where('idSection', '=', $student->idSection)
            ->where('studentCategory', '=', 'All')
            ->where('idFinancialYear', '=', $student->idFinancialYear)
            ->where('feeheadName', 'LIKE','Outstanding Payment%')
            ->whereNull('feeheadLabel')
            ->where('idStudent', '=', $student->idStudent);        
        $feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
            ->where('idFinancialYear', '=', $student->idFinancialYear)
            ->where('feeheadLabel', 'LIKE', $currentPlan . '%')
            ->union($class_feeheads)
            ->union($allcat_feeheads)
            ->union($outstanding)
            ->orderBy('toDate')
            ->get()->toArray();


        $feeheaders=array();
        $m=0;
        foreach($feeheads as $feehead){
            $headerObject = (array)$feehead;
            $startDate = Carbon::parse($headerObject['fromDate']);
            $now = Carbon::now();
            $dueDiff = $startDate->diffInDays($now, false);
            $headerObject['isEnabled'] = ($dueDiff > -1);

            $discountfees = DB::table('student_discounts')->where('idStudent', $student->idStudent)->where('idFeehead',$headerObject['idFeehead'])->where('isActive', 'Y')->get();
            $headerObject['total_amount'] = $headerObject['amount'];
            //check discount
            $headerObject['discount'] = 0;
            foreach($discountfees as $items){
                $headerObject['discount'] = $headerObject['discount'] + $items->amount;
                $headerObject['total_amount'] = $headerObject['total_amount']  - $items->amount;
            }
            //check fine added to this account
            $headerObject['fine'] = self::calculateFine($headerObject, $student);
            $headerObject['total_amount'] = $headerObject['total_amount'] + $headerObject['fine'];

            //check paid amount,discount,fine
            $headerObject['transaction'] = self::fetchTransaction($headerObject['idFeehead'],$student);
            if($headerObject['isEnabled'] == false)
                $headerObject['isPaid'] = "Upcoming";
            else $headerObject['isPaid'] = "Due";

            if($headerObject['total_amount'] > $headerObject['transaction']['paid'])
            {
                $headerObject['extra_amount'] =  0;
                $headerObject['balance'] = $headerObject['total_amount'] - $headerObject['transaction']['paid'];
                if($headerObject['transaction']['paid'] > 0){
                    $m--;
                    if($headerObject['transaction']['paid'] + $headerObject['transaction']['paid_fine'] == $headerObject['total_amount']){
                        $headerObject['balance'] = 0;
                        $headerObject['isPaid'] = "Paid";
                    }else{
                        $m++;
                        $headerObject['isPaid'] = "Partial Paid";
                    }
                }else{
                    if(($startDate->diffInDays($now,false)) > 0)
                    $headerObject['isPaid'] = "Upcoming";
                }
            }
            else {

                $m--;
                $headerObject['balance'] = 0;
                $headerObject['isPaid'] = "Paid";
                $headerObject['extra_amount'] = $headerObject['transaction']['paid'] - $headerObject['total_amount'];
            }
            $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'].' 23:59:59');
                    $now = Carbon::now();
                    $endDiff = $endDate->diffInDays($now, false);
                    $headerObject['isEnabled'] = true;
            }
            if($student->idFinancialYear <= 264) $headerObject['isEnabled'] = true;
            $m++;
            if($headerObject['isEnabled'] == true){
                if($m > 1){
                    $headerObject['isEnabled'] = false;
                }else $headerObject['isEnabled'] = true;
            }
            array_push($feeheaders,$headerObject);
        }
        return $feeheaders;
    }



    static function fetchTransaction($idHeader,$student){
        $result = [];
        $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', $idHeader)
            ->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'), DB::raw('SUM(lesser_transaction_details.discount) as discount'))
            ->first();
        if(isset($partial_paid->totalPaid)){
            $result['paid'] = $partial_paid->totalPaid;
            $result['redeem_discount'] = $partial_paid->discount;
            $result['paid_fine'] = $partial_paid->fine;
        }else{
            $already_paid_feehead = \App\StudentTransactionDetail::join('student_transaction', 'student_transaction_details.idTransaction', '=', 'student_transaction.idTransaction')
            ->where('student_transaction.idStudent', '=', $student->idStudent)
            ->where('student_transaction.idFinancialYear', '=', $student->idFinancialYear)
            ->where('idFeehead', $idHeader)
            ->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');
            })->select(DB::raw('student_transaction_details.amountPaid as amountPaid'),DB::raw('student_transaction_details.discount as discount'),DB::raw('student_transaction_details.fine as fine'))
            ->first();
            if(isset($already_paid_feehead->amountPaid)){
                $result['paid'] = $already_paid_feehead->amountPaid;
                $result['redeem_discount'] = $already_paid_feehead->discount;
                $result['paid_fine'] = $already_paid_feehead->fine;
            }else{
                $result['paid'] = 0.00;
                $result['redeem_discount'] = 0.00;
                $result['paid_fine'] = 0.00;
            }
        }   
        
        return $result;
    }

    static function fetchFineTransaction($idHeader,$student){
        $stepFine = 0;
        $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', $idHeader)
            ->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'), DB::raw('SUM(lesser_transaction_details.discount) as discount'))
            ->first();
        if(isset($partial_paid->totalPaid)){
            $stepFine = $stepFine + $partial_paid->fine;
        }else{
            $already_paid_feehead = \App\StudentTransactionDetail::join('student_transaction', 'student_transaction_details.idTransaction', '=', 'student_transaction.idTransaction')
            ->where('student_transaction.idStudent', '=', $student->idStudent)
            ->where('student_transaction.idFinancialYear', '=', $student->idFinancialYear)
            ->where('idFeehead', $idHeader)
            ->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');
            })->select(DB::raw('student_transaction_details.amountPaid as amountPaid'),DB::raw('student_transaction_details.discount as discount'),DB::raw('student_transaction_details.fine as fine'))
            ->first();
            if(isset($already_paid_feehead->amountPaid)){
                $stepFine = $stepFine +  $already_paid_feehead->fine;
            }else{
                $stepFine = $stepFine + 0.00;
            }
        }   
        
        return  $stepFine;
    }

    static function calculateFine($headerObject, $student){
        $date = Carbon::parse($headerObject['toDate']);
        $fullPaid = \App\StudentTransactionDetail::select('student_transaction.paymentDate')->join('student_transaction', 'student_transaction_details.idTransaction', '=', 'student_transaction.idTransaction')
        ->where('student_transaction_details.idFeehead',$headerObject['idFeehead'])
        ->where('student_transaction_details.idStudent', $student->idStudent)
        ->where(function($query) {
            $query->whereNull('student_transaction.status');
            $query->orWhere('student_transaction.status', '=', 'Cleared');
            $query->orWhere('student_transaction.status', '=', 'In-Process');
            $query->orWhere('student_transaction.status', '=', 'Success');
        })->orderBy('student_transaction.idTransaction','DESC')->first();
        if($fullPaid != null){
            $now = Carbon::parse($fullPaid->paymentDate);
            return self::calculateFineResult($headerObject,$now,$date);
        }else{
            $lessPaid = \App\LesserTransactionDetail::select('lesser_transaction.paymentDate')->join('lesser_transaction', 'lesser_transaction_details.idLesserTransaction', '=', 'lesser_transaction.idLesserTransaction')
                ->where('lesser_transaction_details.idStudent', $student->idStudent)
                ->where('lesser_transaction_details.idFeehead', '=', $headerObject['idFeehead'])
                ->select('lesser_transaction.paymentDate')->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');
                })->orderBy('lesser_transaction.idLesserTransaction', 'DESC')->first();
            if($lessPaid != null){
                $now = Carbon::parse($lessPaid->paymentDate);
                return self::calculateFineResult($headerObject,$now,$date);
            }else{
                $now = Carbon::now();
                if (array_key_exists('paymentDate', $headerObject)) {
                    $now = Carbon::parse($headerObject['paymentDate']);
                }
                return self::calculateFineResult($headerObject,$now,$date);
            }
        }
    }

    static function calculateFineResult($headerObject,$now,$date){
        $diff = $date->diffInDays($now, false);
        if( $diff > 0){
            if($headerObject['fine'] == "0.00"){
                if($now->format('M') != $date->format('M')){
                    $now->addMonth();
                    $months = $now->diffInMonths($date);
                    return ($headerObject['flatFine'] * $months);
                }else{
                    return $headerObject['flatFine'];
                }
            }else{
                return $headerObject['fine'];
            }
        }
    }


    static function getOutstandingAmount($student, Request $request)
    {
        $balance = 0;
        //default plan
        $currentPlan = 'Plan A';
        if ($request->get('paymode') != '') {
            $currentPlan = $request->get('paymode');
        }
        $plan = \App\StudentTransactionDetail::join('student_transaction', 'student_transaction_details.idTransaction', '=', 'student_transaction.idTransaction')
            ->join('feeheads', 'student_transaction_details.idFeehead', '=', 'feeheads.idFeehead')
            ->where(function($query) {
                $query->whereNull('student_transaction.status');
                $query->orWhere('student_transaction.status', '=', 'Cleared');
                $query->orWhere('student_transaction.status', '=', 'In-Process');
                $query->orWhere('student_transaction.status', '=', 'Success');
            })
            ->where('student_transaction_details.idStudent', $student->idStudent)->first();
        if ($plan != null) {
            $currentPlan = $plan->feeheadLabel;
        } else {
            //lesser details
            $lessPlan = \App\LesserTransactionDetail::join('lesser_transaction', 'lesser_transaction_details.idLesserTransaction', '=', 'lesser_transaction.idLesserTransaction')
                ->join('feeheads', 'lesser_transaction_details.idFeehead', '=', 'feeheads.idFeehead')
                ->where(function($query) {
                    $query->whereNull('lesser_transaction.status');
                    $query->orWhere('lesser_transaction.status', '=', 'Cleared');
                    $query->orWhere('lesser_transaction.status', '=', 'In-Process');
                    $query->orWhere('lesser_transaction.status', '=', 'Success');
                })
                ->where('lesser_transaction_details.idStudent', $student->idStudent)->first();
            if ($lessPlan != null) {
                $currentPlan = $lessPlan->feeheadLabel;
            }
        }

        $class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
            ->where('idSection', '=', $student->idSection)
            ->where('idFinancialYear', '=', $student->idFinancialYear)
            ->where('studentCategory', '=', $student->studentType)
            ->where('feeheadLabel', 'LIKE', $currentPlan . '%')
            ->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', $currentPlan . '%')
            ->whereNull('idStudent');
        $outstanding = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
            ->where('idSection', '=', $student->idSection)
            ->where('studentCategory', '=', 'All')
            ->where('idFinancialYear', '=', $student->idFinancialYear)
            ->where('feeheadName', 'LIKE','Outstanding Payment%')
            ->whereNull('feeheadLabel')
            ->where('idStudent', '=', $student->idStudent);
        $feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
            ->where('idFinancialYear', '=', $student->idFinancialYear)
            ->where('feeheadLabel', 'LIKE', $currentPlan . '%')
            ->union($class_feeheads)
            ->union($allcat_feeheads)
            ->union($outstanding)
            ->orderBy('idFeehead', 'ASC')
            ->orderBy('toDate')
            ->get()->toArray();


        $feeheaders=array();
        foreach($feeheads as $feehead){
            $headerObject = (array)$feehead;
            $startDate = Carbon::parse($headerObject['fromDate']);
            $now = Carbon::now();
            $dueDiff = $startDate->diffInDays($now, false);
            $headerObject['isEnabled'] = ($dueDiff > -1);

            $discountfees = DB::table('student_discounts')->where('idStudent', $student->idStudent)->where('idFeehead',$headerObject['idFeehead'])->where('isActive', 'Y')->get();
            $headerObject['total_amount'] = $headerObject['amount'];
            //check discount
            $headerObject['discount'] = 0;
            foreach($discountfees as $items){
                $headerObject['discount'] = $headerObject['discount'] + $items->amount;
                $headerObject['total_amount'] = $headerObject['total_amount']  - $items->amount;
            }
            //check fine added to this account
            $headerObject['fine'] = self::calculateFine($headerObject, $student);
            $headerObject['total_amount'] = $headerObject['total_amount'] + $headerObject['fine'];
            //check paid amount,discount,fine
            $headerObject['transaction'] = self::fetchTransaction($headerObject['idFeehead'],$student);
            if($headerObject['total_amount'] > $headerObject['transaction']['paid'])
            {
                if($headerObject['transaction']['paid'] + $headerObject['transaction']['paid_fine'] == $headerObject['total_amount']){
                    $headerObject['balance'] = 0;
                }else
                $headerObject['balance'] = $headerObject['total_amount'] - $headerObject['transaction']['paid'];
            }
            else {
                $headerObject['balance'] = 0;
            }
            $balance = $balance + $headerObject['balance'];
        }
        return $balance;
    }

    static function getReportDueAmount($student)
    {
        $result = [];
        //default plan
        $currentPlan = 'Plan A';
        $plan = \App\StudentTransactionDetail::join('student_transaction', 'student_transaction_details.idTransaction', '=', 'student_transaction.idTransaction')
            ->join('feeheads', 'student_transaction_details.idFeehead', '=', 'feeheads.idFeehead')
            ->where(function($query) {
                $query->whereNull('student_transaction.status');
                $query->orWhere('student_transaction.status', '=', 'Cleared');
                $query->orWhere('student_transaction.status', '=', 'In-Process');
                $query->orWhere('student_transaction.status', '=', 'Success');
            })
            ->where('student_transaction_details.idStudent', $student->idStudent)->first();
        if ($plan != null) {
            $currentPlan = $plan->feeheadLabel;
        } else {
            //lesser details
            $lessPlan = \App\LesserTransactionDetail::join('lesser_transaction', 'lesser_transaction_details.idLesserTransaction', '=', 'lesser_transaction.idLesserTransaction')
                ->join('feeheads', 'lesser_transaction_details.idFeehead', '=', 'feeheads.idFeehead')
                ->where(function($query) {
                    $query->whereNull('lesser_transaction.status');
                    $query->orWhere('lesser_transaction.status', '=', 'Cleared');
                    $query->orWhere('lesser_transaction.status', '=', 'In-Process');
                    $query->orWhere('lesser_transaction.status', '=', 'Success');
                })
                ->where('lesser_transaction_details.idStudent', $student->idStudent)->first();
            if ($lessPlan != null) {
                $currentPlan = $lessPlan->feeheadLabel;
            }
        }

        $class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
            ->where('idSection', '=', $student->idSection)
            ->where('idFinancialYear', '=', $student->idFinancialYear)
            ->where('studentCategory', '=', $student->studentType)
            ->where('feeheadLabel', 'LIKE', $currentPlan . '%')
            ->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', $currentPlan . '%')
            ->whereNull('idStudent');
        $outstanding = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
            ->where('idSection', '=', $student->idSection)
            ->where('studentCategory', '=', 'All')
            ->where('idFinancialYear', '=', $student->idFinancialYear)
            ->where('feeheadName', 'LIKE','Outstanding Payment%')
            ->whereNull('feeheadLabel')
            ->where('idStudent', '=', $student->idStudent);
        $feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
            ->where('idFinancialYear', '=', $student->idFinancialYear)
            ->where('feeheadLabel', 'LIKE', $currentPlan . '%')
            ->union($class_feeheads)
            ->union($allcat_feeheads)
            ->union($outstanding)
            ->orderBy('idFeehead', 'ASC')
            ->orderBy('toDate')
            ->get()->toArray();


        $feeheaders=array();
        $result['balance'] = 0;
        $result['fee'] = 0;
        $result['total_amount'] = 0;
        $result['fine'] = 0;
        $result['finePaid'] = 0;
        $result['feePaid'] = 0;
        $result['discount'] = 0;
        $result['discountPaid'] = 0;
        foreach($feeheads as $feehead){
            $headerObject = (array)$feehead;
            $startDate = Carbon::parse($headerObject['fromDate']);
            $now = Carbon::now();
            $dueDiff = $startDate->diffInDays($now, false);
            $headerObject['isEnabled'] = ($dueDiff > -1);

            $discountfees = DB::table('student_discounts')->where('idStudent', $student->idStudent)->where('idFeehead',$headerObject['idFeehead'])->where('isActive', 'Y')->get();
            $headerObject['total_amount'] = $headerObject['amount'];
            //check discount
            $headerObject['discount'] = 0;
            foreach($discountfees as $items){
                $headerObject['discount'] = $headerObject['discount'] + $items->amount;
                $headerObject['total_amount'] = $headerObject['total_amount']  - $items->amount;
            }
            //check fine added to this account
            $headerObject['fine'] = self::calculateFine($headerObject, $student);
            $headerObject['total_amount'] = $headerObject['total_amount'] + $headerObject['fine'];
            //check paid amount,discount,fine
            $headerObject['transaction'] = self::fetchTransaction($headerObject['idFeehead'],$student);
            if($headerObject['total_amount'] > $headerObject['transaction']['paid'])
            {
                $headerObject['balance'] = $headerObject['total_amount'] - $headerObject['transaction']['paid'];
                $result['feeheadName'] = $headerObject['feeheadName'];
            }
            else {
                $headerObject['balance'] = 0;
            }
            $result['balance'] += $headerObject['balance'];
            $result['fee'] += $headerObject['amount'];
            $result['total_amount'] += $headerObject['total_amount'];
            $result['fine'] += $headerObject['fine'];
            $result['feePaid'] += $headerObject['transaction']['paid'];
            $result['finePaid'] += $headerObject['transaction']['paid_fine'];
            $result['discountPaid'] += $headerObject['transaction']['redeem_discount'];
            $result['discount'] +=$headerObject['discount'];
        }
        return $result;
    }


    static function getReportAmount($student,$idTransaction,$idLessTransaction,$paymentDate)
    {
        $result = [];
        //default plan
        $currentPlan = 'Plan A';
        $plan = \App\StudentTransactionDetail::join('student_transaction', 'student_transaction_details.idTransaction', '=', 'student_transaction.idTransaction')
            ->join('feeheads', 'student_transaction_details.idFeehead', '=', 'feeheads.idFeehead')
            ->where(function($query) {
                $query->whereNull('student_transaction.status');
                $query->orWhere('student_transaction.status', '=', 'Cleared');
                $query->orWhere('student_transaction.status', '=', 'In-Process');
                $query->orWhere('student_transaction.status', '=', 'Success');
            })
            ->where('student_transaction_details.idStudent', $student->idStudent)->first();
        if ($plan != null) {
            $currentPlan = $plan->feeheadLabel;
        } else {
            //lesser details
            $lessPlan = \App\LesserTransactionDetail::join('lesser_transaction', 'lesser_transaction_details.idLesserTransaction', '=', 'lesser_transaction.idLesserTransaction')
                ->join('feeheads', 'lesser_transaction_details.idFeehead', '=', 'feeheads.idFeehead')
                ->where(function($query) {
                    $query->whereNull('lesser_transaction.status');
                    $query->orWhere('lesser_transaction.status', '=', 'Cleared');
                    $query->orWhere('lesser_transaction.status', '=', 'In-Process');
                    $query->orWhere('lesser_transaction.status', '=', 'Success');
                })
                ->where('lesser_transaction_details.idStudent', $student->idStudent)->first();
            if ($lessPlan != null) {
                $currentPlan = $lessPlan->feeheadLabel;
            }
        }

        $class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
            ->where('idSection', '=', $student->idSection)
            ->where('idFinancialYear', '=', $student->idFinancialYear)
            ->where('studentCategory', '=', $student->studentType)
            ->where('feeheadLabel', 'LIKE', $currentPlan . '%')
            ->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', $currentPlan . '%')
            ->whereNull('idStudent');
        $outstanding = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
            ->where('idSection', '=', $student->idSection)
            ->where('studentCategory', '=', 'All')
            ->where('idFinancialYear', '=', $student->idFinancialYear)
            ->where('feeheadName', 'LIKE','Outstanding Payment%')
            ->whereNull('feeheadLabel')
            ->where('idStudent', '=', $student->idStudent);
        $feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
            ->where('idFinancialYear', '=', $student->idFinancialYear)
            ->where('feeheadLabel', 'LIKE', $currentPlan . '%')
            ->union($class_feeheads)
            ->union($allcat_feeheads)
            ->union($outstanding)
            ->orderBy('idFeehead', 'ASC')
            ->orderBy('toDate')
            ->get()->toArray();


        $feeheaders=array();
        $result['balance'] = 0;
        $result['fee'] = 0;
        $result['total_amount'] = 0;
        $result['fine'] = 0;
        $result['finePaid'] = 0;
        $result['feePaid'] = 0;
        $result['discount'] = 0;
        foreach($feeheads as $feehead){
            $headerObject = (array)$feehead;
            $startDate = Carbon::parse($headerObject['fromDate']);
            $now = Carbon::now();
            $dueDiff = $startDate->diffInDays($now, false);
            $headerObject['isEnabled'] = ($dueDiff > -1);

            $discountfees = DB::table('student_discounts')->where('idStudent', $student->idStudent)->where('idFeehead',$headerObject['idFeehead'])->where('isActive', 'Y')->get();
            $headerObject['total_amount'] = $headerObject['amount'];
            //check discount
            $headerObject['discount'] = 0;
            foreach($discountfees as $items){
                $headerObject['discount'] = $headerObject['discount'] + $items->amount;
                $headerObject['total_amount'] = $headerObject['total_amount']  - $items->amount;
            }
            //check fine added to this account
            $headerObject['fine'] = self::calculateFine($headerObject, $student);
            $headerObject['total_amount'] = $headerObject['total_amount'] + $headerObject['fine'];
            //check paid amount,discount,fine
            $headerObject['transaction'] = self::fetchReportTransaction($headerObject['idFeehead'],$student,$idTransaction,$idLessTransaction,$paymentDate);
            if($headerObject['total_amount'] > $headerObject['transaction']['paid'])
            {
                $headerObject['balance'] = $headerObject['total_amount'] - $headerObject['transaction']['paid'];
            }
            else {
                $headerObject['balance'] = 0;
            }
            $result['balance'] += $headerObject['balance'];
            $result['fee'] += $headerObject['amount'];
            $result['total_amount'] += $headerObject['total_amount'];
            $result['fine'] += $headerObject['fine'];
            $result['feePaid'] += $headerObject['transaction']['paid'];
            $result['finePaid'] += $headerObject['transaction']['paid_fine'];
            $result['discount'] +=$headerObject['discount'];
        }
        return $result;
    }

    static function fetchReportTransaction($idHeader,$student,$idTransaction,$idLessTransaction,$paymentDate){
        $result = [];
        $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', $idHeader);

         if($idLessTransaction != "")   
         $partial_paid = $partial_paid->where('lesser_transaction.idLesserTransaction','<=',$idLessTransaction);
         else $partial_paid = $partial_paid->whereDate('lesser_transaction.paymentDate','<=', Carbon::parse($paymentDate)->format('Y-m-d'));
         $partial_paid = $partial_paid->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'), DB::raw('SUM(lesser_transaction_details.discount) as discount'))
            ->first();
        if(isset($partial_paid->totalPaid)){
            $result['paid'] = $partial_paid->totalPaid;
            $result['redeem_discount'] = $partial_paid->discount;
            $result['paid_fine'] = $partial_paid->fine;
        }else{
            $already_paid_feehead = \App\StudentTransactionDetail::join('student_transaction', 'student_transaction_details.idTransaction', '=', 'student_transaction.idTransaction')
            ->where('student_transaction.idStudent', '=', $student->idStudent)
            ->where('student_transaction.idFinancialYear', '=', $student->idFinancialYear)
            ->where('idFeehead', $idHeader);
            if($idLessTransaction != "")   
            $already_paid_feehead = $already_paid_feehead->where('student_transaction.idTransaction','<=',$idTransaction);
            else $already_paid_feehead = $already_paid_feehead->whereDate('student_transaction.paymentDate','<=', Carbon::parse($paymentDate)->format('Y-m-d'));
            $already_paid_feehead = $already_paid_feehead->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');
            })->select(DB::raw('student_transaction_details.amountPaid as amountPaid'),DB::raw('student_transaction_details.discount as discount'),DB::raw('student_transaction_details.fine as fine'))
            ->first();
            if(isset($already_paid_feehead->amountPaid)){
                $result['paid'] = $already_paid_feehead->amountPaid;
                $result['redeem_discount'] = $already_paid_feehead->discount;
                $result['paid_fine'] = $already_paid_feehead->fine;
            }else{
                $result['paid'] = 0.00;
                $result['redeem_discount'] = 0.00;
                $result['paid_fine'] = 0.00;
            }
        }   
        
        return $result;
    }

    static function calculateMhws($feeheader,$student,$request){
        $feeheaders=array();
        $isPaid = 0;
        $discountfees = DB::table('student_discounts')->where('idStudent', '=', $student->idStudent)->where('idFinancialYear','=',$student->idFinancialYear)->where('isActive', 'Y')->get();
        foreach($feeheader 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;
                    }
                 }
                 
                 $already_paid_feehead = \App\StudentTransactionDetail::where('idStudent', '=', $student->idStudent)
                                    ->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();
                        if($fee_transaction->fine > 0){
                            $headerObject['fine'] = $fee_transaction->fine;
                            $headerObject['amount'] = $headerObject['amount'] + $fee_transaction->fine;
                        }
                        $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;
                                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;
                            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['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);
                    array_push($feeheaders,$headerObject);
                }
        }

        $feePayment = array();
        foreach($feeheaders as $headers){
            if(str_contains($headers['feeheadName'], "Admission") && $headers['isPaid'] == "Due"){
                return [$headers];
            }else{
                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('paymentType') == 1){
                    array_push($feePayment,$headers);
                }else
                if(str_contains($headers['feeheadName'], "First Installment") && $request->get('paymentType') == 2 && $headers['isPaid'] == "Due"){
                    array_push($feePayment,$headers);
                }/*else if(str_contains($headers['feeheadName'], "Second Installment") && $request->get('paymentType') == 2 && $headers['isPaid'] == "Due"){
                    array_push($feePayment,$headers);
                }*/
            }
        }

        foreach($feeheaders as $headers){
            if(str_contains($headers['feeheadName'], "P1")  && $request->get('paymentType') == 2 && $headers['isPaid'] == "Due"){
                $headers['isForceCheck'] = true;
                array_push($feePayment,$headers);
                return $feePayment;
            }else if(str_contains($headers['feeheadName'], "P1")  && $request->get('paymentType') == 1 && $headers['isPaid'] == "Due"){
                $headers['isForceCheck'] = true;
                array_push($feePayment,$headers);
                return $feePayment;
            }else if(str_contains($headers['feeheadName'], "P2")  && $request->get('paymentType') == 2 && $headers['isPaid'] == "Due"){
                $headers['isForceCheck'] = true;
                array_push($feePayment,$headers);
                return $feePayment;
            }else if(str_contains($headers['feeheadName'], "P2")  && $request->get('paymentType') == 1 && $headers['isPaid'] == "Due"){
                $headers['isForceCheck'] = true;
                array_push($feePayment,$headers);
                return $feePayment;
            }
        }

        return $feeheaders;
    }









    static function calculateBusFee($student, Request $request,$stdtransport)
    {
        $summary = [
            "feeTotal" => 0,
            "discount" => 0,
            "fine" => 0,
            "additional" => 0,
            "penaltyAmt" => 0,
            "paidFine" => 0,
            "totalAmount" => 0,
            "balance" => 0,
            "paidfees" => 0
        ];
        //default plan
        $currentPlan = 'Plan A';
        if ($request->get('paymode') != '') {
            $currentPlan = $request->get('paymode');
        }
        $plan = \App\BusTransactionDetail::join('bus_transaction', 'bus_transaction_details.idBusTransaction', '=', 'bus_transaction.idBusTransaction')
            ->join('busfeeheads', 'bus_transaction_details.idBusFeehead', '=', 'busfeeheads.idBusFeehead')
            ->where(function($query) {
                $query->whereNull('bus_transaction.status');
                $query->orWhere('bus_transaction.status', '=', 'Cleared');
                $query->orWhere('bus_transaction.status', '=', 'In-Process');
                $query->orWhere('bus_transaction.status', '=', 'Success');
            })
            ->where('bus_transaction_details.idStudent', $student->idStudent)->first();
        if ($plan != null) {
            $currentPlan = $plan->feeheadLabel;
        } else {
            //lesser details
            $lessPlan = \App\BusLesserTransactionDetail::join('bus_lesser_transaction', 'bus_lesser_transaction.idBusLesserTransaction', '=', 'bus_lesser_transaction.idBusLesserTransaction')
                ->join('busfeeheads', 'bus_lesser_transaction_details.idBusFeehead', '=', 'busfeeheads.idBusFeehead')
                ->where(function($query) {
                    $query->whereNull('bus_lesser_transaction.status');
                    $query->orWhere('bus_lesser_transaction.status', '=', 'Cleared');
                    $query->orWhere('bus_lesser_transaction.status', '=', 'In-Process');
                    $query->orWhere('bus_lesser_transaction.status', '=', 'Success');
                })
                ->where('bus_lesser_transaction_details.idStudent', $student->idStudent)->first();
            if ($lessPlan != null) {
                $currentPlan = $lessPlan->feeheadLabel;
            }
        }

        $feeheads = \DB::table('busfeeheads')->where('idStop', '=', $stdtransport->idStop)
            ->where('idRoute', '=', $stdtransport->idRoute)
            ->where('feeheadLabel', 'LIKE', $currentPlan . '%')
            ->orderBy('toDate')
            ->get()->toArray();


        $feeheaders=array();
        $m=0;
        foreach($feeheads as $feehead){
            $headerObject = (array)$feehead;
            $startDate = Carbon::parse($headerObject['fromDate']);
            $now = Carbon::now();
            $dueDiff = $startDate->diffInDays($now, false);
            $headerObject['isEnabled'] = ($dueDiff > -1);

            $discountfees = DB::table('busfee_discounts')->where('idStudent', $student->idStudent)->where('idBusFeehead',$headerObject['idBusFeehead'])->where('isActive', 'Y')->get();
            $headerObject['total_amount'] = $headerObject['amount'];
            //check discount
            $headerObject['discount'] = 0;
            foreach($discountfees as $items){
                $headerObject['discount'] = $headerObject['discount'] + $items->amount;
                $headerObject['total_amount'] = $headerObject['total_amount']  - $items->amount;
            }
            //check fine added to this account
            $headerObject['fine'] = self::calculateBusFine($headerObject, $student);
            $headerObject['total_amount'] = $headerObject['total_amount'] + $headerObject['fine'];

            //check paid amount,discount,fine
            $headerObject['transaction'] = self::fetchBusTransaction($headerObject['idBusFeehead'],$student);
            if($headerObject['isEnabled'] == false)
                {
                    $headerObject['isPaid'] = "Upcoming";
                    $headerObject['status'] = "Upcoming";
                }
            else {
                $headerObject['isPaid'] = "Due";
                $headerObject['status'] = "Due";
            }

            if($headerObject['total_amount'] > $headerObject['transaction']['paid'])
            {
                $headerObject['extra_amount'] =  0;
                $headerObject['balance'] = $headerObject['total_amount'] - $headerObject['transaction']['paid'];
                if($headerObject['transaction']['paid'] > 0){
                    $m--;
                    if($headerObject['transaction']['paid'] + $headerObject['transaction']['paid_fine'] == $headerObject['total_amount']){
                        $headerObject['balance'] = 0;
                        $headerObject['isPaid'] = "Paid";
                        $headerObject['status'] = "Paid";
                    }else{
                        $m++;
                        $headerObject['isPaid'] = "Partial Paid";
                        $headerObject['status'] = "Partial Paid";
                    }
                }else{
                    if(($startDate->diffInDays($now,false)) > 0)
                    {
                        $headerObject['isPaid'] = "Upcoming";
                        $headerObject['status'] = "Upcoming";
                    }
                }
            }
            else {
                $m--;
                $headerObject['balance'] = 0;
                $headerObject['isPaid'] = "Paid";
                $headerObject['status'] = "Paid";
                $headerObject['extra_amount'] = $headerObject['transaction']['paid'] - $headerObject['total_amount'];
            }
            $headerObject['isEnabled'] = true;
            $m++;
            if($headerObject['isEnabled'] == true){
                if($m > 1){
                    $headerObject['isEnabled'] = false;
                }else $headerObject['isEnabled'] = true;
            }
            array_push($feeheaders,$headerObject);
        }
        return $feeheaders;
    }

    static function calculateBusFine($headerObject, $student){
        $date = Carbon::parse($headerObject['toDate']);
        $fullPaid = \App\BusTransactionDetail::select('bus_transaction.paymentDate')->join('bus_transaction', 'bus_transaction_details.idBusTransaction', '=', 'bus_transaction.idBusTransaction')
        ->where('bus_transaction_details.idBusFeehead',$headerObject['idBusFeehead'])
        ->where('bus_transaction_details.idStudent', $student->idStudent)
        ->where(function($query) {
            $query->whereNull('bus_transaction.status');
            $query->orWhere('bus_transaction.status', '=', 'Cleared');
            $query->orWhere('bus_transaction.status', '=', 'In-Process');
            $query->orWhere('bus_transaction.status', '=', 'Success');
        })->orderBy('bus_transaction.idBusTransaction','DESC')->first();
        if($fullPaid != null){
            $now = Carbon::parse($fullPaid->paymentDate);
            return self::calculateBusFineResult($headerObject,$now,$date);
        }else{
            $lessPaid = \App\BusLesserTransactionDetail::select('bus_lesser_transaction.paymentDate')->join('bus_lesser_transaction', 'bus_lesser_transaction_details.idBusLesserTransaction', '=', 'bus_lesser_transaction.idBusLesserTransaction')
                ->where('bus_lesser_transaction_details.idStudent', $student->idStudent)
                ->where('bus_lesser_transaction_details.idBusFeehead', '=', $headerObject['idBusFeehead'])
                ->select('bus_lesser_transaction.paymentDate')->where(function ($query) {
                    $query->whereNull('bus_lesser_transaction.status');
                    $query->orWhere('bus_lesser_transaction.status', '=', 'Cleared');
                    $query->orWhere('bus_lesser_transaction.status', '=', 'In-Process');
                    $query->orWhere('bus_lesser_transaction.status', '=', 'Success');
                })->orderBy('bus_lesser_transaction.idBusLesserTransaction', 'DESC')->first();
            if($lessPaid != null){
                $now = Carbon::parse($lessPaid->paymentDate);
                return self::calculateBusFineResult($headerObject,$now,$date);
            }else{
                $now = Carbon::now();
                if (array_key_exists('paymentDate', $headerObject)) {
                    $now = Carbon::parse($headerObject['paymentDate']);
                }
                return self::calculateBusFineResult($headerObject,$now,$date);
            }
        }
    }

    static function calculateBusFineResult($headerObject,$now,$date){
        $diff = $date->diffInDays($now, false);
        if( $diff > 0){
            if($headerObject['fine'] == "0.00"){
                if($now->format('M') != $date->format('M')){
                    $now->addMonth();
                    $months = $now->diffInMonths($date);
                    return ($headerObject['flatFine'] * $months);
                }else{
                    return $headerObject['flatFine'];
                }
            }else{
                return $headerObject['fine'];
            }
        }
    }

    static function fetchBusTransaction($idHeader,$student){
        $result = [];
        $partial_paid = DB::table('bus_lesser_transaction')
            ->join('bus_lesser_transaction_details', 'bus_lesser_transaction.idBusLesserTransaction', '=', 'bus_lesser_transaction_details.idBusLesserTransaction')
            ->where('bus_lesser_transaction.idStudent', '=', $student->idStudent)
            ->where('bus_lesser_transaction.idFinancialYear', '=', $student->idFinancialYear)
            ->where('idBusFeehead', $idHeader)
            ->where(function ($query) {
                $query->whereNull('bus_lesser_transaction.status');
                $query->orWhere('bus_lesser_transaction.status', '=', 'Cleared');
                $query->orWhere('bus_lesser_transaction.status', '=', 'In-Process');
                $query->orWhere('bus_lesser_transaction.status', '=', 'Success');
            })
            ->select(DB::raw('SUM(totalPaid) as totalPaid'), DB::raw('SUM(bus_lesser_transaction_details.fine) as fine'), DB::raw('SUM(bus_lesser_transaction_details.discount) as discount'))
            ->first();
        if(isset($partial_paid->totalPaid)){
            $result['paid'] = $partial_paid->totalPaid;
            $result['redeem_discount'] = $partial_paid->discount;
            $result['paid_fine'] = $partial_paid->fine;
        }else{
            $already_paid_feehead = \App\BusTransactionDetail::join('bus_transaction', 'bus_transaction_details.idBusTransaction', '=', 'bus_transaction.idBusTransaction')
            ->where('bus_transaction.idStudent', '=', $student->idStudent)
            ->where('bus_transaction.idFinancialYear', '=', $student->idFinancialYear)
            ->where('idBusFeehead', $idHeader)
            ->where(function($query) {
                $query->whereNull('bus_transaction.status');
                $query->orWhere('bus_transaction.status', '=', 'In-Process');
                $query->orWhere('bus_transaction.status', '=', 'Cleared');
                $query->orWhere('bus_transaction.status', '=', 'Success');
            })->select(DB::raw('bus_transaction_details.amountPaid as amountPaid'),DB::raw('bus_transaction_details.discount as discount'),DB::raw('bus_transaction_details.fine as fine'))
            ->first();
            if(isset($already_paid_feehead->amountPaid)){
                $result['paid'] = $already_paid_feehead->amountPaid;
                $result['redeem_discount'] = $already_paid_feehead->discount;
                $result['paid_fine'] = $already_paid_feehead->fine;
            }else{
                $result['paid'] = 0.00;
                $result['redeem_discount'] = 0.00;
                $result['paid_fine'] = 0.00;
            }
        }   
        
        return $result;
    }

    static function getBusReportAmount($student,$idTransaction,$idLessTransaction,$paymentDate,$stdtransport)
    {
        $result = [];
        //default plan
        $currentPlan = 'Plan A';
        $plan = \App\BusTransactionDetail::join('bus_transaction', 'bus_transaction_details.idBusTransaction', '=', 'bus_transaction.idBusTransaction')
            ->join('busfeeheads', 'bus_transaction_details.idBusFeehead', '=', 'busfeeheads.idBusFeehead')
            ->where(function($query) {
                $query->whereNull('bus_transaction.status');
                $query->orWhere('bus_transaction.status', '=', 'Cleared');
                $query->orWhere('bus_transaction.status', '=', 'In-Process');
                $query->orWhere('bus_transaction.status', '=', 'Success');
            })
            ->where('bus_transaction_details.idStudent', $student->idStudent)->first();
        if ($plan != null) {
            $currentPlan = $plan->feeheadLabel;
        } else {
            //lesser details
            $lessPlan = \App\BusLesserTransactionDetail::join('bus_lesser_transaction', 'bus_lesser_transaction_details.idBusLesserTransaction', '=', 'bus_lesser_transaction.idBusLesserTransaction')
                ->join('busfeeheads', 'bus_lesser_transaction_details.idBusFeehead', '=', 'busfeeheads.idBusFeehead')
                ->where(function($query) {
                    $query->whereNull('bus_lesser_transaction.status');
                    $query->orWhere('bus_lesser_transaction.status', '=', 'Cleared');
                    $query->orWhere('bus_lesser_transaction.status', '=', 'In-Process');
                    $query->orWhere('bus_lesser_transaction.status', '=', 'Success');
                })
                ->where('bus_lesser_transaction_details.idStudent', $student->idStudent)->first();
            if ($lessPlan != null) {
                $currentPlan = $lessPlan->feeheadLabel;
            }
        }

        $feeheads = \DB::table('busfeeheads')->where('idStop', '=', $stdtransport->idStop)
            ->where('idRoute', '=', $stdtransport->idRoute)
            ->where('feeheadLabel', 'LIKE', $currentPlan . '%')
            ->orderBy('idBusFeehead', 'ASC')
            ->orderBy('toDate')
            ->get()->toArray();


        $feeheaders=array();
        $result['balance'] = 0;
        $result['fee'] = 0;
        $result['total_amount'] = 0;
        $result['fine'] = 0;
        $result['finePaid'] = 0;
        $result['feePaid'] = 0;
        $result['discount'] = 0;
        foreach($feeheads as $feehead){
            $headerObject = (array)$feehead;
            $startDate = Carbon::parse($headerObject['fromDate']);
            $now = Carbon::now();
            $dueDiff = $startDate->diffInDays($now, false);
            $headerObject['isEnabled'] = ($dueDiff > -1);

            $discountfees = DB::table('busfee_discounts')->where('idStudent', $student->idStudent)->where('idBusFeehead',$headerObject['idBusFeehead'])->where('isActive', 'Y')->get();
            $headerObject['total_amount'] = $headerObject['amount'];
            //check discount
            $headerObject['discount'] = 0;
            foreach($discountfees as $items){
                $headerObject['discount'] = $headerObject['discount'] + $items->amount;
                $headerObject['total_amount'] = $headerObject['total_amount']  - $items->amount;
            }
            //check fine added to this account
            $headerObject['fine'] = self::calculateBusFine($headerObject, $student);
            $headerObject['total_amount'] = $headerObject['total_amount'] + $headerObject['fine'];
            //check paid amount,discount,fine
            $headerObject['transaction'] = self::fetchBusReportTransaction($headerObject['idBusFeehead'],$student,$idTransaction,$idLessTransaction,$paymentDate);
            if($headerObject['total_amount'] > $headerObject['transaction']['paid'])
            {
                $headerObject['balance'] = $headerObject['total_amount'] - $headerObject['transaction']['paid'];
            }
            else {
                $headerObject['balance'] = 0;
            }
            $result['balance'] += $headerObject['balance'];
            $result['fee'] += $headerObject['amount'];
            $result['total_amount'] += $headerObject['total_amount'];
            $result['fine'] += $headerObject['fine'];
            $result['feePaid'] += $headerObject['transaction']['paid'];
            $result['finePaid'] += $headerObject['transaction']['paid_fine'];
            $result['discount'] +=$headerObject['discount'];
        }
        return $result;
    }

    static function fetchBusReportTransaction($idHeader,$student,$idTransaction,$idLessTransaction,$paymentDate){
        $result = [];
        $partial_paid = DB::table('bus_lesser_transaction')
            ->join('bus_lesser_transaction_details', 'bus_lesser_transaction_details.idBusLesserTransaction', '=', 'bus_lesser_transaction.idBusLesserTransaction')
            ->where('bus_lesser_transaction.idStudent', '=', $student->idStudent)
            ->where('bus_lesser_transaction.idFinancialYear', '=', $student->idFinancialYear)
            ->where('idBusFeehead', $idHeader);

         if($idLessTransaction != "")   
            $partial_paid = $partial_paid->where('bus_lesser_transaction.idBusLesserTransaction','<=',$idLessTransaction);
         else $partial_paid = $partial_paid->whereDate('bus_lesser_transaction.paymentDate','<=', Carbon::parse($paymentDate)->format('Y-m-d'));
         $partial_paid = $partial_paid->where(function ($query) {
                $query->whereNull('bus_lesser_transaction.status');
                $query->orWhere('bus_lesser_transaction.status', '=', 'Cleared');
                $query->orWhere('bus_lesser_transaction.status', '=', 'In-Process');
                $query->orWhere('bus_lesser_transaction.status', '=', 'Success');
            })
            ->select(DB::raw('SUM(totalPaid) as totalPaid'), DB::raw('SUM(bus_lesser_transaction_details.fine) as fine'), DB::raw('SUM(bus_lesser_transaction_details.discount) as discount'))
            ->first();
        if(isset($partial_paid->totalPaid)){
            $result['paid'] = $partial_paid->totalPaid;
            $result['redeem_discount'] = $partial_paid->discount;
            $result['paid_fine'] = $partial_paid->fine;
        }else{
            $already_paid_feehead = \App\BusTransactionDetail::join('bus_transaction', 'bus_transaction_details.idBusTransaction', '=', 'bus_transaction.idBusTransaction')
            ->where('bus_transaction.idStudent', '=', $student->idStudent)
            ->where('bus_transaction.idFinancialYear', '=', $student->idFinancialYear)
            ->where('idBusFeehead', $idHeader);
            if($idTransaction != "")   
            $already_paid_feehead = $already_paid_feehead->where('bus_transaction.idBusTransaction','<=',$idTransaction);
            else $already_paid_feehead = $already_paid_feehead->whereDate('bus_transaction.paymentDate','<=', Carbon::parse($paymentDate)->format('Y-m-d'));
            $already_paid_feehead = $already_paid_feehead->where(function($query) {
                $query->whereNull('bus_transaction.status');
                $query->orWhere('bus_transaction.status', '=', 'In-Process');
                $query->orWhere('bus_transaction.status', '=', 'Cleared');
                $query->orWhere('bus_transaction.status', '=', 'Success');
            })->select(DB::raw('bus_transaction_details.amountPaid as amountPaid'),DB::raw('bus_transaction_details.discount as discount'),DB::raw('bus_transaction_details.fine as fine'))
            ->first();
            if(isset($already_paid_feehead->amountPaid)){
                $result['paid'] = $already_paid_feehead->amountPaid;
                $result['redeem_discount'] = $already_paid_feehead->discount;
                $result['paid_fine'] = $already_paid_feehead->fine;
            }else{
                $result['paid'] = 0.00;
                $result['redeem_discount'] = 0.00;
                $result['paid_fine'] = 0.00;
            }
        }   
        
        return $result;
    }

    static function getBusReportDueAmount($stdtransport)
    {
        $result = [];
        //default plan
        $currentPlan = 'Plan A';
        $plan = \App\BusTransactionDetail::join('bus_transaction', 'bus_transaction_details.idBusTransaction', '=', 'bus_transaction.idBusTransaction')
            ->join('busfeeheads', 'bus_transaction_details.idBusFeehead', '=', 'busfeeheads.idBusFeehead')
            ->where(function($query) {
                $query->whereNull('bus_transaction.status');
                $query->orWhere('bus_transaction.status', '=', 'Cleared');
                $query->orWhere('bus_transaction.status', '=', 'In-Process');
                $query->orWhere('bus_transaction.status', '=', 'Success');
            })
            ->where('bus_transaction_details.idStudent', $stdtransport->idStudent)->first();
        if ($plan != null) {
            $currentPlan = $plan->feeheadLabel;
        } else {
            //lesser details
            $lessPlan = \App\BusLesserTransactionDetail::join('bus_lesser_transaction', 'bus_lesser_transaction_details.idBusLesserTransaction', '=', 'bus_lesser_transaction.idBusLesserTransaction')
                ->join('busfeeheads', 'bus_lesser_transaction_details.idBusFeehead', '=', 'busfeeheads.idBusFeehead')
                ->where(function($query) {
                    $query->whereNull('bus_lesser_transaction.status');
                    $query->orWhere('bus_lesser_transaction.status', '=', 'Cleared');
                    $query->orWhere('bus_lesser_transaction.status', '=', 'In-Process');
                    $query->orWhere('bus_lesser_transaction.status', '=', 'Success');
                })
                ->where('bus_lesser_transaction_details.idStudent', $stdtransport->idStudent)->first();
            if ($lessPlan != null) {
                $currentPlan = $lessPlan->feeheadLabel;
            }
        }

        $feeheads = \DB::table('busfeeheads')->where('idStop', '=', $stdtransport->idStop)
            ->where('idRoute', '=', $stdtransport->idRoute)
            ->where('feeheadLabel', 'LIKE', $currentPlan . '%')
            ->orderBy('idBusFeehead', 'ASC')
            ->orderBy('toDate')
            ->get()->toArray();

        $feeheaders=array();
        $result['balance'] = 0;
        $result['fee'] = 0;
        $result['total_amount'] = 0;
        $result['fine'] = 0;
        $result['finePaid'] = 0;
        $result['feePaid'] = 0;
        $result['discount'] = 0;
        $result['discountPaid'] = 0;
        foreach($feeheads as $feehead){
            $headerObject = (array)$feehead;
            $startDate = Carbon::parse($headerObject['fromDate']);
            $now = Carbon::now();
            $dueDiff = $startDate->diffInDays($now, false);
            $headerObject['isEnabled'] = ($dueDiff > -1);

            $discountfees = DB::table('busfee_discounts')->where('idStudent', $stdtransport->idStudent)->where('idBusFeehead',$headerObject['idBusFeehead'])->where('isActive', 'Y')->get();
            $headerObject['total_amount'] = $headerObject['amount'];
            //check discount
            $headerObject['discount'] = 0;
            foreach($discountfees as $items){
                $headerObject['discount'] = $headerObject['discount'] + $items->amount;
                $headerObject['total_amount'] = $headerObject['total_amount']  - $items->amount;
            }
            //check fine added to this account
            $headerObject['fine'] = self::calculateBusFine($headerObject, $stdtransport);
            $headerObject['total_amount'] = $headerObject['total_amount'] + $headerObject['fine'];
            //check paid amount,discount,fine
            $headerObject['transaction'] = self::fetchBusTransaction($headerObject['idBusFeehead'],$stdtransport);
            if($headerObject['total_amount'] > $headerObject['transaction']['paid'])
            {
                $headerObject['balance'] = $headerObject['total_amount'] - $headerObject['transaction']['paid'];
                $result['feeheadName'] = $headerObject['feeheadName'];
            }
            else {
                $headerObject['balance'] = 0;
            }
            $result['balance'] += $headerObject['balance'];
            $result['fee'] += $headerObject['amount'];
            $result['total_amount'] += $headerObject['total_amount'];
            $result['fine'] += $headerObject['fine'];
            $result['feePaid'] += $headerObject['transaction']['paid'];
            $result['finePaid'] += $headerObject['transaction']['paid_fine'];
            $result['discountPaid'] += $headerObject['transaction']['redeem_discount'];
            $result['discount'] +=$headerObject['discount'];
        }
        return $result;
    }

}

Copyright © 2021 - 2025 IMMREX7