IMMREX7

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

<?php

namespace App\Http\Controllers\School;

use App\Http\PaymentCalculation;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
use DB;
use PDF;
use Carbon\Carbon;
use Session;

class StudentTransactionController extends SchoolController {

    public $total_amount = 0;

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request) {
         if (!request()->ajax()) {
            $students = [];
            /*$students = \App\AdmEntry::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                ->where('isActive', '=', 'Y')->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                ->selectRaw("idStudent, CONCAT(firstName, ' ', COALESCE(lastName,''),' ',ecNo) AS full_name")
                ->pluck('full_name','idStudent')->toArray();*/
            return view('schools.transaction.studentlist',compact('students'));
        }
        $columns = array(
            //   0 =>'sNo',
            0 => 'photo',
            1 => 'ecNo',
            2 => 'name',
            3 => 'father_name',
            4 => 'className',
            5 => 'sectionName',
            6 => 'mobile',
            7 => 'action',
        );
        $totalData = \App\AdmEntry::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                ->where('isActive', '=', 'Y');
        if ($request->idFinancialYear != null) {
            $totalData = $totalData->where('idFinancialYear', '=', $request->idFinancialYear)
                    ->count();
        } else {
            $totalData = $totalData->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                    ->count();
        }
        $totalFiltered = $totalData;
        $limit = $request->input('length');
        $start = $request->input('start');
        $order = $columns[$request->input('order.0.column')];
        $dir = $request->input('order.0.dir');


        // Get Data according to search value    
        if (empty($request->input('search.value'))) {
            if ($limit == '-1') {
                $students = DB::table('students')
                        ->join('classes', 'students.idClass', '=', 'classes.idClass')
                        ->join('sections', 'students.idSection', '=', 'sections.idSection')
                        ->orderBy($order, $dir)
                        ->where('isActive', '=', 'Y')
                        ->where('students.idSchool', '=', Auth::guard('school')->user()->idSchool);
            } else {
                $students = DB::table('students')
                        ->join('classes', 'students.idClass', '=', 'classes.idClass')
                        ->join('sections', 'students.idSection', '=', 'sections.idSection')
                        ->offset($start)
                        ->limit($limit)
                        ->orderBy($order, $dir)
                        ->where('isActive', '=', 'Y')
                        ->where('students.idSchool', '=', Auth::guard('school')->user()->idSchool);
            }
            if ($request->idFinancialYear != null) {
                $students = $students->where('students.idFinancialYear', '=', $request->idFinancialYear)->get();
            } else {
                $students = $students->where('students.idFinancialYear', '=', Session::get('idFinancialYear'))->get();
            }
        } else {
            $search = $request->input('search.value');
            if ($limit == '-1') {
                $students = DB::table('students')
                        ->join('classes', 'students.idClass', '=', 'classes.idClass')
                        ->join('sections', 'students.idSection', '=', 'sections.idSection')
                        ->orderBy($order, $dir)
                        ->where('isActive', '=', 'Y')
                        ->where('students.idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->where(function ($query) use ($search) {
                    $query->where(DB::raw('CONCAT(firstName, " ",lastName)'), 'LIKE', "%{$search}%")
                    ->orWhere('ecNo', 'LIKE', "%{$search}%")
                    ->orWhere('middleName', 'LIKE', "%{$search}%")
                    ->orWhere('firstName', 'LIKE', "{$search}%")
                    ->orWhere('lastName', 'LIKE', "{$search}%")
                    ->orWhere('className', 'LIKE', "%{$search}%")
                    ->orWhere('sectionName', 'LIKE', "%{$search}%")
                    ->orWhere('father_fname', 'LIKE', "%{$search}%")
                    ->orWhere('studentDob', 'LIKE', "%{$search}%")
                    ->orWhere('father_mobile', 'LIKE', "%{$search}%");
                });
            } else {
                $students = DB::table('students')
                        ->join('classes', 'students.idClass', '=', 'classes.idClass')
                        ->join('sections', 'students.idSection', '=', 'sections.idSection')
                        ->offset($start)
                        ->limit($limit)
                        ->orderBy($order, $dir)
                        ->where('isActive', '=', 'Y')
                        ->where('students.idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->where(function ($query) use ($search) {
                    $query->where(DB::raw('CONCAT(firstName, " ",lastName)'), 'LIKE', "%{$search}%")
                    ->orWhere('firstName', 'LIKE', "%{$search}%")
                    ->orWhere('lastName', 'LIKE', "%{$search}%")
                    ->orWhere('middleName', 'LIKE', "%{$search}%")
                    ->orWhere('ecNo', 'LIKE', "%{$search}%")
                    ->orWhere('className', 'LIKE', "%{$search}%")
                    ->orWhere('sectionName', 'LIKE', "%{$search}%")
                    ->orWhere('father_fname', 'LIKE', "%{$search}%")
                    ->orWhere('studentDob', 'LIKE', "%{$search}%")
                    ->orWhere('father_mobile', 'LIKE', "%{$search}%");
                });
            }
            $totalFiltered = DB::table('students')
                    ->join('classes', 'students.idClass', '=', 'classes.idClass')
                    ->join('sections', 'students.idSection', '=', 'sections.idSection')
                    ->where('isActive', '=', 'Y')
                    ->where('students.idSchool', '=', Auth::guard('school')->user()->idSchool)
                    ->where(function ($query) use ($search) {
                $query->where(DB::raw('CONCAT(firstName, " ",lastName)'), 'LIKE', "%{$search}%")
                ->orWhere('firstName', 'LIKE', "%{$search}%")
                ->orWhere('lastName', 'LIKE', "%{$search}%")
                ->orWhere('middleName', 'LIKE', "%{$search}%")
                ->orWhere('ecNo', 'LIKE', "%{$search}%")
                ->orWhere('className', 'LIKE', "%{$search}%")
                ->orWhere('sectionName', 'LIKE', "%{$search}%")
                ->orWhere('father_fname', 'LIKE', "%{$search}%")
                ->orWhere('studentDob', 'LIKE', "%{$search}%")
                ->orWhere('father_mobile', 'LIKE', "%{$search}%");
            });
            if ($request->idFinancialYear != null) {
                $students = $students->where('students.idFinancialYear', '=', $request->idFinancialYear)->get();
                $totalFiltered = $totalFiltered->where('students.idFinancialYear', '=', $request->idFinancialYear)->get()->count();
            } else {
                $students = $students->where('students.idFinancialYear', '=', Session::get('idFinancialYear'))->get();
                $totalFiltered = $totalFiltered->where('students.idFinancialYear', '=', Session::get('idFinancialYear'))->get()->count();
            }
        }
        $data = array();
        if (!empty($students)) {
            $count = 1;
            foreach ($students as $var) {
//                $nestedData['sNo'] = $count;
                $nestedData['photo'] = '<img src="https://online-login.online/storage/schools/' . $var->idSchool . '/students/' . $var->photo . '" height="60">';
                $nestedData['ecNo'] = $var->ecNo;
                $nestedData['name'] = $var->firstName . " " . $var->middleName . " " . $var->lastName;
                $nestedData['father_name'] = $var->father_fname . " " . $var->father_lname;
                $nestedData['className'] = $var->className;
                $nestedData['sectionName'] = $var->sectionName;
                $nestedData['father_mobile'] = $var->father_mobile;
                if(Auth::guard('school')->user()->idSchool == 25 || Auth::guard('school')->user()->idSchool == 86)
                $nestedData['action'] = '<a class="btn btn-warning btn-sm" href="https://online-login.online/school/stdfees/' . $var->idStudent . '/details" target="_blank">School Fees</a><a class="btn btn-warning btn-sm" href="https://online-login.online/school/stdfees-extra/' . $var->idStudent . '/details" target="_blank">Extra Fees</a>';
                else
                $nestedData['action'] = '<a class="btn btn-warning btn-sm" href="https://online-login.online/school/stdfees/' . $var->idStudent . '/details" target="_blank">Select</a>';
                $data[] = $nestedData;
//                $count++;
            }
        }
        $json_data = array(
            "draw" => intval($request->input('draw')),
            "recordsTotal" => intval($totalData),
            "recordsFiltered" => intval($totalFiltered),
            "data" => $data
        );

        $students = json_encode($json_data);
        return $students;

//        $students = \App\AdmEntry::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
//                ->get();
//        return view('schools.transaction.studentlist', compact('students'));
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request) {
        $rules = [];
        if ($request->paymentMode == 'Cash') {
            $rules += ['totalPaid' => 'required'];
        } else if ($request->paymentMode == 'Online') {
            $rules = [];
        } else if ($request->paymentMode == 'IMPS') {
            $rules = [];
        } else if ($request->paymentMode == 'Card') {
            $rules += ['cardNo' => 'required', 'totalPaid' => 'required'];
        } else {
            $rules += [
                'idBank' => 'required',
                'chequeDate' => 'required',
                'chequeNo' => 'required',
                'amount' => 'required'
            ];
        }
        $messages = [
            'cardNo.required' => 'Card No or Trans ID field is required',
            'totalPaid.required' => 'Enter The Amount.',
            'idBank.required' => 'Bank must be selected',
            'chequeDate.required' => 'Cheque / DD Date must be filled.',
            'chequeNo.required' => 'Cheque / DD No. must be filled.'
        ];
        $this->validate($request, $rules, $messages);

        $penaltyAmount = 0;
        $total_paid = 0;
        $isSuccessful = 0;
        $excessAmount = 0;
        if ($request->paymentMode == 'Cash' || $request->paymentMode == 'Card' || $request->paymentMode == 'Online' || $request->paymentMode == 'IMPS') {
            $total_paid = $request->totalPaid;
        } else {
            $total_paid = $request->amount;
        }

        $payableAmount = $request->payable;
        //Check Bounce fine
        $chqbounce = \App\StudentTransaction::where('idStudent', '=', $request->idStudent)
                ->where('idFinancialYear', '=', $request->idFinancialYear)
                ->where('status', '=', 'Bounced')
                ->where('chqFineStatus', '=', '0')
                ->get();
        if (isset($chqbounce)) {
            foreach ($chqbounce as $chqFine)
                $penaltyAmount = $penaltyAmount + $chqFine->chequeBounceCharge;
        }

        //Check if excess amount exists
        $student_transaction = DB::table('student_transaction')
                        ->select('idTransaction')
                        ->where('idStudent', '=', $request->idStudent)
                        ->where('idFinancialYear', '=', $request->idFinancialYear)
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })
                        ->get()->toArray();
        $excessIds = array();
        foreach ($student_transaction as $transaction)
            array_push($excessIds, $transaction->idTransaction);
        $excess_transaction = DB::table('excess_transaction')
                        ->whereIn('idTransaction', $excessIds)
                        ->where('isActive', '=', 'Y')
                        ->orderBy('idTransaction', 'desc')->first();


        if ((count($request->selectedHeaders) == '1') && $total_paid < $payableAmount) {
            $isSuccessful = $this->storeLesserTransaction($request, $penaltyAmount, $excess_transaction);
        } else {
            $lesser_transaction = DB::table('lesser_transaction')
                    ->join('lesser_transaction_details', 'lesser_transaction_details.idLesserTransaction', '=', 'lesser_transaction.idLesserTransaction')
                    ->where('lesser_transaction.idStudent', '=', $request->idStudent)
                    ->where('lesser_transaction.idFinancialYear', '=', $request->idFinancialYear)
                    ->whereIn('idFeehead', $request->selectedHeaders)
                    ->where(function($query) {
                        $query->whereNull('lesser_transaction.status');
                        $query->orWhere('lesser_transaction.status', '=', 'Cleared');
                        $query->orWhere('lesser_transaction.status', '=', 'In-Process');
                        $query->orWhere('lesser_transaction.status', '=', 'Success');
                    })
                    ->select(DB::raw('SUM(totalPaid) as totalPaid'))
                    ->first();
            if ((count($request->selectedHeaders) == '1') && $total_paid == $payableAmount && $lesser_transaction->totalPaid > 0) {

                $isSuccessful = $this->storeLesserTransaction($request, $penaltyAmount, $excess_transaction);
            } else if ($lesser_transaction->totalPaid > 0) {
                flash('Fees cannot been submitted because one selected header belongs to lesser transaction !!');
                if ($request->ajax()) {
                    return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
                }
            } else {
                $isSuccessful = $this->storeSuccessTransaction($request, $penaltyAmount, $excess_transaction);
            }
        }

        if ($isSuccessful == 1) {

            if (isset($chqbounce)) {
                foreach ($chqbounce as $chqFine) {
                    $chqFine->chqFineStatus = 1;
                    $chqFine->update();
                }
            }

            if ($excess_transaction) {
                $this->addAccessTransaction($excess_transaction->excessAmount, $excess_transaction->idExcessTransaction, 1, 0);
            }

            flash('Fees has been submitted successfully!!');
            if ($request->ajax()) {
                return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
            }
        } else {

            flash('Fees has not been submitted successfully!!');
            if ($request->ajax()) {
                return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
            }
        }

        return redirect()->back();
    }

    public function storeLesserTransaction(Request $request, $penaltyAmount, $excess_transaction) {
        $stdtransaction = new \App\LesserTransaction();
        $stdtransaction->fill($request->all());
        if ($request->has('paymentDate') && $request->paymentDate != null) {
            $stdtransaction->paymentDate = $request->paymentDate;
        } else {
            $stdtransaction->paymentDate = today_date();
        }

        if($request->has('remarks')){
            $stdtransaction->remarks = $request->remarks;
        }

        if($request->has('additionalAmount')){
            if($request->additionalAmount != null)
            $stdtransaction->additionalAmount = $request->additionalAmount;
        }

        if ($request->paymentMode == 'Cash' || $request->paymentMode == 'Card' || $request->paymentMode == 'Online' || $request->paymentMode == 'IMPS') {

            if ($excess_transaction) {
                $stdtransaction->totalPaid = $request->totalPaid + $excess_transaction->excessAmount;
                $request->totalPaid = $stdtransaction->totalPaid;
                $stdtransaction->excessAmountUsed = $excess_transaction->excessAmount;
                $stdtransaction->idExcessTransaction = $excess_transaction->idExcessTransaction;
            } else
                $stdtransaction->totalPaid = $request->totalPaid;
        } else {
            if ($excess_transaction) {
                $stdtransaction->totalPaid = $request->amount +
                        $excess_transaction->excessAmount;
                $request->totalPaid = $stdtransaction->totalPaid;
                $stdtransaction->excessAmountUsed = $excess_transaction->excessAmount;
                $stdtransaction->idExcessTransaction = $excess_transaction->idExcessTransaction;
            } else
                {
                    $stdtransaction->totalPaid = $request->amount;
                    if($request->has('additionalAmount')){
                        if($request->additionalAmount != null)
                        {
                            $stdtransaction->totalPaid = $request->amount - $request->additionalAmount;
                        }
                    }
                }

            $stdtransaction->status = 'In-Process';
        }

        $next_receiptno = next_receiptno();
        $stdtransaction->receiptNo = 'SFP000' . $next_receiptno;
        $stdtransaction->idSchool = Auth::guard('school')->user()->idSchool;
        $stdtransaction->penaltyAmount = $penaltyAmount;
        $stdtransaction->fine = 0;
        $stdtransaction->discount = 0;
        $stdtransaction->created_by = Auth::guard('school')->user()->idSchoolUser;
        if(isset($request->outstanding)){
            $outstanding = DB::table('student_transaction_outstanding')->where('idOutstanding',$request->outstanding)->first();
            if($outstanding != null){
                $stdtransaction->idOutstanding = $request->outstanding;
                $stdtransaction->outstandingAmount = $outstanding->amount;
                DB::table('student_transaction_outstanding')->where('idOutstanding',$request->outstanding)->update(['isPaid' => 1]);
            }
        }
        $stdtransaction->save();

        foreach ($request->selectedHeaders as $key => $var) {
            if ($this->storeLesserDetailsTransaction($request, $stdtransaction->idLesserTransaction, $var) == 1)
                return 1;
        }

        return 0;
    }

    public function storeLesserDetailsTransaction(Request $request, $idLesserTransaction, $feeHeaderId) {
        $stepDiscount = 0;
        $stepFine = 0;
        $headerObject = \App\FeeHead::where('idFeehead', '=', $feeHeaderId)->first()->toArray();
        $date = Carbon::parse($headerObject['toDate']);
        if ($request->has('paymentDate') && $request->paymentDate != null) {
            $now = Carbon::parse($request->paymentDate);
        }else{
            $now = Carbon::now();
        }
        $diff = $date->diffInDays($now, false);

        if ($diff > 0) {
            if ($headerObject['fine'] != null && $headerObject['fine'] != 0.00) {
                $stepFine = ( $headerObject['fine'] * $diff);
            } else
            if ($headerObject['flatFine'] != null) {
                if(Auth::guard('school')->user()->idSchool == 25){
                    $student = \App\AdmEntry::where('idStudent', $request->idStudent)->first();
                    if ($request->has('paymentDate') && $request->paymentDate != null) {
                        $headerObject['paymentDate'] = $request->paymentDate;
                    }
                    $calculatedFine = PaymentCalculation::calculateFine($headerObject,$student);
                    $fetchFine = PaymentCalculation::fetchFineTransaction($headerObject['idFeehead'],$student);
                    if( $calculatedFine > $fetchFine)
                    $stepFine = $calculatedFine - $fetchFine;
                    else $stepFine = 0;
                }else
                $stepFine = $stepFine + $headerObject['flatFine'];
            }
        }



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

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

        if ($this->isLesserHeader($request, $idLesserTransaction, $feeHeaderId, $stepFine) == 0) {

            $stdtransaction_detail = new \App\LesserTransactionDetail();
            $stdtransaction_detail->idStudent = $request->idStudent;
            $stdtransaction_detail->idLesserTransaction = $idLesserTransaction;
            $stdtransaction_detail->idFeehead = $feeHeaderId;
            if ($request->has('paymentDate') && $request->paymentDate != null) {
                $stdtransaction_detail->paymentDate = $request->paymentDate;
            } else {
                $stdtransaction_detail->paymentDate = today_date();
            }
            if ($request->paymentMode == 'Cash' || $request->paymentMode == 'Card' || $request->paymentMode == 'Online' || $request->paymentMode == 'IMPS') {
                $stdtransaction_detail->amountPaid = $request->totalPaid;
            } else {
                $stdtransaction_detail->amountPaid = $request->amount;
                if($request->has('additionalAmount')){
                    if($request->additionalAmount != null)
                    {
                        $stdtransaction_detail->amountPaid = $request->amount - $request->additionalAmount;
                    }
                }
                $stdtransaction_detail->status = 'In-Process';
            }

            $stdtransaction_detail->fine = $stepFine;
            $stdtransaction_detail->discount = $stepDiscount;
            $stdtransaction_detail->created_by = Auth::guard('school')->user()->idSchoolUser;
            $stdtransaction_detail->save();
        }

        return 1;
    }

    public function isLesserHeader(Request $request, $idLesserTransaction, $feeHeaderID, $fine) {
        $lesser_transaction = DB::table('lesser_transaction')
                ->join('lesser_transaction_details', 'lesser_transaction_details.idLesserTransaction', '=', 'lesser_transaction.idLesserTransaction')
                ->where('lesser_transaction.idStudent', '=', $request->idStudent)
                ->where('lesser_transaction.idFinancialYear', '=', $request->idFinancialYear)
                ->whereIn('idFeehead', $request->selectedHeaders)
                ->where(function($query) {
                    $query->whereNull('lesser_transaction.status');
                    $query->orWhere('lesser_transaction.status', '=', 'Cleared');
                    $query->orWhere('lesser_transaction.status', '=', 'In-Process');
                    $query->orWhere('lesser_transaction.status', '=', 'Success');
                })
                ->select(DB::raw('SUM(totalPaid) as totalPaid'), DB::raw('SUM(lesser_transaction_details.fine) as fine'))
                ->first();
        if ($lesser_transaction->totalPaid > 0) {
            $stdtransaction_detail = new \App\LesserTransactionDetail();
            $stdtransaction_detail->idStudent = $request->idStudent;
            $stdtransaction_detail->idLesserTransaction = $idLesserTransaction;
            $stdtransaction_detail->idFeehead = $feeHeaderID;
            if ($request->has('paymentDate') && $request->paymentDate != null) {
                $stdtransaction_detail->paymentDate = $request->paymentDate;
            } else {
                $stdtransaction_detail->paymentDate = today_date();
            }
            if ($request->paymentMode == 'Cash' || $request->paymentMode == 'Card' || $request->paymentMode == 'Online' || $request->paymentMode == 'IMPS') {
                $stdtransaction_detail->amountPaid = $request->totalPaid;
            } else {
                $stdtransaction_detail->amountPaid = $request->amount;
                if($request->has('additionalAmount')){
                    if($request->additionalAmount != null)
                    {
                        $stdtransaction_detail->amountPaid = $request->amount - $request->additionalAmount;
                    }
                }
                $stdtransaction_detail->status = 'In-Process';
            }
            if ($lesser_transaction->fine == $fine)
                $stdtransaction_detail->fine = 0;
            else
                $stdtransaction_detail->fine = $fine;
            $stdtransaction_detail->created_by = Auth::guard('school')->user()->idSchoolUser;
            $stdtransaction_detail->discount = 0;
            $stdtransaction_detail->save();

            return 1;
        }else {
            return 0;
        }
    }

    //
    public function addAccessTransaction($excessAmount, $idTransaction, $flag, $isCheque) {
        if ($flag == 1) {
            $excess = \App\ExcessTransaction::where('idExcessTransaction', '=', $idTransaction)->first(); //idTransaction is the  idExcessTransaction in excess table
            $excess->isActive = 'N';
            $excess->update();
        } else {
            $excess = new \App\ExcessTransaction();
            $excess->idTransaction = $idTransaction;
            if ($isCheque == 1)
                $excess->isActive = 'P';
            $excess->created_by = Auth::guard('school')->user()->idSchoolUser;
            $excess->excessAmount = $excessAmount;
            $excess->save();
        }
    }

    public function storeSuccessTransaction(Request $request, $penaltyAmount, $excess_transaction) {
        $total_paid = 0;
        if ($request->paymentMode == 'Cash' || $request->paymentMode == 'Card' || $request->paymentMode == 'Online' || $request->paymentMode == 'IMPS') {
            $total_paid = $request->totalPaid;
        } else {
            $total_paid = $request->amount;
        }

        $excessAmount = $total_paid - $request->payable;
        $stdtransaction = new \App\StudentTransaction();
        $stdtransaction->fill($request->all());
        if ($request->has('paymentDate') && $request->paymentDate != null) {
            $stdtransaction->paymentDate = $request->paymentDate;
        } else {
            $stdtransaction->paymentDate = today_date();
        }

        if($request->has('remarks')){
            $stdtransaction->remarks = $request->remarks;
        }

        if($request->has('additionalAmount')){
            if($request->additionalAmount != null)
            $stdtransaction->additionalAmount = $request->additionalAmount;
        }

        if ($request->paymentMode == 'Cash' || $request->paymentMode == 'Card' || $request->paymentMode == 'Online' || $request->paymentMode == 'IMPS') {
            $stdtransaction->totalPaid = $total_paid;
        } else {
            $stdtransaction->totalPaid = $total_paid;
            if($request->has('additionalAmount')){
                if($request->additionalAmount != null)
                {
                    $stdtransaction->totalPaid = $total_paid - $request->additionalAmount;
                }
            }
            $stdtransaction->status = 'In-Process';
        }

        $next_receiptno = next_receiptno();
        $stdtransaction->receiptNo = 'SFP000' . $next_receiptno;
        $stdtransaction->idSchool = Auth::guard('school')->user()->idSchool;
        $stdtransaction->penaltyAmount = $penaltyAmount;
        $stdtransaction->fine = 0;
        $stdtransaction->discount = 0;
        if ($excess_transaction) {
            $stdtransaction->excessAmountUsed = $excess_transaction->excessAmount;
            $stdtransaction->idExcessTransaction = $excess_transaction->idExcessTransaction;
        }

        if(isset($request->outstanding)){
            $outstanding = DB::table('student_transaction_outstanding')->where('idOutstanding',$request->outstanding)->first();
            if($outstanding != null){
                $stdtransaction->idOutstanding = $request->outstanding;
                $stdtransaction->outstandingAmount = $outstanding->amount;
                DB::table('student_transaction_outstanding')->where('idOutstanding',$request->outstanding)->update(['isPaid' => 1]);
            }
        }

        $stdtransaction->created_by = Auth::guard('school')->user()->idSchoolUser;
        $stdtransaction->save();

        if ($excessAmount > 0) {
            if ($request->paymentMode == 'Cheque')
                $this->addAccessTransaction($excessAmount, $stdtransaction->idTransaction, 0, 1);
            else
                $this->addAccessTransaction($excessAmount, $stdtransaction->idTransaction, 0, 0);
        }

        return $this->storeDetailsTransaction($request, $stdtransaction, $excess_transaction);
    }

    public function storeDetailsTransaction(Request $request, $stdtransaction, $excess_transaction) {
        $totalFine = 0;
        $totalAmount = 0;
        $totalDiscount = 0;
        foreach ($request->selectedHeaders as $key => $var) {
            $stepFine = 0;
            $stepDiscount = 0;
            $stepAmount = 0;

            $headerObject = \App\FeeHead::where('idFeehead', '=', $var)->first()->toArray();
            $date = Carbon::parse($headerObject['toDate']);
            if ($request->has('paymentDate') && $request->paymentDate != null) {
                $now = Carbon::parse($request->paymentDate);
            }else{
                $now = Carbon::now();
            }
            $diff = $date->diffInDays($now, false);
            if ($diff > 0) {
                if ($headerObject['fine'] != null && $headerObject['fine'] != 0.00) {
                    $stepFine = ( $headerObject['fine'] * $diff);
                } else
                if ($headerObject['flatFine'] != null) {
                    if(Auth::guard('school')->user()->idSchool == 25){
                        if($now->format('M') != $date->format('M')){
                            $now->addMonth();
                            $months = $now->diffInMonths($date);
                            if($months > 0){
                                $stepFine = $stepFine + ($headerObject['flatFine'] * $months);
                            }else
                            $stepFine = $stepFine + $headerObject['flatFine'];
                        }else  $stepFine = $stepFine + $headerObject['flatFine'];
                    }else
                    $stepFine = $stepFine + $headerObject['flatFine'];
                }
            }

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

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


            $stepAmount = ( $headerObject['amount'] + $stepFine );
            $stepAmount = $stepAmount - $stepDiscount;

            $stdtransaction_detail = new \App\StudentTransactionDetail();
            $stdtransaction_detail->created_by = Auth::guard('school')->user()->idSchoolUser;
            $stdtransaction_detail->idStudent = $request->idStudent;
            $stdtransaction_detail->idTransaction = $stdtransaction->idTransaction;
            $stdtransaction_detail->idFeehead = $var;
            if ($request->has('paymentDate') && $request->paymentDate != null) {
                $stdtransaction_detail->paymentDate = $request->paymentDate;
            } else {
                $stdtransaction_detail->paymentDate = today_date();
            }

            $stdtransaction_detail->amountPaid = $stepAmount;
            $stdtransaction_detail->fine = $stepFine;
            $stdtransaction_detail->discount = $stepDiscount;

            if ($request->paymentMode == 'Cheque' || $request->paymentMode == 'DD') {
                $stdtransaction_detail->status = 'In-Process';
            }

            if($stdtransaction->penaltyAmount > 0){
                $stdtransaction_detail->chqPenalty = $stdtransaction->penaltyAmount;
            }

            $stdtransaction_detail->save();

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

        $stdtransaction->totalPaid = $totalAmount;
        $stdtransaction->discount = $totalDiscount;
        $stdtransaction->fine = $totalFine;


        if ($request->payable == 0) {
            $excessAmount = $excess_transaction->excessAmount - $totalAmount;
            if ($excessAmount > 0) {
                $this->addAccessTransaction($excessAmount, $stdtransaction->idTransaction, 0, 0);
            }
            $stdtransaction->excessAmountUsed = $totalAmount;
            $stdtransaction->idExcessTransaction = $excess_transaction->idExcessTransaction;
        }

        $stdtransaction->update();

        return 1;
    }

    public function addZeroAmountTransaction(Request $request, $penaltyAmount, $excess_transaction) {
        $total_paid = 0;
        if ($request->paymentMode == 'Cash' || $request->paymentMode == 'Card' || $request->paymentMode == 'Online' || $request->paymentMode == 'IMPS') {
            $total_paid = $request->totalPaid;
        } else {
            $total_paid = $request->amount;
        }

        if ($excess_transaction) {
            $total_paid = $excess_transaction->excessAmount;
        }


        $stdtransaction = new \App\StudentTransaction();
        $stdtransaction->fill($request->all());
        if ($request->has('paymentDate') && $request->paymentDate != null) {
            $stdtransaction->paymentDate = $request->paymentDate;
        } else {
            $stdtransaction->paymentDate = today_date();
        }

        if($request->has('remarks')){
            $stdtransaction->remarks = $request->remarks;
        }

        if($request->has('additionalAmount')){
            if($request->additionalAmount != null)
            $stdtransaction->additionalAmount = $request->additionalAmount;
        }

        if ($request->paymentMode == 'Cash' || $request->paymentMode == 'Card' || $request->paymentMode == 'Online' || $request->paymentMode == 'IMPS') {
            $stdtransaction->totalPaid = $total_paid;
        } else {
            $stdtransaction->totalPaid = $total_paid;
            $stdtransaction->status = 'In-Process';
        }

        $next_receiptno = next_receiptno();
        $stdtransaction->receiptNo = 'SFP000' . $next_receiptno;
        $stdtransaction->idSchool = Auth::guard('school')->user()->idSchool;
        $stdtransaction->penaltyAmount = $penaltyAmount;
        $stdtransaction->fine = 0;
        $stdtransaction->discount = 0;
        $stdtransaction->created_by = Auth::guard('school')->user()->idSchoolUser;
        $stdtransaction->save();

        return $this->storeDetailsTransaction($request, $stdtransaction);
    }

    public function storeChequeTransaction(Request $request) {
        
    }

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

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

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

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

    public function stdList(Request $request) {
        $classes = ['' => '--Select Class--'] + \App\ClassM::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->orderBy('idClass')->get()->pluck('className', 'idClass')->toArray();
        $fys = ['' => '--Select Academic Year--'] + \App\FinancialYear::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->orderBy('idFinancialYear')->get()->pluck('financialYearName', 'idFinancialYear')->toArray();
        $students = [];
        if ($request->idClass != null && $request->idSection != null && $request->idFinancialYear != null) {
            $students = \App\AdmEntry::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                            ->where('idClass', '=', $request->idClass)
                            ->where('idSection', '=', $request->idSection)
                            ->where('idFinancialYear', '=', $request->idFinancialYear)
                            ->orderBy('idStudent')->get();
        } else if ($request->ecNo != null) {
            $students = \App\AdmEntry::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                    ->where('ecNo', '=', $request->ecNo)
                    ->get();
        }
        return view('schools.transaction.studentlist', compact('classes', 'students', 'fys'));
    }

    public function getFeeDetails($id,Request $request) {
      //  dd(Session::get('idFinancialYear'));
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $prevaccess_fee = DB::table('excess_transaction')
                        ->join('student_transaction', 'excess_transaction.idTransaction', '=', 'student_transaction.idTransaction')
                        ->where('idStudent', '=', $student->idStudent)
                        ->where('idFinancialYear', '=', Session::get('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();
        $paidfees_tot = \App\StudentTransaction::where('idStudent', '=', $student->idStudent)
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })
                        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                        ->select('paymentMode', 'paymentDate', 'idTransaction', DB::raw('SUM(totalPaid) as totalPaid'), DB::raw('SUM(discount) as discount'), DB::raw('SUM(fine) as fine'), DB::raw('SUM(penaltyAmount) as penaltyAmount'), DB::raw('SUM(outstandingAmount) as outstandingAmount'))->first();

        $paidfees = \App\StudentTransaction::where('idStudent', '=', $student->idStudent)
                        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'Success');
                        })->get();
        $lesserfees = \App\LesserTransaction::where('idStudent', '=', $student->idStudent)
                        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'Success');
                        })->get();

        if($student->idSchool == 25){
            $lesser_transaction = [];
            $feeheads = [];
            $feetotal = 0;
            $plan = '';
            
            if($paidfees->count() > 0){
                foreach($paidfees as $paidfee){
                    $transactions = \App\StudentTransactionDetail::where('idTransaction','=',$paidfee->idTransaction)->get();
                    foreach($transactions as $transaction){
                        $header = \DB::table('feeheads')->where('idFeehead',$transaction->idFeehead)->first();
                        if (str_contains($header->feeheadLabel, 'Plan A')) {
                            $plan = 'Plan A';
                            break;
                        }else if (str_contains($header->feeheadLabel, 'Plan B')) {
                            $plan = 'Plan B';
                            break;
                        }else if (str_contains($header->feeheadLabel, 'Plan C')) {
                            $plan = 'Plan C';
                            break;
                        }
                    }

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

            if($plan == '')
            if($lesserfees->count() > 0){
                foreach($lesserfees as $paidfee){
                    $transactions = \App\LesserTransactionDetail::where('idLesserTransaction','=',$paidfee->idLesserTransaction)->get();
                    foreach($transactions as $transaction){
                        $header = \DB::table('feeheads')->where('idFeehead',$transaction->idFeehead)->first();
                        if (str_contains($header->feeheadLabel, 'Plan A')) {
                            $plan = 'Plan A';
                            break;
                        }else if (str_contains($header->feeheadLabel, 'Plan B')) {
                            $plan = 'Plan B';
                            break;
                        }else if (str_contains($header->feeheadLabel, 'Plan C')) {
                            $plan = 'Plan C';
                            break;
                        }
                    }

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

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

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

            $feeData = PaymentCalculation::calculateFee($student,$request);
            $sessionPending = [];
            $idStudentSession = null;
            $fetchSession = \App\FinancialYear::where('idFinancialYear','<',$student->idFinancialYear)->where('idSchool', '=',$student->idSchool)->orderBy('idFinancialYear','DESC')->get();
            if(count($fetchSession) > 0){
                foreach($fetchSession as $var){
                    $studentSession = \App\AdmEntry::where('idSchool', '=', $student->idSchool)->where('idFinancialYear', '=', $var->idFinancialYear)->where('ecNo', '=', $student->ecNo)->where('isActive','Y')->first();
                    if($studentSession != null){
                        $sessionPending[$var->financialYearName] = PaymentCalculation::getOutstandingAmount($studentSession,$request);
                    }
                }                
            }
            return view('schools.transaction.feedetails_form_royal', compact('sessionPending','feeData','lesserfees', 'lesser_transaction', 'feetotal', 'paidfees_tot', 'student', 'paidfees', 'feeheads', 'prevaccess_fee','plan','type'));
        }else             
        {
            $class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                ->where('idSection', '=', $student->idSection)
                ->where('idFinancialYear','=', Session::get('idFinancialYear'))
                ->where('studentCategory', '=', $student->studentType)
                ->whereNull('idStudent');
            $allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                    ->where('idSection', '=', $student->idSection)
                    ->where('studentCategory', '=', 'All')
                    ->where('idFinancialYear','=', Session::get('idFinancialYear'))
                    ->whereNull('idStudent');
            $feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                    ->where('idFinancialYear','=', Session::get('idFinancialYear'))
                    ->union($class_feeheads)
                    ->union($allcat_feeheads)
                    ->orderBy('toDate')
                    ->get();
            $feetotal = $feeheads->sum('amount');
            $feeheader_ids = $feeheads->pluck('idFeehead')->toArray();
            $lesser_transaction = DB::table('lesser_transaction')
                ->join('lesser_transaction_details', 'lesser_transaction_details.idLesserTransaction', '=', 'lesser_transaction.idLesserTransaction')
                ->where('lesser_transaction.idStudent', '=', $student->idStudent)
                ->where('lesser_transaction.idFinancialYear', '=', Session::get('idFinancialYear'))
                ->whereIn('idFeehead', $feeheader_ids)
                ->where(function($query) {
                    $query->whereNull('lesser_transaction.status');
                    $query->orWhere('lesser_transaction.status', '=', 'Cleared');
                    $query->orWhere('lesser_transaction.status', '=', 'In-Process');
                    $query->orWhere('lesser_transaction.status', '=', 'Success');
                })
                ->select(DB::raw('SUM(totalPaid) as totalPaid'),DB::raw('SUM(lesser_transaction_details.discount) as discount'))
                ->first();
            
            if($student->idSchool == 135 || $student->idSchool == 140)
            {
                
                $plan = '';
                if($request->get('paymode') != null && $paidfees->count() == 0 && $lesserfees->count() == 0){
                    $plan = $request->get('paymode');
                    $class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                        ->where('idSection', '=', $student->idSection)
                        ->where('idFinancialYear','=', Session::get('idFinancialYear'))
                        ->where('studentCategory', '=', $student->studentType)
                        ->whereNull('idStudent');
                    $allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                            ->where('idSection', '=', $student->idSection)
                            ->where('studentCategory', '=', 'All')
                            ->where('idFinancialYear','=', Session::get('idFinancialYear'))
                            ->whereNull('idStudent');
                    $feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                            ->where('idFinancialYear','=', Session::get('idFinancialYear'))
                            ->union($class_feeheads)
                            ->union($allcat_feeheads)
                            ->orderBy('toDate')
                            ->get();
                    $feetotal = $feeheads->sum('amount');
                }else{
                    if($paidfees->count() > 0){
                        foreach($paidfees as $paidfee){
                            $transactions = \App\StudentTransactionDetail::where('idTransaction','=',$paidfee->idTransaction)->get();
                            foreach($transactions as $transaction){
                                $header = \DB::table('feeheads')->where('idFeehead',$transaction->idFeehead)->first();
                                if(isset($header->feeheadName)){
                                    if (str_contains($header->feeheadName, 'Plan A')) {
                                        $plan = 'Plan A';
                                        break;
                                    }else if (str_contains($header->feeheadName, 'Plan B')) {
                                        $plan = 'Plan B';
                                        break;
                                    }
                                }
                            }
                            if($plan != '') break;
                        }
                    }

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

                    if($request->get('paymode') != "")  $plan = $request->get('paymode');
                    
                    if($plan == '') $plan = 'Plan A';
                   $green = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                                    ->where('idSection', '=', $student->idSection)
                                    ->where('idFinancialYear','=',Session::get('idFinancialYear'))
                                    ->where('feeheadName',  'My contribution for green environment')
                                    ->whereNull('idStudent');
                    $class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                        ->where('idSection', '=', $student->idSection)
                        ->where('idFinancialYear','=', Session::get('idFinancialYear'))
                        ->where('studentCategory', '=', $student->studentType)
                        ->whereNull('idStudent');
                    $allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                            ->where('idSection', '=', $student->idSection)
                            ->where('studentCategory', '=', 'All')
                            ->where('idFinancialYear','=', Session::get('idFinancialYear'))
                            ->whereNull('idStudent');
                    $feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                            ->where('idFinancialYear','=', Session::get('idFinancialYear'))
                            ->union($class_feeheads)
                            ->union($allcat_feeheads)
                             ->union($green)
                            ->orderBy('toDate')
                            ->get();
                    $feetotal = $feeheads->sum('amount');

                }
                return view('schools.transaction.feedetails_form_mhws', compact('lesserfees', 'lesser_transaction', 'feetotal', 'paidfees_tot', 'student', 'paidfees', 'feeheads', 'prevaccess_fee','plan'));
            }
            else return view('schools.transaction.feedetails_form', compact('lesserfees', 'lesser_transaction', 'feetotal', 'paidfees_tot', 'student', 'paidfees', 'feeheads', 'prevaccess_fee'));
        }
    }

    public function getPreviousSessionFee($student){
        $paidfees = \App\StudentTransaction::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();
        $lesserfees = \App\LesserTransaction::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();

        $lesser_transaction = [];
        $feeheads = [];
        $feetotal = 0;
        $plan = '';
        
        if($paidfees->count() > 0){
            foreach($paidfees as $paidfee){
                $transactions = \App\StudentTransactionDetail::where('idTransaction','=',$paidfee->idTransaction)->get();
                foreach($transactions as $transaction){
                    $header = \DB::table('feeheads')->where('idFeehead',$transaction->idFeehead)->first();
                    if( $header != null){
                        if (str_contains($header->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 == '')
        if($lesserfees->count() > 0){
            foreach($lesserfees as $paidfee){
                $transactions = \App\LesserTransactionDetail::where('idLesserTransaction','=',$paidfee->idLesserTransaction)->get();
                foreach($transactions as $transaction){
                        $header = \DB::table('feeheads')->where('idFeehead',$transaction->idFeehead)->first();
                        if( $header != null){
                            if (str_contains($header->feeheadLabel, 'Plan A')) {
                                $plan = 'Plan A';
                                break;
                            }else if (str_contains($header->feeheadLabel, 'Plan B')) {
                                $plan = 'Plan B';
                                break;
                            }else if (str_contains($header->feeheadLabel, 'Plan C')) {
                                $plan = 'Plan C';
                                break;
                            }
                        }
                }

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

        $type = '';
        $outstanding = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
            ->where('idSection', '=', $student->idSection)
            ->where('idFinancialYear','=', $student->idFinancialYear)
            ->where('idStudent', '=', $student->idStudent)
            ->where('feeheadName', 'Outstanding Payment');
            
        if($plan == ''){
            $type = 'Plan A';
            $class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
            ->where('idSection', '=', $student->idSection)
            ->where('idFinancialYear','=', $student->idFinancialYear)
            ->where('studentCategory', '=', $student->studentType)
            ->where('feeheadLabel', 'LIKE', $type.'%')
            ->whereNull('idStudent');
            $allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                    ->where('idSection', '=', $student->idSection)
                    ->where('studentCategory', '=', 'All')
                    ->where('idFinancialYear','=', $student->idFinancialYear)
                    ->where('feeheadLabel', 'LIKE', $type.'%')
                    ->whereNull('idStudent');
            $feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                    ->where('idFinancialYear','=', $student->idFinancialYear)
                    ->where('feeheadLabel', 'LIKE', $type.'%')
                    ->union($class_feeheads)
                    ->union($allcat_feeheads)
                    ->union($outstanding)
                    ->orderBy('toDate')
                    ->get();
            $feetotal = $feeheads->sum('amount');
            $feeheader_ids = $feeheads->pluck('idFeehead')->toArray();
        }else if($plan != ''){
            $class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
            ->where('idSection', '=', $student->idSection)
            ->where('idFinancialYear','=', $student->idFinancialYear)
            ->where('studentCategory', '=', $student->studentType)
            ->where('feeheadLabel', 'LIKE', $plan.'%')
            ->whereNull('idStudent');
            $allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                    ->where('idSection', '=', $student->idSection)
                    ->where('studentCategory', '=', 'All')
                    ->where('idFinancialYear','=', $student->idFinancialYear)
                    ->where('feeheadLabel', 'LIKE', $plan.'%')
                    ->whereNull('idStudent');
            $feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                    ->where('idFinancialYear','=', $student->idFinancialYear)
                    ->where('feeheadLabel', 'LIKE', $plan.'%')
                    ->union($class_feeheads)
                    ->union($allcat_feeheads)
                    ->union($outstanding)
                    ->orderBy('toDate')
                    ->get();   
            $feetotal = $feeheads->sum('amount');
            $feeheader_ids = $feeheads->pluck('idFeehead')->toArray();
        }

        $sdiscount = \App\StudentDiscount::where('idStudent','=',$student->idStudent)
                                            ->whereIn('idFeehead', $feeheader_ids)->where('isActive', 'Y')->get();

        $std_trdet = \App\StudentTransactionDetail::join('student_transaction','student_transaction_details.idTransaction','=','student_transaction.idTransaction')->where('student_transaction_details.idStudent','=',$student->idStudent)
                                               ->whereIn('idFeehead', $feeheader_ids)
                                               ->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');
                                            })->select(DB::raw('student_transaction_details.amountPaid as amount'),DB::raw('student_transaction_details.discount as discount'),DB::raw('student_transaction_details.fine as fine'),'student_transaction_details.status')->orderBy('student_transaction_details.created_at','DESC')->first();
                                       
        $std_ledet = \App\LesserTransactionDetail::join('lesser_transaction','lesser_transaction_details.idLesserTransaction','=','lesser_transaction.idLesserTransaction')->where('lesser_transaction_details.idStudent','=',$student->idStudent)
                                               ->whereIn('idFeehead', $feeheader_ids)
                                               ->select(DB::raw('SUM(lesser_transaction_details.amountPaid) as amount'),DB::raw('SUM(lesser_transaction_details.discount) as discount'),DB::raw('SUM(lesser_transaction_details.fine) as fine'),'lesser_transaction_details.status')->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');
                                            })->first();


        $stepDiscount=0;
        if($sdiscount !=null){
            foreach($sdiscount as $discounts)
            {
                $stepDiscount=$stepDiscount+$discounts->amount;
            }
        }

        $totalAmount = 0;
        if($std_trdet != null)
        {
            $totalAmount = $totalAmount + $std_trdet['amount'] + $std_trdet['fine'] - $std_trdet['discount'];
        }  
        if($std_ledet != null)
        {
            $totalAmount = $totalAmount + $std_ledet['amount'] + $std_ledet['fine'] - $std_ledet['discount'];
        }   

        $feetotal = $feetotal - $stepDiscount;
        return $feetotal > $totalAmount;
    }

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

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

    public function lesserAmtReceipt($id) {
        $school = \App\School::where('idSchool', '=', Auth::guard('school')->user()->idSchool)->first();
        $transaction = \App\LesserTransaction::where('idLesserTransaction', '=', $id)->first();
        $totalAmountPaid = 0;
        $penaltyAmount = 0;
        $totalDiscount = 0;
        foreach($transaction->details as $det){
           $totalAmountPaid = \DB::table('lesser_transaction_details')->where('idStudent', '=', $det->idStudent)->where('idFeehead', '=', $det->idFeehead)->sum('amountPaid');
           $penaltyAmount = \DB::table('lesser_transaction_details')->where('idStudent', '=', $det->idStudent)->where('idFeehead', '=', $det->idFeehead)->sum('fine');
        } 

        $student = \App\AdmEntry::where('idStudent', '=', $transaction->idStudent)->first();
        $class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                ->where('idSection', '=', $student->idSection)
                ->where('studentCategory', '=', $student->studentType)
                ->whereNull('idStudent');
        //   ->get();
        $allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                ->where('idSection', '=', $student->idSection)
                ->where('studentCategory', '=', 'All')
                ->whereNull('idStudent');
        //   ->get();
        $feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                ->union($class_feeheads)
                ->union($allcat_feeheads)
                ->orderBy('toDate')
                ->get();
        $feetotal = $feeheads->sum('amount');

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

    public function cancelReceipt($id) {
        $transaction = \App\StudentTransaction::where('idTransaction', '=', $id)->first();
        $student = \App\AdmEntry::where('idStudent', '=', $transaction->idStudent)->first();
        return view('schools.transaction.cancelreceipt', compact('transaction', 'student'));
    }

    public function cancelLessPaidReceipt($id) {
        $transaction = \App\LesserTransaction::where('idLesserTransaction', '=', $id)->first();
        $student = \App\AdmEntry::where('idStudent', '=', $transaction->idStudent)->first();
        return view('schools.transaction.cancelreceipt', compact('transaction', 'student'));
    }

    public function receiptCancellation(Request $request) {
        $rules = ['remarks' => 'required'];
        $this->validate($request, $rules);
        $acessAmount = 0;
        if ($request->type == 'Full') {
            $transaction = \App\StudentTransaction::where('idTransaction', '=', $request->idTransaction)->first();
            $acessAmount = $transaction->accessPaid;
            DB::beginTransaction();
            $transaction->status = 'Cancelled';
            $transaction->remarks = $request->remarks;
            $transaction->update();


            \App\RollbackTransaction::insert($transaction->toArray());

            $stdtransaction_dets = \App\StudentTransactionDetail::where('idTransaction', '=', $request->idTransaction)->get();
            foreach ($stdtransaction_dets as $var) {
                $det = \App\StudentTransactionDetail::where('idTransactionDetail', '=', $var->idTransactionDetail)->first();
                $det->status = 'Cancelled';
                $det->update();

                //fill details in rollback details
                unset($det->idTransactionDetail);
                \App\RollbackTransactionDetails::insert($det->toArray());
            }
            DB::commit();
            if ($acessAmount > 0) {
                $excess_transaction = DB::table('excess_transaction')
                                ->join('student_transaction', 'excess_transaction.idTransaction', '=', 'student_transaction.idTransaction')
                                ->where('idStudent', '=', $request->idStudent)
                                ->where('idFinancialYear', '=', $request->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();
                if (isset($excess_transaction))
                    $acessAmount = $acessAmount + $excess_transaction->excessAmount;

                $excess = new \App\ExcessTransaction();
                $excess->idTransaction = $request->idTransaction;
                $excess->excessAmount = $acessAmount;
                $excess->remarks = "Access amount has been reverted to this transaction and previous access amount has been added";
                $excess->save();
            }
        } else {
            $transaction = \App\LesserTransaction::where('idLesserTransaction', '=', $request->idLesserTransaction)->first();
            $acessAmount = $transaction->accessPaid;
            DB::beginTransaction();
            $transaction->status = 'Cancelled';
            $transaction->remarks = $request->remarks;
            $transaction->update();

            \App\RollbackTransaction::insert($transaction->toArray());

            $stdtransaction_dets = \App\LesserTransactionDetail::where('idLesserTransaction', '=', $request->idLesserTransaction)->get();
            foreach ($stdtransaction_dets as $var) {
                $det = \App\LesserTransactionDetail::where('idLessTransactionDet', '=', $var->idLessTransactionDet)->first();
                $det->status = 'Cancelled';
                $det->update();

                unset($det->idLessTransactionDet);
                \App\RollbackTransactionDetails::insert($det->toArray());
            }
            DB::commit();
//            if ($acessAmount > 0) {
//                $excess_transaction = DB::table('excess_transaction')
//                                ->join('lesser_transaction', 'excess_transaction.idLesserTransaction', '=', 'lesser_transaction.idLesserTransaction')
//                                ->where('idStudent', '=', $request->idStudent)
//                                ->where('idFinancialYear', '=', $request->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.idLesserTransaction', 'desc')->first();
//                if (isset($excess_transaction))
//                    $acessAmount = $acessAmount + $excess_transaction->excessAmount;
//
//                $excess = new \App\ExcessTransaction();
//                $excess->idTransaction = $request->idTransaction;
//                $excess->excessAmount = $acessAmount;
//                $excess->remarks = "Access amount has been reverted to this transaction and previous access amount has been added";
//                $excess->save();
//            }
        }
        return redirect('school/cancelled-receipts');
    }

    public function getFeewiseData($id, $studentId,Request $request) {
        $student = \App\AdmEntry::where('idStudent', '=', $studentId)->first();
        if($student->idSchool == 25){
            return PaymentCalculation::calculateRoyal($id, $studentId,$request);
        }

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


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

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

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

        for ($i = 0; $i < sizeof($selectedHeaders); $i++) {

            $stepFine = 0;
            $stepDiscount = 0;
            $stepAmount = 0;
            $headerObject = $selectedHeaders[$i];
            $date = Carbon::parse($headerObject['toDate']);            
            if($request->get('payday') != null){
                $now = Carbon::parse($request->get('payday'));
            }else{
                $now = Carbon::now();
            }
            $diff = $date->diffInDays($now, false);
            if ($diff > 0) {
                if ($headerObject['fine'] != null && $headerObject['fine'] != 0.00) {
                    $stepFine = ( $headerObject['fine'] * $diff);
                } else
                if ($headerObject['flatFine'] != null) {
                    //in case of royal check month and calculate fine
                    if($student->idSchool == 25){
                        if($now->format('M') != $date->format('M')){
                            $now->addMonth();
                            $months = $now->diffInMonths($date);
                            if($months > 0){
                                $stepFine = $stepFine + ($headerObject['flatFine'] * $months);
                            }else
                            $stepFine = $stepFine + $headerObject['flatFine'];
                        }else $stepFine = $stepFine + $headerObject['flatFine'];
                    }else
                    $stepFine = $stepFine + $headerObject['flatFine'];
                }
            }

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

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

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

        $totalAmount = $totalAmount + $penaltyAmount + $outstandingAmount;
        $totalAmount = $totalAmount - $lessPaid;

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

}

Copyright © 2021 - 2025 IMMREX7