IMMREX7

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

<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Database\QueryException;
use PDF;
use \App\Http\SendNotificationApi;
use Carbon\Carbon;
use App\Http\PaymentCalculation;

class ClassMController extends Controller {

    public function fetchFilters($id,Request $request){
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $classes  = DB::table('classes')->select('classes.className','classes.idClass')
        ->where('idSchool', $student->idSchool)->get();
        
        return json_encode(array(
            "filter_class" => $classes,
        ));
    }

    //marks module
    public function prepareMarksheet($id,Request $request){
        $student = \App\AdmEntry::where('idStudent', '=', $request->get('idStudent'))->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
            $exam = \App\MarkExamType::join('financial_years','marks_exam_type.idFinancialYear','=','financial_years.idFinancialYear')->where('idType', $id)->first();
            $type = \App\MarkExams::where('marks_exam.idType', '=', $id)->first();
            $result = \App\ExamSheet::join('subjects', 'exam_marksheet.idSubject', '=', 'subjects.idSubject')->where('exam_marksheet.idStudent',$student->idStudent)->where('exam_marksheet.idFinancialYear', $student->idFinancialYear)->where('idExam',$id)->get();  
            $mine = $this->prepareResult($result,$type);
            $results = $mine["result"];
            $totalMarks = $mine["totalMarks"];
            $total = $mine["total"];
            $grade = $mine["grade"];
            $pdf = PDF::loadView('schools.exams.print_mark_sheet', ['margin_top' => 20], compact('results','totalMarks','total','grade', 'school', 'student','exam'));
            return $pdf->stream('marks.pdf');
        }else return json_encode(array());        
    }

    public function fetchExams(Request $request){
        $student = \App\AdmEntry::where('idStudent', '=', $request->id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
            $idExam = \App\MarkExams::where('idClass',$student->idClass)->where('idFinancialYear', $student->idFinancialYear)->whereRaw('idSection IS NULL OR idSection = ?', [$student->idSection])->groupBy('idType')->get()->pluck('idType')->toArray();
            $data = \App\MarkExamType::whereIn('idType', $idExam)->orderBy('idType')->paginate()->items();
            $i=0;
            foreach($data as $exam){
                $uid = $this->guidv4();
                DB::table('student_payment_session')->insert([
                    'idSchool' => $student->idSchool,
                    'idStudent' => $student->idStudent,
                    'idExam' => $exam->idType,
                    'uhid' => $uid
                ]);
                $payment_link = 'https://online-login.online/exam-overview/'.$uid;
                $data[$i]->result_link = $payment_link.'?view=result';
                $data[$i]->ai_link = $payment_link.'?view=ai';
                $i++;
            }
            return json_encode($data);
        }else return json_encode(array());
    }

    public function fetchReportCard(Request $request){
        $student = \App\AdmEntry::where('idStudent', '=', $request->id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
            $data = DB::table('exam_results')->join('exam_types', 'exam_results.idExamType', '=', 'exam_types.idExamType')->select('exam_results.idResult','exam_types.typeName as name','fromDate as from_date','todate as to_date','publishTime as publish_date')->where('idStudent',$request->id)
            ->orderBy('idResult')->paginate()->items();
            $i = 0;
            foreach($data as $var){
                $template = \App\ExamResult::join('exam_types', 'exam_results.idExamType', '=', 'exam_types.idExamType')
                ->select('exam_results.*', 'exam_types.typeName')
                ->where('exam_results.idResult', '=', $var->idResult)->first();
                $path = 'schools/' . $template->idSchool . '/results/' . $template->typeName .'/'. $template->ecNo .'.pdf';
                $data[$i]->urlData = "https://online-login.online/storage/".$path;
                $i++;
            }
            return json_encode($data);
        }else return json_encode(array());
    }

    public function fetchStudentResults(Request $request){
        $student = \App\AdmEntry::where('idStudent', '=', $request->idStudent)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
            $idExam = \App\MarkExams::select('created_at as result','idType')->where('marks_exam.idType', '=', $request->id)->first();
            $uid = $this->guidv4();
                DB::table('student_payment_session')->insert([
                    'idSchool' => $student->idSchool,
                    'idStudent' => $student->idStudent,
                    'idExam' => $idExam->idType,
                    'uhid' => $uid
                ]);
            $payment_link = 'https://online-login.online/exam-overview/'.$uid;
            $idExam->result_link = $payment_link.'?view=result';
            $idExam->ai_link = $payment_link.'?view=ai';
            return json_encode($idExam);
        }else return json_encode(array());
    }

    public function fetchResults(Request $request){
        $student = \App\AdmEntry::where('idStudent', '=', $request->id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
            $type = \App\MarkExams::where('marks_exam.idType', '=', $request->idExam)->first();
            $result = \App\ExamSheet::join('subjects', 'exam_marksheet.idSubject', '=', 'subjects.idSubject')->where('exam_marksheet.idStudent',$student->idStudent)->where('exam_marksheet.idFinancialYear', $student->idFinancialYear)->where('idExam',$request->idExam)->get();  
            $examByPerformance = \App\ExamSheet::join('marks_exam_type', 'exam_marksheet.idExam', '=', 'marks_exam_type.idType')->select(DB::raw('SUM(total) as marks'),'name')->where('exam_marksheet.idStudent',$student->idStudent)->where('exam_marksheet.idFinancialYear', $student->idFinancialYear)->whereNotNull('marks')->groupBy('idExam','idStudent')->get();
            
            
            $topper = \App\ExamSheet::select(DB::raw('SUM(total) as total'),'idStudent as id')->where('exam_marksheet.idClass',$student->idClass)->where('exam_marksheet.idFinancialYear', $student->idFinancialYear)->where('idExam',$request->idExam)->groupBy('idStudent')->orderBy('total','DESC')->first();
            $lowest = \App\ExamSheet::select(DB::raw('SUM(total) as total'),'idStudent as id')->where('exam_marksheet.idClass',$student->idClass)->where('exam_marksheet.idFinancialYear', $student->idFinancialYear)->where('idExam',$request->idExam)->groupBy('idStudent')->orderBy('total','ASC')->first();
            $topperDetails = \App\AdmEntry::join('classes', 'students.idClass', '=', 'classes.idClass')
            ->join('sections', 'students.idSection', '=', 'sections.idSection')->where('idStudent', '=', $topper->id)->first();
            $topperResult = \App\ExamSheet::join('subjects', 'exam_marksheet.idSubject', '=', 'subjects.idSubject')->where('exam_marksheet.idStudent',$topper->id)->where('exam_marksheet.idFinancialYear', $student->idFinancialYear)->where('idExam',$request->idExam)->get();  
            
            $mine = $this->prepareResult($result,$type);
            $top = $this->prepareResult($topperResult,$type);
            if($lowest->total == null) $score =  0 ;
            else $score =  $lowest->total;
            $data = array(
                "result" => $mine["result"],
                "performance" => $examByPerformance,
                "mine-total" => $mine["total"],
                "mine-exam-total" => $mine["totalMarks"],
                "mine-grade" => $mine["grade"],
                "min-total" => $score,
                "topper" => $top["result"],
                "topper-total"=> $top["total"],
                "topper-grade" => $top["grade"],
                "topper-exam-total" => $top["totalMarks"],
                "topper-class" => $topperDetails->className.'-'.$topperDetails->sectionName,
                "topper-name" => $topperDetails->firstName.' '. $topperDetails->middleName.' '. $topperDetails->lastName
            );
            return json_encode($data);
        }else return json_encode(array());
    }

    private function prepareResult($result,$type){
        $totalMarks = json_decode($type->marks,true);
        $gradesRange = json_decode($type->grades,true);
        $resultArr = array();
        $overMinelTotal = 0;
        $overTotal = 0;
            foreach($result as $marks){
                $temp = array(
                    "subject" => $marks->subjectName,
                    "full_marks" => 0,
                    "status" => $marks->attendance,
                    "theory" => $marks->marks,
                    "practical" => $marks->pratical,
                    "total" => $marks->marks + $marks->pratical,
                    "grade" => "",
                    "percentage" => ""
                );
                $overMinelTotal = $overMinelTotal + $temp["total"];
                foreach($totalMarks as $total){
                    if($total["id"] == $marks->idSubject)
                    {
                        if($total["pratical"] == "nil")
                        {
                            $temp["full_marks"] = $total["theory"];
                            $temp["practical"] = "NA";
                        }
                        else
                        $temp["full_marks"] = $total["theory"] + $total["pratical"];
                        $overTotal = $overTotal + $temp["full_marks"];

                        if($temp["full_marks"] != 0 )
                        {
                            $temp["percentage"] = ($temp["total"] / $temp["full_marks"]) * 100;
                            $temp["percentage"] =  number_format((float)$temp["percentage"], 2, '.', '');
                        }
                    }
                    
                }
                foreach($gradesRange as $range){
                    $total = $temp["total"];
                    if($range["from"] <= $total  &&  $total <= $range["to"] ){
                        $temp["grade"] = $range["name"];
                    }
                }
                array_push($resultArr,$temp);
            }
            $grade = '';
            foreach($gradesRange as $range){
                if($overTotal > 0){
                    $total = ($overMinelTotal / $overTotal) * 100;
                    if($range["from"] <= $total  &&  $total <= $range["to"] ){
                        $grade = $range["name"];
                    }
                }
            }
       return array(
                "result" => $resultArr,
                "total" => $overMinelTotal,
                "totalMarks" => $overTotal,
                "grade" => $grade,
            );     
    }


    public function fetchReceipt(Request $request){
        $student = \App\AdmEntry::where('idStudent', '=', $request->id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' || $student->isActive == 'Y'){
            $paidfees = \App\StudentTransaction::where('idStudent', '=', $request->id)->where('idFinancialYear','=',$student->idFinancialYear)
            ->where(function($query) {
                $query->whereNull('status');
                $query->orWhere('status', '=', 'In-Process');
                $query->orWhere('status', '=', 'Cleared');
                $query->orWhere('status', '=', 'Success');
            })
            ->get();
            $transaction = \App\ShopTransaction::where('idStudent', '=', $request->id)->where('idFinancialYear','=',$student->idFinancialYear)
            ->where(function($query) {
                $query->whereNull('status');
                $query->orWhere('status', '=', 'In-Process');
                $query->orWhere('status', '=', 'Cleared');
                $query->orWhere('status', '=', 'Success');
            })
            ->get();
            foreach($paidfees as $transact){
                $feeHead = \App\StudentTransactionDetail::join('feeheads', 'student_transaction_details.idFeehead', '=', 'feeheads.idFeehead')->where('idTransaction', '=', $transact->idTransaction)->first();
                if($feeHead != null)
                if(str_contains($feeHead->feeheadName, "Full Payment") && $feeHead->idFinancialYear == 244){
                    $transaction[] = json_decode(json_encode (array(
                        "type" => "book",
                        "idTransaction" => $transact->idTransaction."00",
                        "receiptNo" => "BOOK".$transact->idTransaction."MH",
                        "totalPaid" => "0.00",
                        "paymentDate" => $transact->paymentDate,
                        "paymentMode" => $transact->paymentMode,
                        "fine" => $transact->fine
                    )), FALSE);
                    break;
                }
            }
            return json_encode(array(
                "transaction" => $transaction
            ));    
        }else{
            return json_encode(array(
                "transaction" => [],
                "total" => 0
            ));
        }
    }

    public function fetchFoodReceipt(Request $request){
        $student = \App\AdmEntry::where('idStudent', '=', $request->id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' || $student->isActive == 'Y'){
            $transaction = \App\FoodTransaction::where('idStudent', '=', $request->id)->where('idFinancialYear','=',$student->idFinancialYear)
            ->where(function($query) {
                $query->whereNull('status');
                $query->orWhere('status', '=', 'In-Process');
                $query->orWhere('status', '=', 'Cleared');
                $query->orWhere('status', '=', 'Success');
            })
            ->get();
            return json_encode(array(
                "transaction" => $transaction
            ));    
        }else{
            return json_encode(array(
                "transaction" => [],
                "total" => 0
            ));
        }
    }

    public function processItems(Request $request){
        $student = \App\AdmEntry::where('idStudent', '=', $request->id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
            $items = json_decode($request->items,true);
            $checkout = array();
            $total = 0;
            $isBook = 1;
            $isUniform = 1;
            foreach($items as $item){
                $product =  \App\Product::where('idProduct',$item['idProduct'])->first();
                if($product != null){
                    $price = $item['qty'] * $product->salePrice;
                    $total = $total + $price;
                    array_push(
                        $checkout,
                        array(
                            "idProduct" => $product->idProduct,
                            "productImage" => $product->productImage,
                            "productName" => $product->productName,
                            "salePrice" => $product->salePrice,
                            "price" => $price,
                            "idSchool" => $product->idSchool,
                            "qty" => $item['qty']
                        )
                    );
                    if (str_contains($product->productName, 'Books') || str_contains($product->productName, 'BOOKS')) {
                        $isBook = 2;
                    }
                    if (str_contains($product->productName, 'Uniform')) {
                        $isUniform = 2;
                    }
                }
            }

            if($isBook == 2 && $isUniform == 2){
                return json_encode(array(
                    "products" => [],
                    "total" => 0,
                    "error_message" => "You have to buy book and uniform separately. Cannot process the order as both items are present in one cart.",
                    "pg" => $this->pg
                ));
            }

            return json_encode(array(
                "products" => $checkout,
                "total" => $total,
                "pg" => $this->pg
            ));    
        }else{
            return json_encode(array(
                "products" => [],
                "total" => 0,
                "pg" => $this->pg
            ));
        }
    }

    public function processFoodItems(Request $request){
        date_default_timezone_set("Asia/Kolkata");  
        $student = \App\AdmEntry::where('idStudent', '=', $request->id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
            $items = json_decode($request->items,true);
            $foodVendor = \App\FoodVendor::where('idSchool', $student->idSchool)->where('idFinancialYear', $student->idFinancialYear)->first();
            if($foodVendor == null){
                return json_encode(array(
                    "products" => [],
                    "total" => 0,
                    "error_message" => "You have not registered any vendor deliver your order. Please contact the administrator",
                    "pg" => $this->pg
                ));
            }

            $orderEndTime = explode("-",$foodVendor ->order_time);
            if(count($orderEndTime) > 1){
                $now = Carbon::now()->format('d-m-Y');
                $endTime = Carbon::parse($now.' '.$orderEndTime[1].':00');
                $currentTime =  Carbon::now();
                //$are_different = $currentTime->gt($endTime);
                $are_different = $currentTime->diffForHumans($endTime,[]);
                if(str_contains($are_different, 'after')){
                    return json_encode(array(
                        "products" => [],
                        "total" => 0,
                        "error_message" => "Vendor is closed for taking any new order right now. Please try again tomorrow.",
                        "pg" => $this->pg
                    ));
                }
            }else{
                return json_encode(array(
                    "products" => [],
                    "total" => 0,
                    "error_message" => "Vendor is not taking any new order right now",
                    "pg" => $this->pg
                ));
            }

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

            if($shopReceipt != null){
                return json_encode(array(
                    "products" => [],
                    "total" => 0,
                    "error_message" => "You have already placed your order. Please try again tomorrow",
                    "pg" => $this->pg
                ));
            }

            foreach($items as $item){
                $product =  \App\Food::select('id as idProduct','item_name as productName','pic as productImage', 'price as salePrice', 'idSchool', 'short_description as description','max_buy')->where('id',$item['idProduct'])->first();
                if($product != null){
                    $price = $item['qty'] * $product->salePrice;
                    $total = $total + $price;
                    array_push(
                        $checkout,
                        array(
                            "idProduct" => $product->idProduct,
                            "productImage" => $product->productImage,
                            "productName" => $product->productName,
                            "salePrice" => $product->salePrice,
                            "price" => $price,
                            "idSchool" => $product->idSchool,
                            "qty" => $item['qty']
                        )
                    );
                }
            }
            return json_encode(array(
                "products" => $checkout,
                "total" => $total,
                "pg" => $this->pg
            ));    
        }else{
            return json_encode(array(
                "products" => [],
                "total" => 0,
                "pg" => $this->pg
            ));
        }
    }

    public function fetchItems(Request $request){
        $student = \App\AdmEntry::where('idStudent', '=', $request->id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
            $classes = \App\ClassM::select('idClass','className')->where('idSchool', '=', $student->idSchool)->get();
            $paidfees = \App\StudentTransaction::where('idStudent', '=',  $request->id)->where('idFinancialYear','=',$student->idFinancialYear)
            ->where(function($query) {
                $query->whereNull('status');
                $query->orWhere('status', '=', 'In-Process');
                $query->orWhere('status', '=', 'Cleared');
                $query->orWhere('status', '=', 'Success');
            })
            ->get();
            $isBookAllowed = "Y";
            $maxBuy = 3;
            foreach($paidfees as $transact){
                $feeHead = \App\StudentTransactionDetail::join('feeheads', 'student_transaction_details.idFeehead', '=', 'feeheads.idFeehead')->where('idTransaction', '=', $transact->idTransaction)->first();
                if($feeHead != null)
                if(str_contains($feeHead->feeheadName, "Full Payment")){
                    $isBookAllowed = "N";
                    break;
                }
            }
            if($request->search != null){
                $products =  \App\Product::select('idProduct','productName','productImage','salePrice','idSchool')->where('idSchool', '=', $student->idSchool)
                ->where('idFinancialYear', '=', $student->idFinancialYear)
                ->where('productName', 'LIKE', $request->search.'%')
                ->get();
                return json_encode(array(
                    "products" => $products,
                    'books' => $isBookAllowed,
                    'max'=>$maxBuy
                )); 
            }

            if($request->products != null){
                $products =  \App\Product::select('idProduct','productName','productImage','salePrice','idSchool')->where('idSchool', '=', $student->idSchool)
                ->where('idFinancialYear', '=', $student->idFinancialYear)
                ->get();
                return json_encode(array(
                    "products" => $products,
                    'books' => $isBookAllowed,
                    'max'=>$maxBuy
                ));
            }

            $className =  \App\ClassM::where('idClass', '=', $student->idClass)->first()->className;
            $products =  \App\Product::select('idProduct','productName','productImage','salePrice','idSchool')
            ->where('idSchool', '=', $student->idSchool)
            ->where('idFinancialYear', '=', $student->idFinancialYear)
            ->where('productName', 'LIKE', $className.'%')
            ->get();
        
            return json_encode(array(
                "products" => $products,
                "filter" => $classes,
                'books' => $isBookAllowed,
                'max'=>$maxBuy
            ));                    
        }else
        return json_encode(array(
            "products" => [],
            "filter" => [],
            'books' => "N",
            'max'=>'0'
        ));
    }

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

            $classes = \App\ClassM::select('idClass','className')->where('idSchool', '=', $student->idSchool)->get();
            $vendor = \App\FoodVendor::where('idSchool', '=', $student->idSchool)
            ->where('idFinancialYear',$student->idFinancialYear)->first();
            $vendorTime = explode("-",$vendor->order_time);
            $now = Carbon::now();
            $idFoodStock = DB::table('food_stock')->whereDate('food_date',$now->format('Y-m-d'))->get()->pluck('idFood')->toArray();
            $toTime = Carbon::parse($now->format('d-M-Y').' '.$vendorTime[0]);
            $now->subDays(1);
            $fromTime = Carbon::parse($now->format('d-M-Y').' '.$vendorTime[1]);
            if(count($idFoodStock) == 0){
                if (str_contains($fromTime->diffForHumans(), 'ago') && str_contains($toTime->diffForHumans(), 'ago')){
                    updateOldStock($student->idSchool,$student->idFinancialYear,$now);
                    $fresh = Carbon::now();
                    $idFood = DB::table('food_stock')->whereDate('food_date',$fresh->format('Y-m-d'))->get()->pluck('idFood')->toArray();
                }
            }else{
                $now = Carbon::now();
                $idFood = DB::table('food_stock')->whereDate('food_date',$now->format('Y-m-d'))->get()->pluck('idFood')->toArray();
            }

            if(isset($request->search))
            $products =  \App\Food::select('id as idProduct','item_name as productName','pic as productImage', 'price as salePrice', 'idSchool', 'short_description as description','max_buy')->where('item_name', 'LIKE', "%".$request->search."%")->whereIn('id',$idFood)->where('idSchool', '=', $student->idSchool)->get();
            else $products =  \App\Food::select('id as idProduct','item_name as productName','pic as productImage', 'price as salePrice', 'idSchool', 'short_description as description','max_buy')->whereIn('id',$idFood)
                                        ->where('idSchool', '=', $student->idSchool)->get();
            
            return json_encode(array(
                "products" => $products,
                "filter" => $classes
            ));                    
        }else
        return json_encode(array(
            "products" => [],
            "filter" => []
        ));
    }

    public function getChatTeachers(Request $request) {
        $student = \App\AdmEntry::where('idStudent', '=', $request->id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
            $data = DB::table('teacher_classes')
                        ->join('employees','teacher_classes.idEmployee','employees.idEmployee')
                        ->join('designations','employees.idDesignation','designations.idDesignation')
                        ->select('teacher_classes.idEmployee as id','firstName','middleName','lastName','designationName')
                        ->where('teacher_classes.idFinancialYear',$student->idFinancialYear)
                        ->where('teacher_classes.idSchool',$student->idSchool)
                        ->where('teacher_classes.idSection', $student->idSection)
                        ->where('teacher_classes.idClass', $student->idClass);
            if($request->name){
                $data = $data->where('firstName', 'LIKE','%'.$request->name.'%');
            }            
            $data = $data->distinct('teacher_classes.idEmployee')->paginate();
            return json_encode($data);               
        }else{
             return json_encode(array());
        }
    }

    public function createMessage() {
       
    }

    public function sendMessage() {
       
    }

    public function getMessage() {
       
    }

    public function fetchCardMaster($id){
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
            /*$isVerified = \App\CardView::where('idStudent',$id)->where('idFinancialYear', $student->idFinancialYear)->where('isVerified','Y')->first();
            if($isVerified != null){
                return json_encode(array(
                    'message' => 'You have already updated the card'
                ));
            }*/
            $today_date = Carbon::today()->format('Y-m-d');
            $data = \App\CardMaster::select('end_date as close_time')->where('idSchool', $student->idSchool)->where('idFinancialYear', $student->idFinancialYear)->whereDate('end_date','>=',$today_date)->whereDate('start_date','<',$today_date)->first();
            if($data == null) {
                return json_encode(array('close_time' => date('Y-m-d',strtotime("-1 days"))));
            }
            return json_encode($data);
        }else return json_encode(array('close_time' => date('Y-m-d',strtotime("-1 days"))));
    }

    public function saveVirtualCard($id, Request $request){
        $student = \App\AdmEntry::join('classes', 'students.idClass', '=', 'classes.idClass')
        ->join('sections', 'students.idSection', '=', 'sections.idSection')->select('students.studentType','students.idSection','students.idClass','father_fname','father_lname','isActive','idFinancialYear','father_mobile','mother_mobile','resPincode','className','sectionName','resAddress','resCity','resState','landmark','studentDob','photo','firstName','middleName','lastName','students.idSchool')->where('idStudent', '=', $id)->first()->toArray();
        $school = \App\School::where('idSchool', '=', $student['idSchool'])->first();
        if($school->isActive == 'Y' && $student['isActive'] == 'Y'){
            $isVerified = \App\CardView::where('idStudent',$id)->where('idFinancialYear', $student['idFinancialYear'])->first();
            if($isVerified == null)
            $card = new \App\CardView();
            else $card = $isVerified;
            $card->idStudent = $id;
            $card->className = $student['className'];
            $card->idClass = $student['idClass'];
            $card->idSection = $student['idSection'];
            $card->idSchool = $student['idSchool'];
            $card->idFinancialYear = $student['idFinancialYear'];
            $card->sectionName = $student['sectionName'];
            $fatherName = '';
            if($student['father_fname'] != null){
                $fatherName = $fatherName.trim($student['father_fname']).' ';
            }
            if($student['father_lname'] != null){
                $fatherName = $fatherName.trim($student['father_lname']).' ';
            }
            $card->parentName = $fatherName;
            $card->isVerified = 'Y';
            $card->parentDate = Carbon::today()->format('Y-m-d');
            if($request->type == "edit"){
                $card->studentName = $request->name;
                $card->address = $request->address.' '.$request->city.' '.$request->pincode;
                $card->student_dob = $request->dob;
                $card->contact_alternative = $request->mother_contact;
                $card->contactNo = $request->father_contact;
                $card->photo = $student['photo'];
                if( $card->photo == null){
                    if (!$request->hasFile('photo')) {
                        return json_encode(array(
                            'results' => 0,
                            "message" => "Photo is mandatory."
                        ));  
                    }
                }
            }else{
                if (!$request->hasFile('photo')) {
                    return json_encode(array(
                        'results' => 0,
                        "message" => "Photo is mandatory."
                    ));  
                }
                
                if($isVerified == null){
                    $studentName = '';
                    if($student['firstName'] != null){
                        $studentName = $studentName.trim($student['firstName']).' ';
                    }
                    if($student['middleName'] != null){
                        $studentName = $studentName.trim($student['middleName']).' ';
                    }
                    if($student['lastName'] != null){
                        $studentName = $studentName.trim($student['lastName']);
                    }
                    
                    $address = '';
                    if($student['resAddress'] != null){
                        $address = $address.trim($student['resAddress']).' ';
                    }
                    if($student['resCity'] != null){
                        $address = $address.trim($student['resCity']).' ';
                    }
                    if($student['resPincode'] != null){
                        $address = $address.trim($student['resPincode']);
                    }
                    $card->studentName = $studentName;
                    $card->address = $address;
                    $card->student_dob = Carbon::parse($student['studentDob'])->format('d-m-Y');
                    $card->contact_alternative = $student['mother_mobile'];
                    $card->contactNo = $student['father_mobile'];
                    $card->photo = $student['photo'];
                }
            }
            if($isVerified == null)
            $card->save();
            else $card->update();

            if ($request->hasFile('photo')) {
                $photo = 'virtualcard_' . $card->id. '.' . $request->file('photo')->getClientOriginalExtension();
                $request->file('photo')->storeAs('public/schools/' . $school->idSchool . '/students/', $photo);
                $card->photo = $photo;
                $card->update();
            }


            DB::beginTransaction();
            try {
                if($request->type == "edit"){
                    $studentDob = Carbon::parse($request->dob)->format('Y-m-d');

                    if(isset($request->idSection)){
                        //old transaction
                        $paidfees = \App\StudentTransaction::join('student_transaction_details', 'student_transaction.idTransaction', '=', 'student_transaction_details.idTransaction')->where('student_transaction.idStudent', '=', $id)
                                    ->where('student_transaction.idFinancialYear', '=',$student['idFinancialYear'])->get();
                        $lesserfees = \App\LesserTransaction::join('lesser_transaction_details', 'lesser_transaction_details.idLesserTransaction', '=', 'lesser_transaction.idLesserTransaction')->where('lesser_transaction.idStudent', '=', $id)
                                    ->where('lesser_transaction.idFinancialYear', '=', $student['idFinancialYear'])->get();
                        
                        //new transaction
                        $outstanding = \DB::table('feeheads')->where('idClass', '=', $student['idClass'])
                                        ->where('idSection', '=', $request->idSection)
                                        ->where('idFinancialYear','=', $student['idFinancialYear'])
                                        ->where('idStudent', '=', $id)
                                        ->where('feeheadName', 'Outstanding Payment');
                        $class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student['idClass'])
                                    ->where('idSection', '=',  $request->idSection)
                                    ->where('idFinancialYear','=', $student['idFinancialYear'])
                                    ->where('studentCategory', '=', $student['studentType'])
                                    ->whereNull('idStudent');
                        $allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student['idClass'])
                                    ->where('idSection', '=',  $request->idSection)
                                    ->where('studentCategory', '=', 'All')
                                    ->where('idFinancialYear','=', $student['idFinancialYear'])
                                    ->whereNull('idStudent');
                        $feeheads = \DB::table('feeheads')->where('idStudent', '=',$id)
                                    ->where('idFinancialYear','=', $student['idFinancialYear'])
                                    ->union($class_feeheads)
                                    ->union($allcat_feeheads)
                                    ->union($outstanding)
                                    ->orderBy('toDate')
                                    ->get();
                        
                        //update paid transaaction
                        foreach($paidfees as $paidfee){
                            $feeheader = DB::table('feeheads')->where('idFeehead',$paidfee->idFeehead)->first();
                            foreach($feeheads as $feehead){
                                if($feeheader->feeheadName == $feehead->feeheadName && $feeheader->feeheadLabel == $feehead->feeheadLabel){
                                    DB::table('student_transaction_details')
                                    ->where('idStudent', $id)
                                    ->where('idFeehead', $paidfee->idFeehead)
                                    ->update(['idFeehead' =>  $feehead->idFeehead]);
                                }
                            } 
                        }     
                        
                        //update less transaaction
                        foreach($lesserfees as $paidfee){
                            $feeheader = DB::table('feeheads')->where('idFeehead',$paidfee->idFeehead)->first();
                            foreach($feeheads as $feehead){
                                if($feeheader->feeheadName == $feehead->feeheadName && $feeheader->feeheadLabel == $feehead->feeheadLabel){
                                    DB::table('lesser_transaction_details')
                                    ->where('idStudent', $id)
                                    ->where('idFeehead', $paidfee->idFeehead)
                                    ->update(['idFeehead' =>  $feehead->idFeehead]);
                                }
                            }
                        }

                        //update feehead section
                        DB::table('feeheads')
                        ->where('idStudent', $id)
                        ->where('idFinancialYear', $student['idFinancialYear'])
                        ->update(['idSection' =>  $request->idSection]);

                        $card->sectionName = \App\Section::select('sectionName','idSection')->where('idSection',$request->idSection)->first()->sectionName;
                        $card->idSection = $request->idSection;
                        $card->update();
                    }

                    if(isset($request->idSection))
                    DB::table('students')
                    ->where('idStudent', $id)
                    ->update(['firstName' => $request->name,'idSection' => $request->idSection,'middleName' => '','lastName' => '','studentDob' => $studentDob,'photo' => $card->photo ,'contactPersonMobile' => $request->father_contact,'contactPersonTel' => $request->mother_contact,'resAddress' => $request->address,'resCity' => $request->city,'resPincode' => $request->pincode]);
                    else 
                    DB::table('students')
                    ->where('idStudent', $id)
                    ->update(['firstName' => $request->name,'middleName' => '','lastName' => '','studentDob' => $studentDob,'photo' => $card->photo ,'contactPersonMobile' => $request->father_contact,'contactPersonTel' => $request->mother_contact,'resAddress' => $request->address,'resCity' => $request->city,'resPincode' => $request->pincode]);
                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollback();
                // something went wrong
                return json_encode(array(
                    'success' => 'FAILED', 
                    'results' => 0,
                    "message" => $e->getMessage()
                ));
            }

            return json_encode(array(
                'success' => 'SUCCESS',
                "message" => "Card details are saved."
            ));   
        }
        else return json_encode(array(
            'results' => 0,
            "message" => "Card details are not saved."
        ));   
    }


    public function geCardStudent($id){
        $data = \App\CardView::where('id',$id)->first();
        $section = \App\Section::select('sectionName','idSection')->where('idClass',$data->idClass)->get()->toArray();
        $isVerified = \App\CardView::where('id',$id)->where('isChecked','Y')->first();
            if($isVerified == null)
            $student['isEditable'] = 'N';
            else {
                $student['isEditable'] = 'Y';
            }
            $isParent = \App\CardView::where('id',$id)->where('isVerified','Y')->first();
            if($isParent == null)
            $student['telephone'] = 'N';
            else {
                $student['telephone'] = 'Y';
            }
            if($data != null){
                $student['mother_mobile'] =  $data->contact_alternative;
                $student['father_mobile'] = $data->contactNo;
                $student['resAddress'] = $data->address;
                $student['resCity'] = $data->city;
                $student['resPincode'] = $data->pincode;
                $student['studentDob'] = Carbon::parse($data->student_dob)->format('Y-m-d');
                if(isset($data->photo)){
                    $student['photo'] = $data->photo;
                }
                $student['firstName'] = $data->studentName;
                $student['middleName'] = '';
                $student['lastName'] = '';
                $student['idSchool'] = $data->idSchool;
                $student['className'] = $data->className;
                $student['sectionName'] = "";
            }
            $student["sections"] = $section;
        return json_encode($student);
    }

    public function fetchWardDetails($id, Request $request){

        if($request->get('link') != null){
            if($request->get('link') == "Y"){
                $data = \App\CardView::where('id',$id)->first();
                if($data->idStudent == null){
                    return $this->geCardStudent($id);
                }
            }
        }   
        
        $student = \App\AdmEntry::join('classes', 'students.idClass', '=', 'classes.idClass')
        ->join('sections', 'students.idSection', '=', 'sections.idSection')->select('isActive','father_mobile','idFinancialYear','mother_mobile','className','sectionName','resAddress','resCity','resPincode','resState','landmark','studentDob','photo','firstName','middleName','lastName','students.idSchool','students.idClass')->where('idStudent', '=', $id)->first()->toArray();

        $school = \App\School::where('idSchool', '=', $student['idSchool'])->first();
        if($school->isActive == 'Y' && $student['isActive'] == 'Y'){
            $section = \App\Section::select('sectionName','idSection')->where('idClass',$student['idClass'])->get()->toArray();
            $isParent = \App\CardView::where('idStudent',$id)->where('idFinancialYear', $student['idFinancialYear'])->where('isVerified','Y')->first();
            if($isParent == null)
            $student['telephone'] = 'N';
            else {
                $student['telephone'] = 'Y';
            }
            
            $isVerified = \App\CardView::where('idStudent',$id)->where('idFinancialYear', $student['idFinancialYear'])->where('isChecked','Y')->first();
            if($isVerified == null)
            $student['isEditable'] = 'N';
            else {
                $student['isEditable'] = 'Y';
            }
            $data = \App\CardView::where('idStudent',$id)->where('idFinancialYear', $student['idFinancialYear'])->first();
            if($data != null){
                $student['mother_mobile'] =  $data->contact_alternative;
                $student['father_mobile'] = $data->contactNo;
                $student['resAddress'] = $data->address;
                $student['resCity'] = $student['resCity'];
                $student['resPincode'] = $student['resPincode'];
                $student['studentDob'] = Carbon::parse($data->student_dob)->format('Y-m-d');
                if(isset($data->photo)){
                    $student['photo'] = $data->photo;
                }
                $student['firstName'] = $data->studentName;
                $student['middleName'] = '';
                $student['lastName'] = '';
            }
            $student["sections"] = $section;
            return json_encode($student);
        }else return json_encode(array());
    }

    public function getClasses() {
        $classes = \App\ClassM::
                orderBy('idClass', 'desc')->get();
        return json_encode($classes);
    }
    
    public function getMcqResults($id,$limit){
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
              $results = \App\McqResult::join('exam_mcq','exam_mcq_results.idExam','exam_mcq.idMcq')
                        ->where('idStudent','=',$student->idStudent)
                        ->skip($limit)
                        ->take($limit+20)
                        ->get();
                return json_encode($results);        
        }else{
             return json_encode(array());
        }
    }

    public function getLiveConference($id,$skip){
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
            $data = DB::table('video_confernce')->where('idFinancialYear','=',$student->idFinancialYear)
                        ->where('idSchool','=',$student->idSchool)
                        ->where(function($query) use ($student) {
                            $query->whereRaw('idSection IS NULL AND idClass = ?', [$student->idClass]);
                            $query->orWhereRaw('idSection = ? AND idClass = ?', [$student->idSection,$student->idClass]);
                        })
                        ->orderBy('isActive', 'desc')
                        ->skip($skip)
                        ->take(20)
                        ->get();
            return json_encode($data);               
        }else{
             return json_encode(array());
        }
    }
    
    public function getStudentResults($id,$idExam){
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){

              $results = \App\McqResult::where('idStudent','=',$student->idStudent)
                        ->where('idExam','=',$idExam)
                        ->first();

              if(isset($results)) {
                  $results->total = DB::table('exam_mcq')->where('idMcq',$idExam)->first()->totalMarks;

                  $results->highest = \App\McqResult::where('idExam','=',$idExam)->max('marks');
                  
                  $validation = DB::table('exam_mcq_response')->join('exam_mcq_questions','exam_mcq_response.idQuestion','exam_mcq_questions.idQuestions')->select('exam_mcq_response.marks','exam_mcq_response.response','exam_mcq_questions.question','exam_mcq_questions.questionType','exam_mcq_questions.answerA','exam_mcq_questions.answerB','exam_mcq_questions.answerC','exam_mcq_questions.answerD','exam_mcq_questions.answerCorrect','exam_mcq_response.isPublished')->where('idStudent',$student->idStudent)->where('idExam', $idExam)->get(); 


                  return json_encode(array(
                        'results' => $results,
                        'markings' => $validation
                  )); 

              }else {
                $validation = DB::table('exam_mcq_response')
                    ->join('exam_mcq_questions','exam_mcq_response.idQuestion','exam_mcq_questions.idQuestions')
                    ->select('exam_mcq_response.marks','exam_mcq_response.response','exam_mcq_questions.question','exam_mcq_questions.questionType','exam_mcq_questions.answerA','exam_mcq_questions.answerB','exam_mcq_questions.answerC','exam_mcq_questions.answerD','exam_mcq_questions.answerCorrect','exam_mcq_response.isPublished')
                    ->where('idStudent',$student->idStudent)
                    ->where('idExam', $idExam)
                    ->get(); 
                if($validation == null){
                    return json_encode(array(
                        'results' => $results,
                        'markings' =>array()
                    )); 
                }
                $marksScored = 0;
                foreach ($validation as $result) {
                    $marksScored = $marksScored + $result->marks;
                }
                if (\App\McqResult::where('idStudent',$student->idStudent)->where('idExam', $idExam)->doesntExist()) {
                    $mcq = new \App\McqResult();
                    $mcq->idStudent = $student->idStudent;
                    $mcq->idFinancialYear = $student->idFinancialYear;
                    $mcq->idSchool = $student->idSchool;
                    $mcq->idClass = $student->idClass;
                    $mcq->idSection = $student->idSection;
                    $mcq->idSchool = $student->idSchool;
                    $mcq->idExam = $idExam;
                    $mcq->idSubject = DB::table('exam_mcq')->where('idMcq',$idExam)->first()->idSubject;
                    $mcq->marks = $marksScored;
                    $mcq->save();
                }  
                return json_encode(array(
                        'results' => $results,
                        'markings' => array(),
                        "message" => "Result not published but publishing now check after a minutes."
                ));      
            }   
                 

        }else{
             return json_encode(array());
        }
    }
    
    public function getExams($id,$limit){
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
              $exams = \App\ExamMcq::where('idFinancialYear','=',$student->idFinancialYear)
       					->where('idSchool','=',$student->idSchool)
                        ->where(function($query) use ($student) {
                            $query->whereRaw('idSection IS NULL AND idClass = ?', [$student->idClass]);
                            $query->orWhereRaw('idSection = ? AND idClass = ?', [$student->idSection,$student->idClass]);
                        })
                        ->orderBy('examDate', 'desc')
       					->skip($limit)
                        ->take($limit+20)
                        ->get();
                return json_encode($exams);        
        }else{
             return json_encode(array());
        }
    }

    public function getExamsV2($id){
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
              $exams = \App\ExamMcq::select('exam_mcq.*',DB::raw('(SELECT COUNT(*) FROM exam_mcq_response WHERE idStudent = '.$id.' AND idExam = exam_mcq.idMcq) as result'))->where('idFinancialYear','=',$student->idFinancialYear)
       					->where('idSchool','=',$student->idSchool)
       					->whereRaw('idSection IS NULL AND idClass = ?', [$student->idClass])
       					->orWhereRaw('idSection = ? AND idClass = ?', [$student->idSection,$student->idClass])
                        ->orderBy('examDate', 'desc')
       					->paginate();
              return json_encode($exams);        
        }else{
             return json_encode(array());
        }
    }
    
    public function submitExam(Request $request){

        $data = $request->all();
        $student = "";
        $exam = "";
        $resuls ="";

        $marksScored = 0;
        foreach ($data as $result) {
            $marksObtained = 0;
            if ($student == "" || $exam == "" || $resuls == "") {
                $student = \App\AdmEntry::where('idStudent', '=', $result['idStudent'])->first();
                $exam = \App\ExamMcq::where('idMcq', '=', $result['idMcq'])->first();
                $resuls = \App\McqResult::where('idStudent',$student->idStudent)->where('idExam',$exam->idMcq)->first();
                if(isset($resuls->idResult)){
                    return json_encode(['message' => "Exam is already submitted"], 200);
                }
            }

            $questions = \App\ExamQuestions::where('idQuestions', '=', $result['idQuestions'])->first();

            if($result['userResponse'] == $questions->answerCorrect){
                $marksObtained = $questions->marks;
                $marksScored = $marksScored + $questions->marks;
            }

            if (DB::table('exam_mcq_response')->where('idStudent',$student->idStudent)->where('idQuestion', $questions->idQuestions)->doesntExist()) {


                $isPublished = "N";
                $type = DB::table('exam_mcq_questions')->select("questionType")->where('idQuestions', $questions->idQuestions)->first();
                if($type->questionType == "mcq" ||$type->questionType == "math_type" || $type->questionType == "images_questions" || $type->questionType == "question_image" || $type->questionType == "image_image"){
                    $isPublished = "Y";
                }

                DB::table('exam_mcq_response')->insert([
                    [
                        'idQuestion' => $questions->idQuestions, 
                        'idExam' => $result['idMcq'], 
                        'idStudent' => $student->idStudent,
                        'marks'=>$marksObtained,
                        'response'=>$result['userResponse'],
                        'isPublished'=>$isPublished
                    ]
                ]);

            }else{
                return json_encode(['message' => "Exam is already submitted"], 200);
            } 
        }
        
        if (\App\McqResult::where('idStudent',$student->idStudent)->where('idExam', $exam->idMcq)->doesntExist()) {
            $mcq = new \App\McqResult();
            $mcq->idStudent = $student->idStudent;
            $mcq->idFinancialYear = $student->idFinancialYear;
            $mcq->idSchool = $student->idSchool;
            $mcq->idClass = $student->idClass;
            $mcq->idSection = $student->idSection;
            $mcq->idSchool = $student->idSchool;
            $mcq->idExam = $exam->idMcq;
            $mcq->idSubject = $exam->idSubject;
            $mcq->marks = $marksScored;
            $mcq->save();
        }

        return json_encode(['message' => "Exam is successfully submitted"], 200);
    }

    public function uploadExamResult(Request $request,$id){
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        $questions = \App\ExamQuestions::where('idQuestions', '=', $request->idQuestion)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
            if ($request->hasFile('exam')) {
                $nw = 'mcq_'.$id.'_result_' . $questions->idQuestions . '.' . $request->file('exam')->getClientOriginalExtension();
                $request->file('exam')->storeAs('public/schools/' . $school->idSchool . '/mcq/', $nw);
            }
            return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
        }else{
            return response()->json(['success' => "FAILED"], 200, ['app-status' => 'success']);
        }
    }

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

            $isSubmitted = DB::table('home_files')->where('idTopic',$request->id)
                                                  ->where('idStudent',$request->idStudent)
                                                  ->where('idType',$request->type)
                                                  ->first();
            if($isSubmitted != null){
                return response()->json(['success' => "ALREADY SAVED"], 200, ['app-status' => 'success']);
            }                                      

            $documents = null;
            if($request->type == "H"){
                $documents = \App\Homework::where('idHomework', '=', $request->id)->first();    
            }else if($request->type == "P"){
                $documents = \App\PracticeSet::where('idSet', '=', $request->id)->first();
            }else{

            }
            $documents->submit_student = $documents->submit_student + 1;
            $documents->update();
            $nw = "";
            if ($request->hasFile('pdfFile')) {
                $nw = 'document_'.$request->type.'_' .$request->idStudent. '.' . $request->file('pdfFile')->getClientOriginalExtension();
                $request->file('pdfFile')->storeAs('public/schools/' . $school->idSchool . '/documents/', $nw);
            }

            if (DB::table('home_files')->insert([
                [
                    'idStudent' => $request->idStudent,
                    'idTopic' => $request->id,
                    'idType' => $request->type,
                    'fileLocation' => $nw
                ]
            ]))
            return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
            else return response()->json(['success' => "FAILED"], 200, ['app-status' => 'success']);
        }else{
            return response()->json(['success' => "FAILED"], 200, ['app-status' => 'success']);
        }
    }
    
    public function getQuestions($id){
        $questions = \App\ExamQuestions::leftJoin('mcq_paragraph','exam_mcq_questions.idParagraph','mcq_paragraph.idParagraph')
        ->select('idQuestions','question','answerA','answerB','answerC','answerD','questionType','marks','paraText')
        ->where('exam_mcq_questions.idMcq', '=', $id)
        ->orderBy('idQuestions','asc')
        ->get();
        foreach ($questions as $key => $question) {
            if($question['questionType'] == "math_type"){
                  $latex = str_replace('exponentialE','mathrm{e}',$question['question']);
                  $latexNext = str_replace('imaginaryI','mathrm{i}',$latex);
                  $questions[$key]['question']  = $latexNext;
            }
        }
        return json_encode($questions);
    }
    
    public function getDetails() {
        $user=Auth::guard('student-api')->user();
        $profile = DB::table('students')
                   ->join('schools', 'students.idSchool', '=', 'schools.idSchool')
                   ->join('classes', 'students.idClass', '=', 'classes.idClass')
                   ->join('sections', 'students.idSection', '=', 'sections.idSection')
                   ->join('financial_years', 'students.idFinancialYear', '=', 'financial_years.idFinancialYear')
                   ->select('students.isActive','schools.schoolName', 'schools.telephone','schools.email','classes.className','sections.sectionName','students.firstName','students.middleName','students.lastName','students.studentDob','students.studentPob','students.gender','students.aadhaarNo','students.bloodGroup','students.resAddress','students.resCity','students.resPincode','students.resTelephone','students.idStudent','students.idSchool','students.idFinancialYear','students.admissionNo','students.idClass','students.idSection','students.ecNo','students.photo','financial_years.financialYearName','students.motherTounge','students.bloodGroup','students.contactPerson','students.father_fname','students.father_lname','students.father_dob','students.father_qualification','students.father_occupation','students.father_designation','students.father_company','students.father_workloc','students.father_panno','students.father_telephone','students.father_mobile','students.father_email','students.mother_fname','students.mother_lname','students.mother_dob','students.mother_qualification','students.mother_occupation','students.mother_designation','students.mother_company','students.mother_workloc','students.mother_telephone','students.mother_mobile','students.mother_email','students.isEditable')
                   ->whereRaw('father_mobile = ? OR mother_mobile = ?', [$user->mobile,$user->mobile])->where('students.isActive','Y')->get();

        //return $profile;
        $stdProfile = array();           
        foreach ($profile as $studentDetails) {
                if( /*($studentDetails->idFinancialYear >= $this->fys($studentDetails) || $studentDetails->idSchool == 25) &&*/ $studentDetails->isActive == "Y"){
                    if(!isset($studentDetails->aadhaarNo)) $studentDetails->aadhaarNo = "NA";
                    if(!isset($studentDetails->studentPob)) $studentDetails->studentPob = "NA";
                    if(!isset($studentDetails->father_fname)) $studentDetails->father_fname = "NA";
                    if(!isset($studentDetails->father_lname)) $studentDetails->father_lname = "NA";
                    if(!isset($studentDetails->father_dob)) $studentDetails->father_dob = "NA";
                    if(!isset($studentDetails->father_qualification)) $studentDetails->father_qualification = "NA";
                    if(!isset($studentDetails->father_occupation)) $studentDetails->father_occupation = "NA";
                    if(!isset($studentDetails->father_designation)) $studentDetails->father_designation = "NA";
                    if(!isset($studentDetails->father_company)) $studentDetails->father_company = "NA";
                    if(!isset($studentDetails->father_workloc)) $studentDetails->father_workloc = "NA";
                    if(!isset($studentDetails->father_email)) $studentDetails->father_email = "NA";
                    if(!isset($studentDetails->father_mobile)) $studentDetails->father_mobile = "NA";
                    
                    if(!isset($studentDetails->mother_fname)) $studentDetails->mother_fname = "NA";
                    if(!isset($studentDetails->mother_lname)) $studentDetails->mother_lname = "NA";
                    if(!isset($studentDetails->mother_dob)) $studentDetails->mother_dob = "NA";
                    if(!isset($studentDetails->mother_qualification)) $studentDetails->mother_qualification = "NA";
                    if(!isset($studentDetails->mother_occupation)) $studentDetails->mother_occupation = "NA";
                    if(!isset($studentDetails->mother_designation)) $studentDetails->mother_designation = "NA";
                    if(!isset($studentDetails->mother_company)) $studentDetails->mother_company = "NA";
                    if(!isset($studentDetails->mother_workloc)) $studentDetails->mother_workloc = "NA";
                    if(!isset($studentDetails->mother_email)) $studentDetails->mother_email = "NA";
                  
              		array_push($stdProfile, $studentDetails);
                }
            DB::table('students')->where('idStudent',$studentDetails->idStudent)->update(['profileSwitch'=>1]);           
        }
        if(count($stdProfile) > 0)
        {
            return json_encode($stdProfile);
        }
        else{
            $profile = DB::table('students')
                   ->join('schools', 'students.idSchool', '=', 'schools.idSchool')
                   ->join('classes', 'students.idClass', '=', 'classes.idClass')
                   ->join('sections', 'students.idSection', '=', 'sections.idSection')
                   ->join('financial_years', 'students.idFinancialYear', '=', 'financial_years.idFinancialYear')
                   ->select('students.isActive','schools.schoolName', 'schools.telephone','schools.email','classes.className','sections.sectionName','students.firstName','students.middleName','students.lastName','students.studentDob','students.studentPob','students.gender','students.aadhaarNo','students.bloodGroup','students.resAddress','students.resCity','students.resPincode','students.resTelephone','students.idStudent','students.idSchool','students.idFinancialYear','students.admissionNo','students.idClass','students.idSection','students.ecNo','students.photo','financial_years.financialYearName','students.motherTounge','students.bloodGroup','students.contactPerson','students.father_fname','students.father_lname','students.father_dob','students.father_qualification','students.father_occupation','students.father_designation','students.father_company','students.father_workloc','students.father_panno','students.father_telephone','students.father_mobile','students.father_email','students.mother_fname','students.mother_lname','students.mother_dob','students.mother_qualification','students.mother_occupation','students.mother_designation','students.mother_company','students.mother_workloc','students.mother_telephone','students.mother_mobile','students.mother_email','students.isEditable')
                   ->whereRaw('father_mobile = ? OR mother_mobile = ?', [$user->mobile,$user->mobile])->where('students.isActive','Y')->orderBy('idFinancialYear','DESC')->first();
            if($profile != null){
                if(!isset($profile->aadhaarNo)) $profile->aadhaarNo = "NA";
                    if(!isset($profile->studentPob)) $profile->studentPob = "NA";
                    if(!isset($profile->father_fname)) $profile->father_fname = "NA";
                    if(!isset($profile->father_lname)) $profile->father_lname = "NA";
                    if(!isset($profile->father_dob)) $profile->father_dob = "NA";
                    if(!isset($profile->father_qualification)) $profile->father_qualification = "NA";
                    if(!isset($profile->father_occupation)) $profile->father_occupation = "NA";
                    if(!isset($profile->father_designation)) $profile->father_designation = "NA";
                    if(!isset($profile->father_company)) $profile->father_company = "NA";
                    if(!isset($profile->father_workloc)) $profile->father_workloc = "NA";
                    if(!isset($profile->father_email)) $profile->father_email = "NA";
                    if(!isset($profile->father_mobile)) $profile->father_mobile = "NA";
                    
                    if(!isset($profile->mother_fname)) $profile->mother_fname = "NA";
                    if(!isset($profile->mother_lname)) $profile->mother_lname = "NA";
                    if(!isset($profile->mother_dob)) $profile->mother_dob = "NA";
                    if(!isset($profile->mother_qualification)) $profile->mother_qualification = "NA";
                    if(!isset($profile->mother_occupation)) $profile->mother_occupation = "NA";
                    if(!isset($profile->mother_designation)) $profile->mother_designation = "NA";
                    if(!isset($profile->mother_company)) $profile->mother_company = "NA";
                    if(!isset($profile->mother_workloc)) $profile->mother_workloc = "NA";
                    if(!isset($profile->mother_email)) $profile->mother_email = "NA";
                  
              	array_push($stdProfile, $profile);
            }
            return json_encode($stdProfile);
        }
    }

    public function saveDetails(Request $request){
    	 $id = $request->idStudent;
    	 $data = (array) $request->all();
    	 unset($data['idStudent']);
    	 DB::table('students')
            ->where('idStudent', $id)
            ->update($data);
         DB::table('students')
            ->where('idStudent', $id)
            ->update(['isEditable'=>'N']);   
    	 return response()->json(['success' => 'SUCCESS'], 200, ['app-status' => 'success']);
    }
    
    public function viewHomework($id,$limit,Request $request) {
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
            if($request->get('search') != "" || $request->get('date') != ""){
                $homeworks = \App\Homework::select('homework.*',DB::raw("(SELECT idHomeFile FROM home_files WHERE idType='H' AND idStudent = ".$id." AND idTopic = homework.idHomework LIMIT 1) AS idFile"))
                ->where('idSchool', '=', $student->idSchool);
                if($request->get('search') != "")
                $homeworks->where('subject','LIKE', '%'.$request->get('search').'%');
                if($request->get('date') != ""){
                    $now  = Carbon::parse($request->get('date'));
                    $homeworks->whereDate('publishDate',$now);
                }
                $homeworks =  $homeworks->where('isPublished', 'Y')
                ->where('idFinancialYear','=',$student->idFinancialYear)
                ->where(function($query) use ($student) {
                    $query->whereNull('idStudent');
                    $query->whereRaw('idSection = ? AND idClass =? AND idStudent IS NULL', [$student->idSection,$student->idClass]);
                    $query->orWhereRaw('idSection = ? AND idClass =? AND idStudent= ?', [$student->idSection,$student->idClass,$student->idStudent]);
                })
                ->orderBy('idHomework', 'desc')
                ->skip($limit)
                ->take(20);
            }else
            $homeworks = \App\Homework::select('homework.*',DB::raw("(SELECT idHomeFile FROM home_files WHERE idType='H' AND idStudent = ".$id." AND idTopic = homework.idHomework LIMIT 1) AS idFile"))
                ->where('idSchool', '=', $student->idSchool)
                ->where('isPublished', 'Y')
                ->where('idFinancialYear','=',$student->idFinancialYear)
                ->where(function($query) use ($student) {
                    $query->whereNull('idStudent');
                    $query->whereRaw('idSection = ? AND idClass =? AND idStudent IS NULL', [$student->idSection,$student->idClass]);
                    $query->orWhereRaw('idSection = ? AND idClass =? AND idStudent= ?', [$student->idSection,$student->idClass,$student->idStudent]);
                })
                ->orderBy('idHomework', 'desc')
                ->skip($limit)
                ->take(20);
            $homeworks = $homeworks->get();
            return json_encode($homeworks);
        }else{
            return json_encode(array());
        }
        
    }
    
    public function viewHomeworkDoc($id) {
        $homework = \App\Homework::findOrFail($id);
        $path = storage_path('app/public/schools/' . $homework->idSchool . '/homeworks/' . $homework->homeworkFile);
        return response()->file($path);
    }
    
    public function viewShortStories($id,$limit) {
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
         $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
            $stories = \App\ShortStory::where('idSchool', '=', $student->idSchool)
        ->where('isPublished', '=', 'Y')
                        ->whereOr('idClass', '=', $student->idClass)
                        ->where('idFinancialYear','=',$student->idFinancialYear)
                        ->orderBy('idStory', 'desc')
                        ->skip($limit)
                        ->take($limit+20)
                        ->get();
            return json_encode($stories);
        }else{
            return json_encode(array());
        }
        
    }
    
    
    public function viewExamResults($id,$limit) {
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
         $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
            $exams = \App\ExamType::leftJoin('exam_results','exam_types.idExamType', 'exam_results.idExamType')
       					->where('exam_types.idFinancialYear','=',$student->idFinancialYear)
       					->where('exam_types.idSchool','=',$student->idSchool)
       					->where('exam_results.ecNo','=',$student->ecNo)
                        ->skip($limit)
                        ->take($limit+20)
                        ->get();
            return json_encode($exams);
        }else{
            return json_encode(array());
        }
        
    }

     public function viewExamDoc($id) {
        $exams = \App\ExamResult::join('exam_types','exam_results.idExamType', 'exam_types.idExamType')
        ->where('exam_results.idResult','=',$id)->first();
        if($exams->idClass == "232")
        {
            $path = storage_path('app/public/schools/' . $exams->idSchool . '/results/' . $exams->typeName . '/' . substr($exams->ecNo,3). '.pdf');
        }else{
            $path = storage_path('app/public/schools/' . $exams->idSchool . '/results/' . $exams->typeName . '/' . $exams->ecNo. '.pdf');
        }
        return response()->file($path);
    }
    
    
    public function viewShortStoriesLong($id) {
        $stories = \App\ShortStory::where('idStory', '=', $id)
                        ->get()->first();
       return json_encode($stories);
    }


    public function downloadGallery($id) {
            $photos = \App\Gallery::findOrFail($id);
            $school = \App\School::where('idSchool', '=', $photos->idSchool)->first();
            if($school->isActive == 'Y'){
            $folderName=\App\GalleryFolder::where('idFolder', '=', $photos->idFolder)->value('folderName');
            $path = storage_path('app/public/schools/' . $photos->idSchool . '/galleries/' . $folderName. '/' .$photos->image);
            return response()->file($path); 
            }else{
            return json_encode(array());
        	}      
        }
    
    public function viewGallery($id,$limit, Request $request) {
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
            $folders = \App\GalleryFolder::join('gallery','gallery_folder.idFolder', 'gallery.idFolder')->select('gallery_folder.*')
            ->where('gallery.idFinancialYear','=',$student->idFinancialYear)
            ->where('gallery.idSchool', '=', $student->idSchool)
            ->distinct('idFolder')
            ->orderBy('gallery_folder.updated_at', 'desc')
            ->get();
            if($request->get('idClass') != "" || $request->get('date') != "" ){
                $folders = \App\GalleryFolder::join('gallery','gallery_folder.idFolder', 'gallery.idFolder')->select('gallery_folder.*')
                ->where('gallery.idFinancialYear','=',$student->idFinancialYear)
                ->where('gallery.idSchool', '=', $student->idSchool);
                if($request->get('idClass') != "") 
                    $folders->where('gallery.idClass', '=', $request->get('idClass'));
                if($request->get('date') != ""){
                    $now = Carbon::parse($request->get('date'));
                    $folders->whereDate('gallery_folder.updated_at',$now->format('Y-m-d'));
                } 
                $folders = $folders->distinct('idFolder')
                ->orderBy('gallery_folder.updated_at', 'desc')
                ->get();
            }
            $results = array();
            foreach($folders as $folder){
                $photos = DB::table('gallery')->where('idSchool', '=', $student->idSchool)->where('idFolder', '=', $folder->idFolder)->first();
                if($photos){
                $folder_image = array(
                    'idFolder'=>$folder->idFolder,
                    'idSchool'=>$folder->idSchool,
                    'folderName'=>$folder->folderName,
                    'image'=>$photos->image
                    );
                array_push($results, $folder_image);
                }
            }
            return json_encode($results);
        }else{
            return json_encode(array());
        }
        
    }
    
    public function viewGalleryFiles($id,$folder_id,$limit) {
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){

            $photos = \App\Gallery::where('idFolder', '=', $folder_id)
                        ->where('idSchool', '=', $student->idSchool)
                            ->orderBy('idGallery', 'desc')
                            ->skip($limit)
                            ->take($limit+20)
                            ->get();
           return json_encode($photos);
        }else{
            return json_encode(array());
        }
    }

    public function loadBook($id){
       $ebook = \App\ELibrary::where('idElibrary', '=', $id)->first();
       $path = 'http://online-login.online/storage/schools/' . $ebook->idSchool . '/e-library/' . $ebook->ePdf;
       //return response()->file($path);
       return view('schools.library.pdfviewer', compact('path'));
       //return $path;
    }

    public function getBooks($id,$limit){
    	$student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
    	$ebook = \App\ELibrary::where('idClass', '=', $student->idClass)->where('idSchool', '=', $student->idSchool)->skip($limit)
                            ->take($limit+20)
                            ->get();
           return json_encode($ebook);
        }else{
            return json_encode(array());
        }
    }
    
    public function viewNoticeboards($id,$limit,Request $request) {
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
            $student_notification = \App\Noticeboard::where('idSchool', '=', $student->idSchool)
                                    ->where('idFinancialYear','=',$student->idFinancialYear)
                                    ->where('idStudent','=',$student->idStudent);
                                                           
            if($request->get('search') != "" || $request->get('date') != ""){
                    $notices = \App\Noticeboard::where('idSchool', '=', $student->idSchool)
                    ->where('idFinancialYear','=',$student->idFinancialYear);
                    if($request->get('search') != "")
                    $notices->where('subject','LIKE', '%'.$request->get('search').'%');
                    if($request->get('date') != ""){
                        $now  = Carbon::parse($request->get('date'));
                        $notices->whereDate('publishDate',$now);
                    }
                    $notices = $notices->where(function($query) use ($student) {
                        $query->orwhereRaw(' ( idClass IS NULL AND idSection IS NULL)')
                        ->orwhereRaw(' ( idClass=? AND idSection IS NULL)',[$student->idClass])
                        ->orWhereRaw(' ( idClass=? AND idSection=?)',[$student->idClass,$student->idSection]);
                    })       
                    ->union($student_notification)
                    ->where('isPublished', '=', 'Y')
                    ->orderBy('idNoticeboard', 'desc');
            }else
                $notices = \App\Noticeboard::where('idSchool', '=', $student->idSchool)
                ->where('idFinancialYear','=',$student->idFinancialYear)
                ->where(function($query) use ($student) {
                    $query->orwhereRaw(' ( idClass IS NULL AND idSection IS NULL)')
                    ->orwhereRaw(' ( idClass=? AND idSection IS NULL)',[$student->idClass])
                    ->orWhereRaw(' ( idClass=? AND idSection=?)',[$student->idClass,$student->idSection]);
                })       
                ->union($student_notification)
                ->where('isPublished', '=', 'Y')
                ->orderBy('idNoticeboard', 'desc');
                
            $notices = $notices ->skip($limit)
                            ->take(20)->get();
            return json_encode($notices);
        }else{
            return json_encode(array());
        }
        
    }
    
    public function viewNoticeboardsDocs($id) {
        $notice = \App\Noticeboard::findOrFail($id);
        $path = storage_path('app/public/schools/' . $notice->idSchool . '/noticeboard/' . $notice->noticeFile);
        return response()->file($path);
    }
    
    public function viewCalender($id) {
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
            $holidays = \App\Holiday::where('idSchool', '=', $student->idSchool)->where('idFinancialYear','=',$student->idFinancialYear)->get();
            return json_encode($holidays);
        }else{
            return json_encode(array());
        }
        
    }
    
    public function viewPositiveNews($id,$limit) {
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
             $positive_news = \App\PositiveNews::where('idSchool', '=', $student->idSchool)->where('isPublished', '=', 'Y')
                         ->where('idFinancialYear','=',$student->idFinancialYear)
                         ->where(function($query) use ($student) {
                            $query->whereRaw('(idClass=? or idClass IS NULL)',[$student->idClass]);
                        })    
                        ->orderBy('idNews', 'desc')->skip($limit)->take(20)->get();
            return json_encode($positive_news);
        }else{
            return json_encode(array());
        }
       
    }
    
    public function viewThoughts($id,$limit) {
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
            $thoughts = \App\WeekThought::where('idSchool', '=', $student->idSchool)
                        ->where('idFinancialYear','=',$student->idFinancialYear)
                        ->where('isPublished', '=', 'Y')
                        ->where(function($query) use ($student) {
                            $query->whereRaw('(idClass=? or idClass IS NULL)',[$student->idClass]);
                        })  
                        ->orderBy('idThought', 'desc')
                        ->skip($limit)->take(20)->get();
            return json_encode($thoughts);
        }else{
            return json_encode(array());
        }
        
    }
    
    public function viewNewsLetter($id,$limit) {
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
            $newsletters = \App\NewsLetter::where('idSchool', '=', $student->idSchool)
                            ->where('isPublished', '=', 'Y')
                            ->where('idFinancialYear','=',$student->idFinancialYear)
                            ->where(function($query) use ($student) {
                                $query->whereRaw('(idClass=? or idClass IS NULL)',[$student->idClass]);
                            })
                            ->orderBy('idNewsletter', 'desc')->skip($limit)->take(20)->get();
                       if($school->idSchool != 14){
                        	for ($k= 0; $k < count($newsletters);$k++) {
                        		$newsletters[$k]['videoKey'] = $newsletters[$k]['videoLink'];
            					$newsletters[$k]['videoLink'] = "https://www.youtube.com/embed/".$newsletters[$k]['videoLink'];
            					
                        	}
                       }
                        
            return json_encode($newsletters);
        }else{
            return json_encode(array());
        }
        
    }


    public function getStudentSubjects($id){
 		$student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        $subjects = \App\Subject::where('idSchool', '=', $student->idSchool)->where('idClass',$student->idClass)->where('idFinancialYear','=',$student->idFinancialYear)->get();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
        	return json_encode($subjects);
        }else{
            return json_encode(array());
        }
    }
    
    public function viewNewsLetterSearch($filter,$id,$limit) {
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
       
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
             if($filter != "none")
                {
                    if(substr($filter, 0,1) == "0"){
                         $newsletters = \App\NewsLetter::where('idSchool', '=', $student->idSchool)->where('subjectName', 'LIKE', substr($filter,1)."%")
                            ->where('isPublished', '=', 'Y')
                            ->where('idFinancialYear',$student->idFinancialYear)
                            ->where(function($query) use ($student) {
                                $query->whereRaw('(idClass=? or idClass IS NULL)',[$student->idClass]);
                            })
                            ->orderBy('idNewsletter', 'desc')->skip($limit)->take(20)->get();
                    }else {
                         $newsletters = \App\NewsLetter::where('idSchool', '=', $student->idSchool)->where('title', 'LIKE', $filter."%")
                            ->where('isPublished', '=', 'Y')
                            ->where('idFinancialYear',$student->idFinancialYear)
                            ->where(function($query) use ($student) {
                                $query->whereRaw('(idClass=? or idClass IS NULL)',[$student->idClass]);
                            })
                            ->orderBy('idNewsletter', 'desc')->skip($limit)->take(20)->get();
                    }
                   
                }
                else {
                    $newsletters = \App\NewsLetter::where('idSchool', '=', $student->idSchool)
                    ->where('isPublished', '=', 'Y')
                    ->where('idFinancialYear','=',$student->idFinancialYear)
                    ->where(function($query) use ($student) {
                        $query->whereRaw('(idClass=? or idClass IS NULL)',[$student->idClass]);
                    })
                    ->orderBy('idNewsletter', 'desc')->skip($limit)->take(20)->get();
                    }           
                        
                       if($school->idSchool != 14){
                        	for ($k= 0; $k < count($newsletters);$k++) {
                        		$newsletters[$k]['videoKey'] = $newsletters[$k]['videoLink'];
            					$newsletters[$k]['videoLink'] = "https://www.youtube.com/embed/".$newsletters[$k]['videoLink'];
                        	}
                       }
                        
            return json_encode($newsletters);
            
        }else{
            return json_encode(array());
        }
        
    }
    
    public function viewPracticeSet($id,$limit,Request $request) {
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
            if($request->get('search') != "" || $request->get('date') != ""){
                $psets = \App\PracticeSet::select('practice_sets.*',DB::raw("(SELECT idHomeFile FROM home_files WHERE idType='P' AND idStudent = ".$id." AND idTopic = practice_sets.idSet) AS idFile"))->where('idSchool', '=', $student->idSchool)
                ->where('isPublished', '=', 'Y');
                if($request->get('search') != "")
                    $psets->where('subject','LIKE', '%'.$request->get('search').'%');
                if($request->get('date') != ""){
                        $now  = Carbon::parse($request->get('date'));
                        $psets->whereDate('publishDate',$now);
                }
                $psets = $psets->where('idClass', '=', $student->idClass)
                ->where('idSection', '=', $student->idSection)
                ->whereOr('idStudent', '=', $student->idStudent)
                ->where('idFinancialYear','=',$student->idFinancialYear)
                ->orderBy('idSet', 'desc')
                ->skip($limit)
                ->take($limit+20);
            }else
            $psets = \App\PracticeSet::select('practice_sets.*',DB::raw("(SELECT idHomeFile FROM home_files WHERE idType='P' AND idStudent = ".$id." AND idTopic = practice_sets.idSet) AS idFile"))->where('idSchool', '=', $student->idSchool)
                ->where('isPublished', '=', 'Y')
                ->where('idClass', '=', $student->idClass)
                ->where('idSection', '=', $student->idSection)
                ->whereOr('idStudent', '=', $student->idStudent)
                ->where('idFinancialYear','=',$student->idFinancialYear)
                ->orderBy('idSet', 'desc')
                ->skip($limit)
                ->take($limit+20);
            $psets = $psets->get();
            return json_encode($psets);
        }else{
            return json_encode(array());
        }
        
    }
    
    public function viewTimetable($id) {
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
            $timetable=DB::table('timetable')
                ->rightJoin('periods', 'timetable.idPeriod', '=', 'periods.idPeriod')
                ->leftJoin('employees', 'timetable.idEmployee', '=', 'employees.idEmployee')
                ->leftJoin('subjects', 'timetable.idSubject', '=', 'subjects.idSubject')
                ->select('timetable.idPeriod', 'timetable.idWeekday', 'timetable.idEmployee', 'timetable.idSubject', 'periods.periodName', 'periods.fromTime', 'periods.toTime', 'periods.isLunchBreak','employees.firstName','employees.lastName','subjects.subjectName')
                ->where('periods.idClass', '=', $student->idClass)
                ->where('periods.idSection', '=', $student->idSection)
                ->get();                
         return json_encode($timetable); 
        }else{
            return json_encode(array());
        }
            
    }
    
    public function viewWishes($id){
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
            $birthday=DB::table('birthday_response')
                ->where('idStudent', '=', $id)
                ->where('idFy', '=', $student->idFinancialYear)->get();
            return json_encode($birthday);
        }else{
            return json_encode(array());
        }
    }

    public function viewBirthdays($id){
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
            $birthday=DB::table('students')
                ->join('classes', 'students.idClass', '=', 'classes.idClass')
                ->join('sections', 'students.idSection', '=', 'sections.idSection')
                ->select('students.firstName','students.middleName','students.lastName','students.studentDob','students.gender','students.idStudent','classes.className','sections.sectionName')
                ->whereRaw("DATE_FORMAT((students.studentDob),'%m-%d') = DATE_FORMAT(UTC_TIMESTAMP(),'%m-%d')")
                ->where('students.idSchool', '=', $student->idSchool)
                ->where('students.idClass', '=', $student->idClass)
                ->where('students.idSection', '=', $student->idSection)->get();
            return json_encode($birthday);
        }else{
            return json_encode(array());
        }
        
    }

    var $pg = array([
        "idSchool" => 140,
        "pg" => "easebuzz",
        "isActive" => "Y"
    ],[
        "idSchool" => 159,
        "pg" => "easebuzz",
        "isActive" => "Y"
    ],[
        "idSchool" => 160,
        "pg" => "easebuzz",
        "isActive" => "Y"
    ],[
        "idSchool" => 135,
        "pg" => "easebuzz",
        "isActive" => "Y"
    ],[
        "idSchool" => 163,
        "pg" => "easebuzz",
        "isActive" => "Y"
    ],[
        "idSchool" => 181,
        "pg" => "easebuzz",
        "isActive" => "Y"
    ],[
        "idSchool" => 183,
        "pg" => "easebuzz",
        "isActive" => "Y"
    ],[
        "idSchool" => 39,
        "pg" => "easebuzz",
        "isActive" => "Y"
    ]);
    
    public function getInstallmentFull($id,Request $request,$payment_link){
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        $fy = array();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
            
            $class_feeheads = \App\FeeHead::where('idClass', '=', $student->idClass)
                ->where('idSection', '=', $student->idSection)
                ->where('studentCategory', '=', $student->studentType)
                ->where('idFinancialYear','=',$student->idFinancialYear)
                ->whereNull('idStudent')
                ->get();
            $allcat_feeheads = \App\FeeHead::where('idClass', '=', $student->idClass)
                    ->where('idSection', '=', $student->idSection)
                    ->where('idFinancialYear','=',$student->idFinancialYear)
                    ->where('studentCategory', '=', 'All')
                    ->whereNull('idStudent')
                    ->get();
            $std_feeheads = \App\FeeHead::where('idStudent', '=', $student->idStudent)->where('idFinancialYear','=',$student->idFinancialYear)->get();
            $feeheads = new \Illuminate\Database\Eloquent\Collection; //Create empty collection which we know has the merge() method
            $feeheads = $feeheads->merge($class_feeheads);
            $feeheads = $feeheads->merge($std_feeheads);
            $feeheads = $feeheads->merge($allcat_feeheads)->sortBy('toDate', 1);
            $feeheads=$feeheads->sort(function ($a, $b) {
                return strtotime($a->toDate) - strtotime($b->toDate);
            });           
            
            $transaction = new \Illuminate\Database\Eloquent\Collection; //Create empty collection which we know has the merge() method
            
            $paidfees = \App\StudentTransaction::where('idStudent', '=', $id)->where('idFinancialYear','=',$student->idFinancialYear)
            ->where(function($query) {
                $query->whereNull('status');
                $query->orWhere('status', '=', 'In-Process');
                $query->orWhere('status', '=', 'Cleared');
                $query->orWhere('status', '=', 'Success');
            })
            ->get();
            /*$k =0;
            foreach($paidfees as $var){
                //$paidfees[$k]->totalPaid = strval($var->totalPaid - $var->fine);
                $k++;
            }*/
            $lessfees = \App\LesserTransaction::where('idStudent', '=', $id)->where('idFinancialYear','=',$student->idFinancialYear)
            ->select('lesser_transaction.*','lesser_transaction.idLesserTransaction as idTransaction')
            ->where(function($query) {
                $query->whereNull('status');
                $query->orWhere('status', '=', 'In-Process');
                $query->orWhere('status', '=', 'Cleared');
                $query->orWhere('status', '=', 'Success');
            })
            ->where('totalPaid','>',0)
            ->get();

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

            foreach($transaction as $transact){
                $feeHead = \App\StudentTransactionDetail::join('feeheads', 'student_transaction_details.idFeehead', '=', 'feeheads.idFeehead')->where('idTransaction', '=', $transact->idTransaction)->first();
                if($feeHead != null)
                if($feeHead->idFinancialYear > 244){
                    if(str_contains($feeHead->feeheadName, "Full Payment") || $feeHead->feeheadName == "Plan A (Full Payment)"){
                        $transaction[] = json_decode(json_encode (array(
                            "type" => "book",
                            "idTransaction" => $transact->idTransaction."00",
                            "receiptNo" => "BOOK".$transact->idTransaction."MH",
                            "totalPaid" => "0.00",
                            "paymentDate" => $transact->paymentDate,
                            "paymentMode" => $transact->paymentMode,
                            "fine" => $transact->fine
                        )), FALSE);
                        break;
                    }                    
                }
            }
            
            $discountfees = DB::table('student_discounts')->where('idStudent', '=', $id)->where('idFinancialYear','=',$student->idFinancialYear)->where('isActive', 'Y')->get();
            $feeheaders=array();
            $isPaid = 0;
            $paymode = 2;
            foreach($feeheads as $key => $value)
            {
                 $headerObject=json_decode($value,true);
                 $headerObject['isPaid']='Due';
                 $headerObject['partial'] = 0;
                 $discount = 0;
                 foreach($discountfees as $items){
                    if($items->idFeehead == $headerObject['idFeehead']){
                        $headerObject['amount'] = $headerObject['amount'] - $items->amount;
                    }
                 }
                 
                 $already_paid_feehead = \App\StudentTransactionDetail::join('student_transaction','student_transaction_details.idTransaction','=','student_transaction.idTransaction')->where('student_transaction_details.idStudent', '=', $id)
                                    ->where('student_transaction_details.idFeehead', '=', $headerObject['idFeehead'])->where(function($query) {
                                $query->whereNull('student_transaction_details.status');
                                $query->orWhere('student_transaction_details.status', '=', 'In-Process');
                                $query->orWhere('student_transaction_details.status', '=', 'Cleared');
                                $query->orWhere('student_transaction_details.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 != null){
                            $headerFine = \App\StudentTransactionDetail::where('idFeehead',$headerObject['idFeehead'])->where('idTransaction',$already_paid_feehead->idTransaction)->first();
                            if($headerFine != null){
                                $headerObject['fine'] = $headerFine->fine;
                                $headerObject['amount'] = $headerObject['amount'] + $headerFine->fine;
                            }
                            $headerObject['isPaid']='Paid';
                            $isPaid++;
                        }
                        if(str_contains($headerObject['feeheadName'], "Full Payment")){
                            $paymode = 1;
                        }
                    }else if($already_paid_feehead->amountPaid > $headerObject['amount'])
                    {
                        $fee_transaction = \App\StudentTransaction::where('idTransaction',$already_paid_feehead->idTransaction)->first();
                        if($fee_transaction != null){
                            if($headerObject['amount'] == ($already_paid_feehead->amountPaid - $fee_transaction->fine)){
                                $headerObject['isPaid']='Paid';
                                $isPaid++;
                                $headerFine = \App\StudentTransactionDetail::where('idFeehead',$headerObject['idFeehead'])->where('idTransaction',$already_paid_feehead->idTransaction)->first();
                                if($headerFine != null){
                                    $headerObject['fine'] = $headerFine->fine;
                                    $headerObject['amount'] = $headerObject['amount'] + $headerFine->fine;
                                }
                            }
                            
                        }
                        if(str_contains($headerObject['feeheadName'], "Full Payment")){
                            $paymode = 1;
                        }
                    }
                    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';
                                        $headerObject['partial']=$partialAmount;
                                        $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';
                                    $headerObject['partial']=$partialAmount;
                                    $isPaid++;
                                } 
                            elseif($partialAmount > $headerObject['amount']  )    
                            {
                                $headerObject['fine'] = $partialAmount - $headerObject['amount'];
                                $headerObject['amount'] = $partialAmount;
                                $headerObject['isPaid']='Paid';
                                $isPaid++;
                            } 
                            else $headerObject['isPaid']='Due';
                        }else  $headerObject['isPaid']='Due'; 
                    }  
                }  
               

                if(str_contains($headerObject['feeheadName'], "Full Payment")){
                    $startDate = Carbon::parse($headerObject['fromDate']);
                    $now = Carbon::now();
                    $dueDiff = $startDate->diffInDays($now, false);
                    $headerObject['isEnabled'] = ($dueDiff > -1);
                    if($dueDiff > -1){
                        $startDate = Carbon::parse($headerObject['toDate'].' 23:59:59');
                        $now = Carbon::now();
                        $dueDiff = $startDate->diffInDays($now, false);
                        if($dueDiff >= 1)
                        $headerObject['isEnabled'] = false;
                    }
                    array_push($feeheaders,$headerObject);
                }else{
                    $startDate = Carbon::parse($headerObject['fromDate']);
                    $now = Carbon::now();
                    $dueDiff = $startDate->diffInDays($now, false);
                    $headerObject['isEnabled'] = ($dueDiff > -1);
                    if($dueDiff > -1){
                        $endDate = Carbon::parse($headerObject['toDate'].' 23:59:59');
                        $now = Carbon::now();
                        $endDiff = $endDate->diffInDays($now, false);
                        $headerObject['isEnabled'] = ($endDiff < 0);
                        if($student->idSchool == 160){
                            $headerObject['isEnabled'] = true;
                        }
                        if($student->idSchool == 140 && str_contains($headerObject['feeheadName'], "Second Installment")){
                            $headerObject['isEnabled'] = true;
                        }
                        if($student->idSchool == 135 && $headerObject['isEnabled'] == false){
                            $headerObject['isEnabled'] = true;
                        }
                    }

                    if(!str_contains($headerObject['feeheadName'], "environment")){
                       // if($student->idSchool == 135) $headerObject['isEnabled'] = false;
                    }
                    array_push($feeheaders,$headerObject);
                }
                
                
            }

            $feePayment = array();
            //return json_encode($feeheaders);
            foreach($feeheaders as $headers){
                if(str_contains($headers['feeheadName'], "Admission") && $headers['isPaid'] == "Due"){
                    return json_encode(array(
                        "fees" => [$headers],
                        "paidFee" => $transaction,
                        "discount" => $discountfees,
                        "forceFee" => $fy,
                        'payment_link' => $payment_link,
                        "pg" => $this->pg
                    )); 
                }else{
                    if(str_contains($headers['feeheadName'], "environment")){
                        array_push($feePayment,$headers);
                    }
                    if(str_contains($headers['feeheadName'], "Admission") && $headers['isPaid'] == "Paid"){
                        array_push($feePayment,$headers);
                    }
                    if(str_contains($headers['feeheadName'], "P1") && $headers['isPaid'] == "Paid"){
                        array_push($feePayment,$headers);
                    }
                    if(str_contains($headers['feeheadName'], "Full Payment") && $request->get('paymentType') == 1){
                        array_push($feePayment,$headers);
                    }else
                    if(str_contains($headers['feeheadName'], "First Installment") && $request->get('paymentType') == 2 && ($headers['isPaid'] == "Due" || $headers['isPaid'] == "Partial Paid")){
                        array_push($feePayment,$headers);
                    }else if(str_contains($headers['feeheadName'], "First Installment") && $request->get('paymentType') == 2 && $headers['isPaid'] == "Paid"){
                        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'], "First Installment") && $request->get('paymentType') == 2 && $headers['isPaid'] == "Due" && $student->idSchool != 140){
                    if($student->idSchool != 135 && $student->idSchool != 181  && $student->idSchool != 183)
                    return json_encode(array(
                        "fees" => $feePayment,
                        "paidFee" => $transaction,
                        "discount" => $discountfees,
                        "forceFee" => $fy,
                        "pg" => $this->pg,
                        'payment_link' => $payment_link
                    )); 
                }else if(str_contains($headers['feeheadName'], "P1")  && $request->get('paymentType') == 2 && $headers['isPaid'] == "Due"){
                    $headers['isForceCheck'] = true;
                    array_push($feePayment,$headers);
                    /*return json_encode(array(
                        "fees" => $feePayment,
                        "paidFee" => $transaction,
                        "discount" => $discountfees,
                        "forceFee" => $fy,
                        "pg" => $this->pg,
                        'payment_link' => $payment_link
                    )); */
                }else if(str_contains($headers['feeheadName'], "P1")  && $request->get('paymentType') == 1 && $headers['isPaid'] == "Due" ){
                    $headers['isForceCheck'] = true;
                    array_push($feePayment,$headers);
                    return json_encode(array(
                        "fees" => $feePayment,
                        "paidFee" => $transaction,
                        "discount" => $discountfees,
                        "forceFee" => $fy,
                        "pg" => $this->pg,
                        'payment_link' => $payment_link
                    )); 
                }else if(str_contains($headers['feeheadName'], "P2")  && $request->get('paymentType') == 2 && $headers['isPaid'] == "Due"){
                    $headers['isForceCheck'] = true;
                    array_push($feePayment,$headers);
                    return json_encode(array(
                        "fees" => $feePayment,
                        "paidFee" => $transaction,
                        "discount" => $discountfees,
                        "forceFee" => $fy,
                        "pg" => $this->pg,
                        'payment_link' => $payment_link
                    )); 
                }else if(str_contains($headers['feeheadName'], "P2")  && $request->get('paymentType') == 1 && $headers['isPaid'] == "Due"){
                    $headers['isForceCheck'] = true;
                    array_push($feePayment,$headers);
                    return json_encode(array(
                        "fees" => $feePayment,
                        "paidFee" => $transaction,
                        "discount" => $discountfees,
                        "forceFee" => $fy,
                        "pg" => $this->pg,
                        'payment_link' => $payment_link
                    )); 
                }
            }

            if($request->get('paymentType') == 1 ){
                $paymentHeaders = array();
                foreach($feeheaders as $headers){
                    if(!str_contains($headers['feeheadName'], "Installment")){
                        array_push($paymentHeaders,$headers);
                    }
                }
                return json_encode(array(
                    "fees" => $paymentHeaders,
                    "paidFee" => $transaction,
                    "discount" => $discountfees,
                    "forceFee" => $fy,
                    "pg" => $this->pg,
                    'payment_link' => $payment_link
                ));
            }else if($request->get('paymentType') == 2 ){
                $paymentHeaders = array();
                foreach($feeheaders as $headers){
                    if(!str_contains($headers['feeheadName'], "Full Payment")){
                        array_push($paymentHeaders,$headers);
                    }
                }
                return json_encode(array(
                    "fees" => $paymentHeaders,
                    "paidFee" => $transaction,
                    "discount" => $discountfees,
                    "forceFee" => $fy,
                    "pg" => $this->pg,
                    'payment_link' => $payment_link
                ));
            }
            
            return json_encode(array(
                "fees" => $feeheaders,
                "paidFee" => $transaction,
                "discount" => $discountfees,
                "forceFee" => $fy,
                "pg" => $this->pg,
                'payment_link' => $payment_link
            )); 
        }else{
            return json_encode(array(
                "forceFee" => $fy,
                "pg" => $this->pg,
                "fees" => [],
                'payment_link' => $payment_link
            ));
        }
    }

    public function getCombinedDetails($id,Request $request){
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
            //fetch financial Year
            $fy = array();
            $fetchSession = \App\FinancialYear::where('idSchool',$student->idSchool)->get();
            foreach($fetchSession as $session){
                $promotions = \App\AdmEntry::where('idSchool', '=', $student->idSchool)
                ->where('father_mobile','=',$student->father_mobile)
                ->where('father_fname','=',$student->father_fname)
                ->where('ecNo','=',$student->ecNo)
                ->where('idFinancialYear','=',$session->idFinancialYear)
                ->first();
                if($promotions != null)
                array_push($fy,array(
                    "id" => $promotions->idStudent,
                    "yearName" => $session->financialYearName,
                    "idFinancialYear" => $promotions->idFinancialYear
                ));
            }

            if(count($fy) == 0){
                $currentFy = \App\FinancialYear::where('idFinancialYear',$student->idFinancialYear)->first();
                if($currentFy != null)
                array_push($fy,array(
                    "id" => $id,
                    "yearName" => $currentFy->financialYearName,
                    "idFinancialYear" => $currentFy->idFinancialYear
                ));
            }

            $plan = "";
            //Select Plan
            $paymodes = array();
            $feeheaders = [];
            $summary = [
                "feeTotal" => 0,
                "discount" => 0,
                "fine" => 0,
                "additional" => 0,
                "penaltyAmt" => 0,
                "paidFine" => 0,
                "totalAmount" => 0,
                "balance" => 0,
                "paidfees" => 0
            ];
            $k =0;
            if($school->idSchool == 25){
                if($plan == ""){
                    $plana_class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                                                ->where('idSection', '=', $student->idSection)
                                                ->where('idFinancialYear', '=', $student->idFinancialYear)
                                                ->where('studentCategory', '=', $student->studentType)
                                                ->where('feeheadLabel', 'LIKE', 'Plan A%')
                                                ->whereNull('idStudent');
                                                    //   ->get();
                    $plana_allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                                                            ->where('idSection', '=', $student->idSection)
                                                            ->where('studentCategory', '=', 'All')
                                                            ->where('idFinancialYear', '=', $student->idFinancialYear)
                                                            ->where('feeheadLabel', 'LIKE', 'Plan A%')
                                                            ->whereNull('idStudent');
                                                    //   ->get();
                    $plana_feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                                                            ->where('idFinancialYear', '=', $student->idFinancialYear)
                                                            ->where('feeheadLabel', 'LIKE', 'Plan A%')
                                                            ->union($plana_class_feeheads)
                                                            ->union($plana_allcat_feeheads)
                                                            ->orderBy('toDate')
                                                            ->get();
                    $afeetotal = $plana_feeheads->sum('amount');
                    array_push($paymodes,array(
                        'feeheadName' => 'Fees in Full Payment',
                        'isPaid' => 'Plan A',
                        'amount'=> $afeetotal
                    ));
                    $planb_class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                                                ->where('idSection', '=', $student->idSection)
                                                ->where('idFinancialYear', '=', $student->idFinancialYear)
                                                ->where('studentCategory', '=', $student->studentType)
                                                ->where('feeheadLabel', 'LIKE', 'Plan B%')
                                                ->whereNull('idStudent');
                                                //   ->get();
                                                $planb_allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                                                        ->where('idSection', '=', $student->idSection)
                                                        ->where('studentCategory', '=', 'All')
                                                        ->where('idFinancialYear', '=', $student->idFinancialYear)
                                                        ->where('feeheadLabel', 'LIKE', 'Plan B%')
                                                        ->whereNull('idStudent');
                                                //   ->get();
                                                $planb_feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                                                        ->where('idFinancialYear', '=', $student->idFinancialYear)
                                                        ->where('feeheadLabel', 'LIKE', 'Plan B%')
                                                        ->union($planb_class_feeheads)
                                                        ->union($planb_allcat_feeheads)
                                                        ->orderBy('toDate')
                                                        ->get();
                                                $bfeetotal = $planb_feeheads->sum('amount');
                                                array_push($paymodes,array(
                                                    'feeheadName' => 'Fees in Terms',
                                                    'isPaid' => 'Plan B',
                                                    'amount' => $bfeetotal
                                                ));
                    $planc_class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                                                ->where('idSection', '=', $student->idSection)
                                                ->where('idFinancialYear', '=', $student->idFinancialYear)
                                                ->where('studentCategory', '=', $student->studentType)
                                                ->where('feeheadLabel', 'LIKE', 'Plan C%')
                                                ->whereNull('idStudent');
                                                //   ->get();
                                                $planc_allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                                                        ->where('idSection', '=', $student->idSection)
                                                        ->where('studentCategory', '=', 'All')
                                                        ->where('idFinancialYear', '=', $student->idFinancialYear)
                                                        ->where('feeheadLabel', 'LIKE', 'Plan C%')
                                                        ->whereNull('idStudent');
                                                //   ->get();
                                                $planc_feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                                                        ->where('idFinancialYear', '=', $student->idFinancialYear)
                                                        ->where('feeheadLabel', 'LIKE', 'Plan C%')
                                                        ->union($planc_class_feeheads)
                                                        ->union($planc_allcat_feeheads)
                                                        ->orderBy('toDate')
                                                        ->get();
                                                $cfeetotal = $planc_feeheads->sum('amount');   
                                                array_push($paymodes,array(
                                                    'feeheadName' => 'Fees in Installments',
                                                    'isPaid' => 'Plan C',
                                                    'amount'=> $cfeetotal
                                                ));   
                }
                $feeheaders = PaymentCalculation::calculateFee($student,$request);
                foreach($feeheaders as $var){
                    $summary['feeTotal'] = $summary['feeTotal'] + $var['amount'];
                    $summary['discount'] = $summary['discount'] + $var['discount'];
                    $summary['fine'] = $summary['fine'] + $var['fine'];
                    $summary['paidFine'] = $summary['paidFine'] + $var['transaction']['paid_fine'];
                    $summary['totalAmount'] = $summary['totalAmount'] + $var['total_amount'];
                    $summary['balance'] = $summary['balance'] + $var['balance'];
                    $summary['paidfees'] = $summary['paidfees'] + $var['transaction']['paid'];
                    if($var['isPaid'] == "Partial Paid"){
                        $feeheaders[$k]['isEnabled'] = false;
                    }
                    $k++;
                }
            }else{
                $class_feeheads = \App\FeeHead::where('idClass', '=', $student->idClass)
                ->where('idSection', '=', $student->idSection)
                ->where('studentCategory', '=', $student->studentType)
                ->where('idFinancialYear','=',$student->idFinancialYear)
                ->whereNull('idStudent')
                ->get();
                $allcat_feeheads = \App\FeeHead::where('idClass', '=', $student->idClass)
                        ->where('idSection', '=', $student->idSection)
                        ->where('idFinancialYear','=',$student->idFinancialYear)
                        ->where('studentCategory', '=', 'All')
                        ->whereNull('idStudent')
                        ->get();
                $std_feeheads = \App\FeeHead::where('idStudent', '=', $student->idStudent)->where('idFinancialYear','=',$student->idFinancialYear)->get();
                $feeheads = new \Illuminate\Database\Eloquent\Collection; //Create empty collection which we know has the merge() method
                $feeheads = $feeheads->merge($class_feeheads);
                $feeheads = $feeheads->merge($std_feeheads);
                $feeheads = $feeheads->merge($allcat_feeheads)->sortBy('toDate', 1);
                $feeheads=$feeheads->sort(function ($a, $b) {
                    return strtotime($a->toDate) - strtotime($b->toDate);
                });
                $feeheaders=array();
                if($student->idSchool == 140 || $student->idSchool == 135 || $student->idSchool == 159 || $student->idSchool == 160 || $student->idSchool == 139){
                    if($plan == ""){
                        array_push($paymodes,array(
                            'feeheadName' => 'Fees in Full Payment',
                            'isPaid' => '1',
                            'amount'=> "0"
                        )); 
                        array_push($paymodes,array(
                            'feeheadName' => 'Fees in Installments',
                            'isPaid' => '2',
                            'amount'=> "0"
                        ));   
                    }
                    $feeheaders = PaymentCalculation::calculateMhws($feeheads,$student,$request);
                }
            }

            //Fetch payment transaction
            $transaction = new \Illuminate\Database\Eloquent\Collection; //Create empty collection which we know has the merge() method
            if($request->get('transaction') != "" && $request->get('transaction') != null){
                $paidfees = \App\StudentTransaction::where('idStudent', '=', $id)->get();
                $lessfees = \App\LesserTransaction::where('idStudent', '=', $id)->get();
            }else{
                $paidfees = \App\StudentTransaction::where('idStudent', '=', $id)->where(function($query) {
                    $query->whereNull('status');
                    $query->orWhere('status', '=', 'In-Process');
                    $query->orWhere('status', '=', 'Cleared');
                    $query->orWhere('status', '=', 'Success');
                })->get();
                $lessfees = \App\LesserTransaction::where('idStudent', '=', $id)->where(function($query) {
                    $query->whereNull('status');
                    $query->orWhere('status', '=', 'In-Process');
                    $query->orWhere('status', '=', 'Cleared');
                    $query->orWhere('status', '=', 'Success');
                })->get();
            }
            $transaction = $transaction->merge($lessfees);
            $transaction = $transaction->merge($paidfees);
            if($student->idSchool == 140 || $student->idSchool == 135 || $student->idSchool == 159 || $student->idSchool == 160 || $student->idSchool == 139){
                foreach($transaction as $transact){
                    $feeHead = \App\StudentTransactionDetail::join('feeheads', 'student_transaction_details.idFeehead', '=', 'feeheads.idFeehead')->where('idTransaction', '=', $transact->idTransaction)->first();
                    if($feeHead != null)
                    if($feeHead->idFinancialYear > 244){
                        if(str_contains($feeHead->feeheadName, "Full Payment") || $feeHead->feeheadName == "Plan A (Full Payment)"){
                            $transaction[] = json_decode(json_encode (array(
                                "type" => "book",
                                "idTransaction" => $transact->idTransaction."00",
                                "receiptNo" => "BOOK".$transact->idTransaction."MH",
                                "totalPaid" => "0.00",
                                "paymentDate" => $transact->paymentDate,
                                "paymentMode" => $transact->paymentMode,
                                "fine" => $transact->fine
                            )), FALSE);
                            break;
                        }                    
                    }
                }
            }

            //Fetch Dicount
            $discountfees = DB::table('student_discounts')->where('idStudent', '=', $id)->where('isActive', 'Y')->get();
            return json_encode(array(
                "paymode" => $paymodes,
                "fees" => $feeheaders,
                "forceFee" => $fy,
                "paidFee" => $transaction,
                "discount" => $discountfees,
                "summary" => $summary
            ));
        }
    }

    public function getRoyalFee($id,Request $request,$payment_link){
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
            /*$outstanding = \DB::table('feeheads')->where('feeheadName','Outstanding Payment')->where('idStudent',$id)->first();
            if($outstanding != null){
                $details = \App\StudentTransactionDetail::where('idFeehead',$outstanding->idFeehead)->first();
                if($details == null){
                    return json_encode(array(
                        "paymode" => [],
                        "fees" => [],
                        "forceFee" => [],
                        "paidFee" => [],
                        "summary" => [],
                        "discount" => [],
                        'payment_link' => $payment_link
                    ));
                }
            }*/

            $fetchSession = \App\FinancialYear::where('idSchool',$student->idSchool)->get();
            $fy = array();
            foreach($fetchSession as $session){
                $promotions = \App\AdmEntry::where('idSchool', '=', $student->idSchool)
                ->where('father_mobile','=',$student->father_mobile)
                ->where('father_fname','=',$student->father_fname)
                ->where('ecNo','=',$student->ecNo)
                ->where('idFinancialYear','=',$session->idFinancialYear)
                ->first();
                if($promotions != null)
                array_push($fy,array(
                    "id" => $promotions->idStudent,
                    "yearName" => $session->financialYearName,
                    "idFinancialYear" => $promotions->idFinancialYear
                ));
            }
            $summary = [
                "feeTotal" => 0,
                "discount" => 0,
                "fine" => 0,
                "additional" => 0,
                "penaltyAmt" => 0,
                "paidFine" => 0,
                "totalAmount" => 0,
                "balance" => 0,
                "paidfees" => 0
            ];
            $k =0;
            $feeheaders = PaymentCalculation::calculateFee($student,$request);
            foreach($feeheaders as $var){
                $summary['feeTotal'] = $summary['feeTotal'] + $var['amount'];
                $summary['discount'] = $summary['discount'] + $var['discount'];
                $summary['fine'] = $summary['fine'] + $var['fine'];
                $summary['paidFine'] = $summary['paidFine'] + $var['transaction']['paid_fine'];
                $summary['totalAmount'] = $summary['totalAmount'] + $var['total_amount'];
                $summary['balance'] = $summary['balance'] + $var['balance'];
                $summary['paidfees'] = $summary['paidfees'] + $var['transaction']['paid'];
                
                if($var['isPaid'] == "Partial Paid"){
                    $feeheaders[$k]['isEnabled'] = false;
                }
                $k++;
            }

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

                    if($plan != '') break;
                }
            }
            /*
            $type = '';
            if($request->get('paymode') != '' && $plan == ''){
                $type = $request->get('paymode');
                $class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                ->where('idSection', '=', $student->idSection)
                ->where('idFinancialYear','=', $student->idFinancialYear)
                ->where('studentCategory', '=', $student->studentType)
                ->where('feeheadLabel', 'LIKE', $type.'%')
                ->whereNull('idStudent');
                $allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                        ->where('idSection', '=', $student->idSection)
                        ->where('studentCategory', '=', 'All')
                        ->where('idFinancialYear','=', $student->idFinancialYear)
                        ->where('feeheadLabel', 'LIKE', $type.'%')
                        ->whereNull('idStudent');
                $feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                        ->where('idFinancialYear','=', $student->idFinancialYear)
                        ->where('feeheadLabel', 'LIKE', $type.'%')
                        ->union($class_feeheads)
                        ->union($allcat_feeheads)
                        ->orderBy('idFeehead','ASC')
                        ->orderBy('toDate')
                        ->get()->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)
                        ->orderBy('idFeehead','ASC')
                        ->orderBy('toDate')
                        ->get()->toArray();
            }*/
            
            
            $transaction = new \Illuminate\Database\Eloquent\Collection; //Create empty collection which we know has the merge() method
            if($request->get('transaction') != "" && $request->get('transaction') != null){
                $paidfees = \App\StudentTransaction::where('idStudent', '=', $id)->get();
                $lessfees = \App\LesserTransaction::where('idStudent', '=', $id)->get();
            }else{
                $paidfees = \App\StudentTransaction::where('idStudent', '=', $id)->where(function($query) {
                    $query->whereNull('status');
                    $query->orWhere('status', '=', 'In-Process');
                    $query->orWhere('status', '=', 'Cleared');
                    $query->orWhere('status', '=', 'Success');
                })->get();
                $lessfees = \App\LesserTransaction::where('idStudent', '=', $id)->where(function($query) {
                    $query->whereNull('status');
                    $query->orWhere('status', '=', 'In-Process');
                    $query->orWhere('status', '=', 'Cleared');
                    $query->orWhere('status', '=', 'Success');
                })->get();
            }
            $transaction = $transaction->merge($lessfees);
            $transaction = $transaction->merge($paidfees);
            
            $discountfees = DB::table('student_discounts')->where('idStudent', '=', $id)->where('isActive', 'Y')->get();
            /*$feeheaders=array();
            foreach($feeheads as $feehead)
            {
                 $headerObject = (array)$feehead;
                 $discount = 0;
                 $summary['feeTotal'] = $summary['feeTotal'] + $headerObject['amount'];
                 foreach($discountfees as $items){
                    if($items->idFeehead == $headerObject['idFeehead']){
                        $headerObject['amount'] = $headerObject['amount'] - $items->amount;
                        $summary['discount'] = $summary['discount'] + $items->amount;
                        $discount  = $items->amount;
                    }
                 }
                 $already_paid_feehead = \App\StudentTransactionDetail::where('idStudent', '=', $id)
                                    ->where('idFeehead', '=', $headerObject['idFeehead'])->where(function($query) {
                                $query->whereNull('status');
                                $query->orWhere('status', '=', 'In-Process');
                                $query->orWhere('status', '=', 'Cleared');
                                $query->orWhere('status', '=', 'Success');
                            })->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();
                $startDate = Carbon::parse($headerObject['fromDate']);
                $date = Carbon::parse($headerObject['toDate']);

                                    $now = Carbon::now();
                                        $lastPayDate = \App\StudentTransactionDetail::join('student_transaction','student_transaction_details.idTransaction','=','student_transaction.idTransaction')->where('student_transaction_details.idStudent','=',$id)
                                        ->where('idFeehead','=',$headerObject['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');
                                     })->select('student_transaction.paymentDate')->orderBy('student_transaction.idTransaction','DESC')->first();

                                        if($lastPayDate == null){
                                            $lastPayDate = \App\LesserTransactionDetail::join('lesser_transaction','lesser_transaction_details.idLesserTransaction','=','lesser_transaction.idLesserTransaction')->where('lesser_transaction_details.idStudent','=',$id)
                                            ->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($lastPayDate != null){
                                                $now = Carbon::parse($lastPayDate->paymentDate);
                                            }else{
                                                $now = Carbon::now();
                                            }
                                        }else{
                                            $now = Carbon::parse($lastPayDate->paymentDate);
                                        }

                $dueDiff = $startDate->diffInDays($now, false);
                $diff = $date->diffInDays($now, false);
                $headerObject['isEnabled'] = ($dueDiff > -1);

                if( $diff > 0){
                    if($headerObject['fine'] == "0.00"){
                        if($now->format('M') != $date->format('M')){
                            $now->addMonth();
                            $months = $now->diffInMonths($date);
                            $headerObject['fine'] = ($headerObject['flatFine'] * $months);
                            $summary['fine'] = $summary['fine'] + $headerObject['fine'];
                        }else{
                            $headerObject['fine'] = $headerObject['flatFine'];
                            $summary['fine'] = $summary['fine'] + $headerObject['fine'];
                        }
                    }
                }

                if($already_paid_feehead){    
                    $headerObject['pay_type'] = "full";       
                    $summary['paidFine'] = $summary['paidFine'] + $already_paid_feehead->fine;  
                    $summary['paidfees'] = $summary['paidfees'] + $already_paid_feehead->amountPaid;      
                    if($discount == 0){
                        $summary['discount'] = $summary['discount'] + $already_paid_feehead->discount;
                    } 
                    if($already_paid_feehead->amountPaid >= $headerObject['amount']){
                        $headerObject['isPaid']='Paid';
                        $headerObject['isEnabled'] = false;
                    }                            
                    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'), DB::raw('SUM(lesser_transaction_details.discount) as discount'))
                        ->first();
                        if($partial_paid){ 
                                $headerObject['isEnabled'] = false;  
                                $headerObject['pay_type'] = "less";     
                                $partialAmount=0;    
                                $partialAmount=$partialAmount+$partial_paid->totalPaid;

                                if($discount == 0){
                                    $summary['discount'] = $summary['discount'] + $partial_paid->discount;
                                } 
                                $summary['paidFine'] = $summary['paidFine'] + $partial_paid->fine;  
                                $summary['paidfees'] = $summary['paidfees'] + $partial_paid->totalPaid;  
                                        
                                if($partial_paid->totalPaid - $partial_paid->fine >= $headerObject['amount'])    
                                $headerObject['isPaid']='Paid';  
                                else  if($partialAmount >0)    
                                $headerObject['isPaid']='Partial Paid'; 
                            else  $headerObject['isPaid']='Due';
                        } else  {
                            $headerObject['pay_type'] = "not-paid";  
                            $headerObject['isPaid']='Due';
                        }
                }
                array_push($feeheaders,$headerObject);
            }
            $summary['totalAmount'] = $summary['feeTotal'] + $summary['paidFine'] - $summary['discount'];
            $summary['balance'] = $summary['totalAmount'] - $summary['paidfees'];*/
            return json_encode(array(
                "paymode" => [],
                "current_plan" => $plan,
                "fees" => $feeheaders,
                "forceFee" => $fy,
                "paidFee" => $transaction,
                "discount" => $discountfees,
                "summary" => $summary,
                'payment_link' => $payment_link
            ));
        }
    }


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

        if($student->idSchool == 25){
            if($student->studentType == "2025-26" || $student->studentType == "2025-26 (2/YF)"){
                $class_feeheads = \App\ExtraFeehead::whereNull('idClass')->where('extra_feehead.idSchool', '=', $student->idSchool)
                ->where('extra_feehead.type', '=', 'Online')
                ->where('extra_feehead.idFinancialYear','=', $student->idFinancialYear);
                $feeheaders = \App\ExtraFeehead::where('idClass', '=', $student->idClass)
                ->where('extra_feehead.idSchool', '=', $student->idSchool)
                ->where('extra_feehead.type', '=', 'Online')
                ->where('extra_feehead.idFinancialYear','=', $student->idFinancialYear)
                ->union($class_feeheads)
                ->get(); 
            }else{
                $class_feeheads = \App\ExtraFeehead::whereNull('idClass')->where('extra_feehead.idSchool', '=', $student->idSchool)
                ->where('extra_feehead.type', '=', 'Online')
                ->where('idExtraFeehead','!=',484)
                ->where('extra_feehead.idFinancialYear','=', $student->idFinancialYear);
                $feeheaders = \App\ExtraFeehead::where('idClass', '=', $student->idClass)
                ->where('extra_feehead.idSchool', '=', $student->idSchool)
                ->where('extra_feehead.type', '=', 'Online')
                ->where('idExtraFeehead','!=',484)
                ->where('extra_feehead.idFinancialYear','=', $student->idFinancialYear)
                ->union($class_feeheads)
                ->get(); 
            }
        }else{
            $class_feeheads = \App\ExtraFeehead::whereNull('idClass')->where('extra_feehead.idSchool', '=', $student->idSchool)
            ->where('extra_feehead.idFinancialYear','=', $student->idFinancialYear);
            $feeheaders = \App\ExtraFeehead::where('idClass', '=', $student->idClass)
            ->where('extra_feehead.idSchool', '=', $student->idSchool)
            ->where('extra_feehead.idFinancialYear','=', $student->idFinancialYear)
            ->union($class_feeheads)
            ->get(); 
        }
        

        
        $transaction = \App\StudentExtraTransaction::select('student_transaction_extra.*','student_transaction_extra_details.idFeehead')
        ->leftJoin('student_transaction_extra_details', 'student_transaction_extra.idTransaction', '=', 'student_transaction_extra_details.idTransaction')->where('student_transaction_extra.idStudent', '=', $id);
        if($request->get('transaction') != "" && $request->get('transaction') != null){
            $transaction = $transaction->where('student_transaction_extra.idFinancialYear','=', $student->idFinancialYear)->get();
        }
        else $transaction = $transaction->where(function($query) {
            $query->whereNull('student_transaction_extra.status');
            $query->orWhere('student_transaction_extra.status', '=', 'In-Process');
            $query->orWhere('student_transaction_extra.status', '=', 'Cleared');
            $query->orWhere('student_transaction_extra.status', '=', 'Success');
        })->where('student_transaction_extra.idFinancialYear','=', $student->idFinancialYear)->get();  

        return json_encode(array(
                "paymode" => [],
                "fees" => $feeheaders,
                "forceFee" => $fy,
                "paidFee" => $transaction
            ));    
    }

    function guidv4($data = null) {
        // Generate 16 bytes (128 bits) of random data or use the data passed into the function.
        $data = $data ?? random_bytes(16);
        assert(strlen($data) == 16);
    
        // Set version to 0100
        $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
        // Set bits 6-7 to 10
        $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
    
        // Output the 36 character UUID.
        return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
    }
    
    public function getFeeDetails($id,Request $request) {
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $payment_link = 'https://online-login.online/payment-overview/';
        if($student->idSchool == 140 || $student->idSchool == 135 || $student->idSchool == 159 || $student->idSchool == 160 || $student->idSchool == 139 || $student->idSchool == 181 || $student->idSchool == 183 || $student->idSchool == 39){
            return $this->getInstallmentFull($id,$request,$payment_link);
        }else if($student->idSchool == 25){
            if($request->get('paymode') != null){
                return $this->getRoyalFee($id,$request,$payment_link);
            }else{
                $fetchSession = \App\FinancialYear::where('idFinancialYear','>=',$student->idFinancialYear)->get();
                $fy = array();
                foreach($fetchSession as $session){
                    $promotions = \App\AdmEntry::where('idSchool', '=', $student->idSchool)
                    ->where('father_mobile','=',$student->father_mobile)
                    ->where('father_fname','=',$student->father_fname)
                    ->where('ecNo','=',$student->ecNo)
                    ->where('idFinancialYear','=',$session->idFinancialYear)
                    ->first();
                    if($promotions != null)
                    array_push($fy,array(
                        "id" => $promotions->idStudent,
                        "yearName" => $session->financialYearName,
                        "idFinancialYear" => $promotions->idFinancialYear
                    ));
                }
                $plan = '';
                $paidfees = \App\StudentTransaction::where('idStudent', '=', $student->idStudent)
                ->where(function($query) {
                    $query->whereNull('status');
                    $query->orWhere('status', '=', 'In-Process');
                    $query->orWhere('status', '=', 'Cleared');
                    $query->orWhere('status', '=', 'Success');
                })->get();

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

                        if($plan != '') break;
                    }
                }
                if($plan != '') return $this->getRoyalFee($id,$request,$payment_link);
            }
            $paymodes = array();
            $plana_class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                                            ->where('idSection', '=', $student->idSection)
                                            ->where('idFinancialYear', '=', $student->idFinancialYear)
                                            ->where('studentCategory', '=', $student->studentType)
                                            ->where('feeheadLabel', 'LIKE', 'Plan A%')
                                            ->whereNull('idStudent');
                                            //   ->get();
            $plana_allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                                                    ->where('idSection', '=', $student->idSection)
                                                    ->where('studentCategory', '=', 'All')
                                                    ->where('idFinancialYear', '=', $student->idFinancialYear)
                                                    ->where('feeheadLabel', 'LIKE', 'Plan A%')
                                                    ->whereNull('idStudent');
                                            //   ->get();
            $plana_feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                                                    ->where('idFinancialYear', '=', $student->idFinancialYear)
                                                    ->where('feeheadLabel', 'LIKE', 'Plan A%')
                                                    ->union($plana_class_feeheads)
                                                    ->union($plana_allcat_feeheads)
                                                    ->orderBy('toDate')
                                                    ->get();
            $afeetotal = $plana_feeheads->sum('amount');
            array_push($paymodes,array(
                'feeheadName' => 'Fees in Full Payment',
                'isPaid' => 'Plan A',
                'amount'=> $afeetotal
            ));
            $planb_class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                                            ->where('idSection', '=', $student->idSection)
                                            ->where('idFinancialYear', '=', $student->idFinancialYear)
                                            ->where('studentCategory', '=', $student->studentType)
                                            ->where('feeheadLabel', 'LIKE', 'Plan B%')
                                            ->whereNull('idStudent');
                                            //   ->get();
                                            $planb_allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                                                    ->where('idSection', '=', $student->idSection)
                                                    ->where('studentCategory', '=', 'All')
                                                    ->where('idFinancialYear', '=', $student->idFinancialYear)
                                                    ->where('feeheadLabel', 'LIKE', 'Plan B%')
                                                    ->whereNull('idStudent');
                                            //   ->get();
                                            $planb_feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                                                    ->where('idFinancialYear', '=', $student->idFinancialYear)
                                                    ->where('feeheadLabel', 'LIKE', 'Plan B%')
                                                    ->union($planb_class_feeheads)
                                                    ->union($planb_allcat_feeheads)
                                                    ->orderBy('toDate')
                                                    ->get();
                                            $bfeetotal = $planb_feeheads->sum('amount');
                                            array_push($paymodes,array(
                                                'feeheadName' => 'Fees in Terms',
                                                'isPaid' => 'Plan B',
                                                'amount' => $bfeetotal
                                            ));
                $planc_class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                                            ->where('idSection', '=', $student->idSection)
                                            ->where('idFinancialYear', '=', $student->idFinancialYear)
                                            ->where('studentCategory', '=', $student->studentType)
                                            ->where('feeheadLabel', 'LIKE', 'Plan C%')
                                            ->whereNull('idStudent');
                                            //   ->get();
                                            $planc_allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                                                    ->where('idSection', '=', $student->idSection)
                                                    ->where('studentCategory', '=', 'All')
                                                    ->where('idFinancialYear', '=', $student->idFinancialYear)
                                                    ->where('feeheadLabel', 'LIKE', 'Plan C%')
                                                    ->whereNull('idStudent');
                                            //   ->get();
                                            $planc_feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                                                    ->where('idFinancialYear', '=', $student->idFinancialYear)
                                                    ->where('feeheadLabel', 'LIKE', 'Plan C%')
                                                    ->union($planc_class_feeheads)
                                                    ->union($planc_allcat_feeheads)
                                                    ->orderBy('toDate')
                                                    ->get();
                                            $cfeetotal = $planc_feeheads->sum('amount');   
                                            array_push($paymodes,array(
                                                'feeheadName' => 'Fees in Installments',
                                                'isPaid' => 'Plan C',
                                                'amount'=> $cfeetotal
                                            ));                             
            return json_encode(array(
                "fees" => [],
                "paidFee" => [],
                "forceFee" => $fy,
                "paymode" => $paymodes,
                'payment_link' => $payment_link
            ));
        }
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
            $fetchSession = \App\FinancialYear::where('idFinancialYear','>=',$student->idFinancialYear)->get();
            $fy = array();
            $paymodes = [];
            $summary = [
                "feeTotal" => 0,
                "discount" => 0,
                "fine" => 0,
                "additional" => 0,
                "penaltyAmt" => 0,
                "paidFine" => 0,
                "totalAmount" => 0,
                "balance" => 0,
                "paidfees" => 0
            ];
            $plana_class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                                            ->where('idSection', '=', $student->idSection)
                                            ->where('idFinancialYear', '=', $student->idFinancialYear)
                                            ->where('studentCategory', '=', $student->studentType)
                                            ->whereNull('idStudent');
                                            //   ->get();
            $plana_allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                                                    ->where('idSection', '=', $student->idSection)
                                                    ->where('studentCategory', '=', 'All')
                                                    ->where('idFinancialYear', '=', $student->idFinancialYear)
                                                    ->whereNull('idStudent');
                                            //   ->get();
            $plana_feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                                                    ->where('idFinancialYear', '=', $student->idFinancialYear)
                                                    ->union($plana_class_feeheads)
                                                    ->union($plana_allcat_feeheads)
                                                    ->orderBy('toDate')
                                                    ->get();
            $afeetotal = $plana_feeheads->sum('amount');
            array_push($paymodes,array(
                'feeheadName' => 'Fees',
                'isPaid' => 'Full',
                'amount'=> $afeetotal
            ));
            $summary['feeTotal'] = $afeetotal;
            $summary['totalAmount'] = $afeetotal;
            foreach($fetchSession as $session){
                    $promotions = \App\AdmEntry::where('idSchool', '=', $student->idSchool)
                    ->where('father_mobile','=',$student->father_mobile)
                    ->where('father_fname','=',$student->father_fname)
                    ->where('ecNo','=',$student->ecNo)
                    ->where('idFinancialYear','=',$session->idFinancialYear)
                    ->first();
                if($promotions != null)
                array_push($fy,array(
                    "id" => $promotions->idStudent,
                    "yearName" => $session->financialYearName,
                    "idFinancialYear" => $promotions->idFinancialYear
                ));
            }
            $class_feeheads = \App\FeeHead::where('idClass', '=', $student->idClass)
                ->where('idSection', '=', $student->idSection)
                ->where('studentCategory', '=', $student->studentType)
                ->where('idFinancialYear','=',$student->idFinancialYear)
                ->whereNull('idStudent')
                ->get();
            $allcat_feeheads = \App\FeeHead::where('idClass', '=', $student->idClass)
                    ->where('idSection', '=', $student->idSection)
                    ->where('idFinancialYear','=',$student->idFinancialYear)
                    ->where('studentCategory', '=', 'All')
                    ->whereNull('idStudent')
                    ->get();
            $std_feeheads = \App\FeeHead::where('idStudent', '=', $student->idStudent)->where('idFinancialYear','=',$student->idFinancialYear)->get();
         
            $feeheads = new \Illuminate\Database\Eloquent\Collection; //Create empty collection which we know has the merge() method
            $feeheads = $feeheads->merge($class_feeheads);
            $feeheads = $feeheads->merge($std_feeheads);
            $feeheads = $feeheads->merge($allcat_feeheads)->sortBy('toDate', 1);
            $feeheads=$feeheads->sort(function ($a, $b) {
                return strtotime($a->toDate) - strtotime($b->toDate);
            });
            
            
            $transaction = new \Illuminate\Database\Eloquent\Collection; //Create empty collection which we know has the merge() method
            
            $paidfees = \App\StudentTransaction::where('idStudent', '=', $id)->get();
            $lessfees = \App\LesserTransaction::where('idStudent', '=', $id)->get();
            
            $transaction = $transaction->merge($lessfees);
            $transaction = $transaction->merge($paidfees);
            
            $discountfees = DB::table('student_discounts')->where('idStudent', '=', $id)->where('isActive', 'Y')->get();
            $feeheaders=array();
            foreach($feeheads as $key => $value)
            {
                 $headerObject=json_decode($value,true);
                 $discount = 0;
                 foreach($discountfees as $items){
                    if($items->idFeehead == $headerObject['idFeehead']){
                        $headerObject['amount'] = $headerObject['amount'] - $items->amount;
                        $summary['discount'] = $summary['discount'] + $items->amount;
                    }
                 }
                 $already_paid_feehead = \App\StudentTransactionDetail::where('idStudent', '=', $id)
                                    ->where('idFeehead', '=', $headerObject['idFeehead'])->where(function($query) {
                                $query->whereNull('status');
                                $query->orWhere('status', '=', 'In-Process');
                                $query->orWhere('status', '=', 'Cleared');
                                $query->orWhere('status', '=', 'Success');
                            })->first();

                if($already_paid_feehead){                    
                    if($already_paid_feehead->amountPaid == $headerObject['amount']){
                        $summary['paidfees'] = $summary['paidfees'] + $already_paid_feehead->amountPaid;
                        $headerObject['isPaid']='Paid';
                    }else{
                        $partial_paid =  DB::table('lesser_transaction')
                        ->join('lesser_transaction_details', 'lesser_transaction_details.idLesserTransaction', '=', 'lesser_transaction.idLesserTransaction')
                        ->where('lesser_transaction.idStudent', '=', $student->idStudent)
                        ->where('lesser_transaction.idFinancialYear', '=', $student->idFinancialYear)
                        ->where('idFeehead', $headerObject['idFeehead'])
                        ->where(function($query) {
                            $query->whereNull('lesser_transaction.status');
                            $query->orWhere('lesser_transaction.status', '=', 'Cleared');
                            $query->orWhere('lesser_transaction.status', '=', 'In-Process');
                            $query->orWhere('lesser_transaction.status', '=', 'Success');
                        })
                        ->select(DB::raw('SUM(totalPaid) as totalPaid'), DB::raw('SUM(lesser_transaction_details.fine) as fine'))
                        ->first();
                            if(isset($partial_paid->totalPaid)){ 
                                $summary['paidfees'] = $summary['paidfees'] + $partial_paid->totalPaid;

                                $partialAmount=0;    
                                $partialAmount=$partialAmount+$partial_paid->totalPaid;
                                        
                                if($partialAmount >0)    
                                    $headerObject['isPaid']='Partial Paid'; 
                                else  $headerObject['isPaid']='Due';
                            }
                        else  $headerObject['isPaid']='Due'; 
                        }
                } else  
                $headerObject['isPaid']='Due'; 
                array_push($feeheaders,$headerObject);
            }
            $summary['balance'] = $summary['feeTotal'] - $summary['paidfees'];
            if($request->get('paymode') != null){
                return json_encode(array(
                    "fees" => $feeheaders,
                    "paidFee" => $transaction,
                    "paymode" => [],
                    "discount" => $discountfees,
                    "summary" => $summary,
                    'payment_link' => $payment_link
                )); 
            }else{
                return json_encode(array(
                    "fees" => $feeheaders,
                    "forceFee" => $fy,
                    "paidFee" => $transaction,
                    "paymode" => $paymodes,
                    "discount" => $discountfees,
                    'payment_link' => $payment_link
                )); 
            }            
        }else{
            return json_encode(array());
        }
    }
    
    public function getSudharshanFeeDetails($id) {
         $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
         $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
            $std_feeheads = \App\NorthFeeHead::where('idStudent', '=', $student->idStudent)->where('idFinancialYear', '=', $this->fys($student))->where('isParent', '0')->where('isActive', 'Y')->where('idType', 'fee')->get();
     
            $feeheads = new \Illuminate\Database\Eloquent\Collection; //Create empty collection which we know has the merge() method
            $feeheads = $feeheads->merge($std_feeheads)->sortBy('toDate', 1);
            $feeheads=$feeheads->sort(function ($a, $b) {
                return strtotime($a->toDate) - strtotime($b->toDate);
            });
            
            $paidfees = \App\StudentTransaction::select('student_transaction.*')
            //->join('student_transaction_details','student_transaction.idTransaction','=','student_transaction_details.idTransaction')
            //->leftJoin('northfeeheads','student_transaction_details.idFeehead', '=','northfeeheads.idFeehead')
            ->where('student_transaction.idStudent', '=', $id)->where('student_transaction.idFinancialYear', '=',  $student->idFinancialYear)->get();
            $lessfees = \App\LesserTransaction::where('idStudent', '=', $id)->where('idFinancialYear', '=', $student->idFinancialYear)->get();
            $feeheaders=array();
            $fineheads=\DB::table('northfines')->where('idSchool', '=', $student->idSchool)->where('idFinancialYear', '=', $student->idFinancialYear)->get();  
            $fineAmount=0;
            $flatfine=0;
            $perDay=array();
                foreach($fineheads as $fine){
                     if($fine->isFlat==1)
                          $flatfine=$fine->amount;
                    else{
                          array_push($perDay,$fine); 
                         } 
                     }
             $now = Carbon::now();         
            foreach($feeheads as $key => $value)
            {
                 $headerObject=json_decode($value,true);
                 $child_feeheads = \App\NorthFeeHead::where('idStudent', '=', $student->idStudent)
                 ->where('isParent', $headerObject['idFeehead'])->where('idType', 'fee')->where('isActive', 'Y')->get();
                 $desc='';
                 $i=1;
                 $totalDiscount=0;
                 foreach($child_feeheads as $headers){
                    $total= $headers->amount-$headers->discount;
                    $feeheadName= \App\Header::where('idHeader', '=', $headers->idHeader)->first();
                    $desc=$desc.$i.' . '.strtoupper($feeheadName->headerName).' -  Rs. '.$total.PHP_EOL; 
                    $i++;
                    $totalDiscount=$totalDiscount+$headers->discount;
                    $headerObject['feeheadName']=$headers->demandName;
                 }
                
                 $headerObject['description']=$desc;
                 $headerObject['discount']=$totalDiscount;
                 $headerObject['amount']=$headerObject['amount']-$totalDiscount;
                 $date = Carbon::parse($headerObject['toDate']); 
                 $diff = $date->diffInDays($now,false);
                     $already_paid_feehead = \App\StudentTransactionDetail::where('idStudent', '=', $id)
                                        ->whereIn('idFeehead', $child_feeheads->pluck('idFeehead')->toArray())->where(function($query) {
                                    $query->whereNull('status');
                                    $query->orWhere('status', '=', 'In-Process');
                                    $query->orWhere('status', '=', 'Cleared');
                                    $query->orWhere('status', '=', 'Success');
                                })->first();
                    if($already_paid_feehead){                    
                        $headerObject['isPaid']='Paid';
                           $fine=\App\StudentTransaction::where('idStudent', '=', $id)->where('idTransaction', '=', $already_paid_feehead->idTransaction)->select(DB::raw('SUM(fine) as fine'))->first();
                           $headerObject['fine']=$fine->fine;
                    }else  {
                        $headerObject['isPaid']='Due'; 
                        if( $diff < 0){
                            $fineAmount=0;
                        }
                        if($headerObject['fine'] == 'flat' && $diff > 0){
                            $fineAmount=$flatfine;
                        }elseif($headerObject['fine'] == 'per' && $diff > 0){
                            if($diff > 0){
                                                 foreach($perDay as $per){
                                                    if($per->days <= $diff){
                                                        $fineAmount=$per->amount;
                                                        break;
                                                    } 
                                                 }
                                             }
                        }
                        
                        $headerObject['fine']=$fineAmount;
                    }
                        $partial_paid =  DB::table('lesser_transaction_details')
                        ->where('lesser_transaction_details.idStudent', '=', $student->idStudent)
                        ->whereIn('idFeehead', $child_feeheads->pluck('idFeehead')->toArray())
                        ->where(function($query) {
                            $query->whereNull('lesser_transaction_details.status');
                            $query->orWhere('lesser_transaction_details.status', '=', 'Cleared');
                            $query->orWhere('lesser_transaction_details.status', '=', 'In-Process');
                            $query->orWhere('lesser_transaction_details.status', '=', 'Success');
                        })
                        ->select(DB::raw('SUM(amountPaid) as totalPaid'),DB::raw('SUM(discount) as discount'), DB::raw('SUM(fine) as fine'))
                        ->first();
                    if(isset($partial_paid->totalPaid)){        
                            if($headerObject['amount']== ( $partial_paid->totalPaid + $partial_paid->discount))
                            $headerObject['isPaid']='Paid';        
                            else    
                            $headerObject['isPaid']='Partial Paid  Rs '. $partial_paid->totalPaid; 
                        }
                    array_push($feeheaders,$headerObject);
            }
            
            if( $student->idSchool == 25){
                 return json_encode(array(
                )); 
            }else{
                return json_encode(array(
                    "fees" => $feeheaders,
                    "paidFee" => $paidfees,
                    "leeFee"=>$lessfees,
                    "discount" => [],
                    "extLink"=> $school->regPaymentLink
                )); 
            }
        }else{
            return json_encode(array());
        }
        
    }
    
    public function getSudharshanBusFee($id){
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
          $std_feeheads = \App\NorthFeeHead::where('idStudent', '=', $student->idStudent)->where('idFinancialYear', '=', $this->fys($student))->where('isParent', '0')->where('isActive', 'Y')->where('idType', 'bus')->get();
     
            $feeheads = new \Illuminate\Database\Eloquent\Collection; //Create empty collection which we know has the merge() method
            $feeheads = $feeheads->merge($std_feeheads)->sortBy('toDate', 1);
            $feeheads=$feeheads->sort(function ($a, $b) {
                return strtotime($a->toDate) - strtotime($b->toDate);
            });
            
            $paidfees = \App\BusTransaction::where('idStudent', '=', $id)->where('idFinancialYear', '=', $this->fys($student))->get();
            $lessfees = \App\BusLesserTransaction::where('idStudent', '=', $id)->where('idFinancialYear', '=', $this->fys($student))->get();
            $feeheaders=array();
            $fineheads=\DB::table('northfines')->where('idSchool', '=', $student->idSchool)->where('idFinancialYear', '=', $student->idFinancialYear)->get();  
            $fineAmount=0;
            $flatfine=0;
            $perDay=array();
                foreach($fineheads as $fine){
                     if($fine->isFlat==1)
                          $flatfine=$fine->amount;
                    else{
                          array_push($perDay,$fine); 
                         } 
                     }
             $now = Carbon::now();         
            foreach($feeheads as $key => $value)
            {
                 $headerObject=json_decode($value,true);
                 $child_feeheads = \App\NorthFeeHead::where('idStudent', '=', $student->idStudent)->where('isActive', 'Y')->where('isParent', $headerObject['idFeehead'])->where('idType', 'bus')->pluck('idFeehead')->toArray();
                 $date = Carbon::parse($headerObject['toDate']); 
                 $diff = $date->diffInDays($now,false);
                     $already_paid_feehead = \App\BusTransactionDetail::where('idStudent', '=', $id)
                                        ->whereIn('idBusFeehead', $child_feeheads)->where(function($query) {
                                    $query->whereNull('status');
                                    $query->orWhere('status', '=', 'In-Process');
                                    $query->orWhere('status', '=', 'Cleared');
                                    $query->orWhere('status', '=', 'Success');
                                })->first();
                    if($already_paid_feehead){                    
                        $headerObject['isPaid']='Paid';
                           $fine=\App\BusTransaction::where('idStudent', '=', $id)->where('idBusTransaction', '=', $already_paid_feehead->idBusTransaction)->select(DB::raw('SUM(fine) as fine'))->first();
                           $headerObject['fine']=$fine->fine;
                    }else  {
                        $headerObject['isPaid']='Due'; 
                        if( $diff < 0){
                            $fineAmount=0;
                        }
                        if($headerObject['fine'] == 'flat' && $diff > 0){
                            $fineAmount=$flatfine;
                        }elseif($headerObject['fine'] == 'per' && $diff > 0){
                            if($diff > 0){
                                                 foreach($perDay as $per){
                                                    if($per->days <= $diff){
                                                        $fineAmount=$per->amount;
                                                        break;
                                                    } 
                                                 }
                                             }
                        }
                        
                        $headerObject['fine']=$fineAmount;
                    }
                        $partial_paid =  DB::table('bus_lesser_transaction_details')
                        ->where('bus_lesser_transaction_details.idStudent', '=', $student->idStudent)
                        ->whereIn('idBusFeehead', $child_feeheads)
                        ->where(function($query) {
                            $query->whereNull('bus_lesser_transaction_details.status');
                            $query->orWhere('bus_lesser_transaction_details.status', '=', 'Cleared');
                            $query->orWhere('bus_lesser_transaction_details.status', '=', 'In-Process');
                            $query->orWhere('bus_lesser_transaction_details.status', '=', 'Success');
                        })
                        ->select(DB::raw('SUM(amountPaid) as totalPaid'),DB::raw('SUM(discount) as discount'), DB::raw('SUM(fine) as fine'))
                        ->first();
                    if(isset($partial_paid->totalPaid)){        
                            if($headerObject['amount']== ( $partial_paid->totalPaid + $partial_paid->discount))
                            $headerObject['isPaid']='Paid';        
                            else    
                            $headerObject['isPaid']='Partial Paid  Rs '. $partial_paid->totalPaid; 
                        }
                    array_push($feeheaders,$headerObject);
            }
            
                return json_encode(array(
                    "fees" => $feeheaders,
                    "paidFee" => $paidfees,
                    "leeFee"=>$lessfees
                ));       
        }else{
            return json_encode(array());
        }
        
    }
    
    
    public function getSudharshanHostelFee($id){
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
           $std_feeheads = \App\NorthFeeHead::where('idStudent', '=', $student->idStudent)->where('idFinancialYear', '=', $this->fys($student))->where('isParent', '0')->where('isActive', 'Y')->where('idType', 'hostel')->get();
     
            $feeheads = new \Illuminate\Database\Eloquent\Collection; //Create empty collection which we know has the merge() method
            $feeheads = $feeheads->merge($std_feeheads)->sortBy('toDate', 1);
            $feeheads=$feeheads->sort(function ($a, $b) {
                return strtotime($a->toDate) - strtotime($b->toDate);
            });
            
            $paidfees = \App\HostelTransaction::where('idStudent', '=', $id)->where('idFinancialYear', '=', $this->fys($student))->get();
            $lessfees = \App\HostelLesserTransaction::where('idStudent', '=', $id)->where('idFinancialYear', '=', $this->fys($student))->get();
            $feeheaders=array();
            $fineheads=\DB::table('northfines')->where('idSchool', '=', $student->idSchool)->where('idFinancialYear', '=', $student->idFinancialYear)->get();  
            $fineAmount=0;
            $flatfine=0;
            $perDay=array();
                foreach($fineheads as $fine){
                     if($fine->isFlat==1)
                          $flatfine=$fine->amount;
                    else{
                          array_push($perDay,$fine); 
                         } 
                     }
             $now = Carbon::now();         
            foreach($feeheads as $key => $value)
            {
                 $headerObject=json_decode($value,true);
                 $child_feeheads = \App\NorthFeeHead::where('idStudent', '=', $student->idStudent)->where('isActive', 'Y')->where('isParent', $headerObject['idFeehead'])->where('idType', 'hostel')->pluck('idFeehead')->toArray();
                 $date = Carbon::parse($headerObject['toDate']); 
                 $diff = $date->diffInDays($now,false);
                     $already_paid_feehead = \App\HostelTransactionDetail::where('idStudent', '=', $id)
                                        ->whereIn('idFeehead', $child_feeheads)->where(function($query) {
                                    $query->whereNull('status');
                                    $query->orWhere('status', '=', 'In-Process');
                                    $query->orWhere('status', '=', 'Cleared');
                                    $query->orWhere('status', '=', 'Success');
                                })->first();
                    if($already_paid_feehead){                    
                        $headerObject['isPaid']='Paid';
                           $fine=\App\HostelTransaction::where('idStudent', '=', $id)->where('idHostelTransaction', '=', $already_paid_feehead->idHostelTransaction)->select(DB::raw('SUM(fine) as fine'))->first();
                           $headerObject['fine']=$fine->fine;
                    }else  {
                        $headerObject['isPaid']='Due'; 
                        if( $diff < 0){
                            $fineAmount=0;
                        }
                        if($headerObject['fine'] == 'flat' && $diff > 0){
                            $fineAmount=$flatfine;
                        }elseif($headerObject['fine'] == 'per' && $diff > 0){
                            if($diff > 0){
                                                 foreach($perDay as $per){
                                                    if($per->days <= $diff){
                                                        $fineAmount=$per->amount;
                                                        break;
                                                    } 
                                                 }
                                             }
                        }
                        
                        $headerObject['fine']=$fineAmount;
                    }
                        $partial_paid =  DB::table('hostel_lesser_transaction_details')
                        ->where('hostel_lesser_transaction_details.idStudent', '=', $student->idStudent)
                        ->whereIn('idFeehead', $child_feeheads)
                        ->where(function($query) {
                            $query->whereNull('hostel_lesser_transaction_details.status');
                            $query->orWhere('hostel_lesser_transaction_details.status', '=', 'Cleared');
                            $query->orWhere('hostel_lesser_transaction_details.status', '=', 'In-Process');
                            $query->orWhere('hostel_lesser_transaction_details.status', '=', 'Success');
                        })
                        ->select(DB::raw('SUM(amountPaid) as totalPaid'),DB::raw('SUM(discount) as discount'), DB::raw('SUM(fine) as fine'))
                        ->first();
                    if(isset($partial_paid->totalPaid)){        
                            if($headerObject['amount']== ( $partial_paid->totalPaid + $partial_paid->discount))
                            $headerObject['isPaid']='Paid';        
                            else    
                            $headerObject['isPaid']='Partial Paid  Rs '. $partial_paid->totalPaid; 
                        }
                    array_push($feeheaders,$headerObject);
            }
            
                return json_encode(array(
                    "fees" => $feeheaders,
                    "paidFee" => $paidfees,
                    "leeFee"=>$lessfees
                ));      
        }else{
            return json_encode(array());
        }
        
    }
    
    public function printHostel($id){
        $transaction = \App\HostelTransaction::where('idHostelTransaction', '=', $id)->first();
        //Get All feehead
        $student = \App\AdmEntry::where('idStudent', '=', $transaction->idStudent)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($student->idSchool == 14){
            $feehead_ids = $transaction->details->pluck('idParent')->toArray();
            $class_feeheads = \DB::table('northfeeheads')->where('idClass', '=', $student->idClass)
                ->where('idSection', '=', $student->idSection)
                ->where('studentCategory', '=', $student->studentType)
                ->where('isParent',0)
                ->whereNull('idStudent');
            $feeheads = \DB::table('northfeeheads')->where('idStudent', '=', $student->idStudent)->where('isParent',0)
                    ->union($class_feeheads)
                    ->orderBy('toDate')
                    ->get();
            $feetotal = $feeheads->sum('amount');
            $demands = \App\NorthFeeHead::where('isParent', '=', '0')
                                ->whereIn('idFeehead', $feehead_ids)
                                ->get();
             $pdf = PDF::loadView('schools.north.transaction.print_receipt', ['margin_top' => 20], compact('transaction', 'school', 'student', 'feetotal','demands','feehead_ids'));
            return $pdf->stream('feereceipt.pdf');
        }else{
            $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 printExtraReceipt($id,$rid,Request $request){
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        $transaction = \App\StudentExtraTransaction::where('idTransaction', '=', $rid)->first();
        $pdf = PDF::loadView('schools.transaction.print_receipt_extra', ['margin_top' => 20], compact('transaction', 'school', 'student'));
        return $pdf->stream('feereceipt.pdf');
    }

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

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

    public function printLessReceipt($id,$rid,Request $request){
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student ->idSchool)->first();
        $transaction = \App\LesserTransaction::where('idLesserTransaction', '=', $rid)->first();
        $totalAmountPaid = 0;
        $penaltyAmount = 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');
        } 
        $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 printReceipt($id,$rid,Request $request) {
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        $transaction = \App\StudentTransaction::where('idTransaction', '=', $rid)->where('idStudent', '=', $id)->first();
        //if($transaction == null){

        //}
        //Get All feehead
        if($student->idSchool == 14){
            $feehead_ids = $transaction->details->pluck('idParent')->toArray();
            $demands = \App\NorthFeeHead::select('isParent')->where('isParent', '!=', '0')
                                ->whereIn('idFeehead', $feehead_ids)
                                ->distinct('isParent')
                                ->get();
            $student = \App\AdmEntry::where('idStudent', '=', $transaction->idStudent)->first();
            $class_feeheads = \DB::table('northfeeheads')->where('idClass', '=', $student->idClass)
                    ->where('idSection', '=', $student->idSection)
                    ->where('studentCategory', '=', $student->studentType)
                    ->where('isParent',0)
                    ->where('isActive','=','Y')
                    ->whereNull('idStudent');
            $feeheads = \DB::table('northfeeheads')->where('idStudent', '=', $student->idStudent)
                    ->where('isActive','=','Y')
                    ->where('isParent',0)
                    ->union($class_feeheads)
                    ->orderBy('toDate')
                    ->get();
            $feetotal = $feeheads->sum('amount');
        
        $pdf = PDF::loadView('schools.north.transaction.print_receipt', ['margin_top' => 20], compact('demands','transaction', 'school', 'student', 'feetotal'));
            return $pdf->stream('feereceipt.pdf');
        }else{
            $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');
            if($request->get("paymentMode") != null){
                $transaction = \App\StudentTransaction::where('idTransaction', '=', substr($rid,0,-2))->first();
                $student = \App\AdmEntry::where('idStudent', $transaction->idStudent)->first();
                $pdf = PDF::loadView('schools.transaction.book_print_receipt', ['margin_top' => 20], compact('transaction', 'school', 'student', 'feetotal'));
                return $pdf->stream('feereceipt.pdf');
            }
            $pdf = PDF::loadView('schools.transaction.print_receipt', ['margin_top' => 20], compact('transaction', 'school', 'student', 'feetotal'));
            return $pdf->stream('feereceipt.pdf');
        }
    }

    public function printBusNewReceipt($idStudent,$id){
        $transaction = \App\BusTransaction::where('idBusTransaction', '=', $id)->where('idStudent', '=', $idStudent)->first();
        $student = \App\AdmEntry::where('idStudent', '=', $idStudent)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        //Get All feehead
        $plan = '';
            $paidHeaders= \App\BusTransactionDetail::join('busfeeheads', 'bus_transaction_details.idBusFeehead', '=', 'busfeeheads.idBusFeehead')->select('feeheadLabel')
            ->where('idStudent', '=', $student->idStudent)->where(function($query) {
                $query->whereNull('status');
                $query->orWhere('status', '=', 'In-Process');
                $query->orWhere('status', '=', 'Cleared');
                $query->orWhere('status', '=', 'Success');
            })->get();
    
            if(count($paidHeaders) == 0){
                $lessHeaders = \App\BusLesserTransactionDetail::join('busfeeheads', 'bus_lesser_transaction_details.idBusFeehead', '=', 'busfeeheads.idBusFeehead')->select('feeheadLabel')
                ->where('idStudent', '=', $student->idStudent)->where(function($query) {
                    $query->whereNull('status');
                    $query->orWhere('status', '=', 'In-Process');
                    $query->orWhere('status', '=', 'Cleared');
                    $query->orWhere('status', '=', 'Success');
                })->get();
    
                if(count($lessHeaders) > 0){
                    foreach($lessHeaders as $feeTransaction){
                        if (str_contains($feeTransaction->feeheadLabel, 'Plan A')) {
                            $plan = 'Plan A';
                            break;
                        }else if (str_contains($feeTransaction->feeheadLabel, 'Plan B')) {
                            $plan = 'Plan B';
                            break;
                        }
                    }
                }
            }else{
                foreach($paidHeaders as $feeTransaction){
                    if (str_contains($feeTransaction->feeheadLabel, 'Plan A')) {
                        $plan = 'Plan A';
                        break;
                    }else if (str_contains($feeTransaction->feeheadLabel, 'Plan B')) {
                        $plan = 'Plan B';
                        break;
                    }
                }
            }
        $stdtransport = \App\StudentTransport::where('idStudent', '=', $student->idStudent)->where('idFinancialYear', '=', $student->idFinancialYear)->first();
        $feeheads = \App\BusFeehead::where('idStop', '=', $stdtransport->idStop)
                                        ->where('feeheadLabel', '=', $plan)
                                        ->orderBy('toDate')
                                        ->get();
        $feetotal = $feeheads->sum('amount');
        //dd($transaction->details);   
        //return response()->json(['Status' => $transaction], 404, ['app-status' => 'success']);     
        $pdf = PDF::loadView('schools.buses.print_receipt', ['margin_top' => 20], compact('transaction', 'school', 'student', 'feetotal'));
        return $pdf->stream('feereceipt.pdf');
    }

    public function printBusLessReceipt($idStudent,$id){
        $transaction = \App\BusLesserTransaction::where('idBusLesserTransaction', '=', $id)->where('idStudent', '=', $idStudent)->first();
        $student = \App\AdmEntry::where('idStudent', '=', $idStudent)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        //Get All feehead
        $plan = '';
            $paidHeaders= \App\BusTransactionDetail::join('busfeeheads', 'bus_transaction_details.idBusFeehead', '=', 'busfeeheads.idBusFeehead')->select('feeheadLabel')
            ->where('idStudent', '=', $student->idStudent)->where(function($query) {
                $query->whereNull('status');
                $query->orWhere('status', '=', 'In-Process');
                $query->orWhere('status', '=', 'Cleared');
                $query->orWhere('status', '=', 'Success');
            })->get();
    
            if(count($paidHeaders) == 0){
                $lessHeaders = \App\BusLesserTransactionDetail::join('busfeeheads', 'bus_lesser_transaction_details.idBusFeehead', '=', 'busfeeheads.idBusFeehead')->select('feeheadLabel')
                ->where('idStudent', '=', $student->idStudent)->where(function($query) {
                    $query->whereNull('status');
                    $query->orWhere('status', '=', 'In-Process');
                    $query->orWhere('status', '=', 'Cleared');
                    $query->orWhere('status', '=', 'Success');
                })->get();
    
                if(count($lessHeaders) > 0){
                    foreach($lessHeaders as $feeTransaction){
                        if (str_contains($feeTransaction->feeheadLabel, 'Plan A')) {
                            $plan = 'Plan A';
                            break;
                        }else if (str_contains($feeTransaction->feeheadLabel, 'Plan B')) {
                            $plan = 'Plan B';
                            break;
                        }
                    }
                }
            }else{
                foreach($paidHeaders as $feeTransaction){
                    if (str_contains($feeTransaction->feeheadLabel, 'Plan A')) {
                        $plan = 'Plan A';
                        break;
                    }else if (str_contains($feeTransaction->feeheadLabel, 'Plan B')) {
                        $plan = 'Plan B';
                        break;
                    }
                }
            }
        $stdtransport = \App\StudentTransport::where('idStudent', '=', $student->idStudent)->where('idFinancialYear', '=', $student->idFinancialYear)->first();
        $feeheads = \App\BusFeehead::where('idStop', '=', $stdtransport->idStop)
                                        ->where('feeheadLabel', '=', $plan)
                                        ->orderBy('toDate')
                                        ->get();
        $feetotal = $feeheads->sum('amount');
        //dd($transaction->details);   
        //return response()->json(['Status' => $transaction], 404, ['app-status' => 'success']);     
        $pdf = PDF::loadView('schools.buses.print_receipt', ['margin_top' => 20], compact('transaction', 'school', 'student', 'feetotal'));
        return $pdf->stream('feereceipt.pdf');
    }
    
    

    public function changePassword(Request $req){

    if ($req->has('pwd')) {
      $user=Auth::guard('student-api')->user();
      $parent = \App\Parents::findOrfail($user->idParent);
      $parent->password = bcrypt($req->pwd);
      if($parent->save())
      return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
      else 
        return response()->json(['success' => "Failed"], 200, ['app-status' => 'success']);
        }else  return response()->json(['success' => "Failed"], 200, ['app-status' => 'success']);
    }

    public function changeNumber(Request $request){
        $user=Auth::guard('student-api')->user();
        if( DB::table('user_request')->where('prevNumber', $user->mobile)->where('isResolved', 0)->doesntExist()){
             if(DB::table('user_request')->insert([
            [
                'noteRequest' => 'Change Number', 
                'prevNumber' => $user->mobile,
                'newNumber'=>$request->mobile,
                'created_at'=>Carbon::now()->timestamp,
                'isResolved'=>0
            ]
        ])) return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
        else 
        return response()->json(['success' => "Failed"], 200, ['app-status' => 'success']);
    
        }  
      else 
        return response()->json(['success' => "Request already exists"], 200, ['app-status' => 'success']);
    }
    
    public function getStudentAttendence($id,$mid){
         $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
         $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
         
            if($school->isActive == 'Y' && $student->isActive == 'Y'){
                //calculate no of working days
                 $totalDays=0;
                 $now = Carbon::now();
                 $m = $mid;
                 $y = $now->year;
                 
                 $dt = 1 . '-' . $m . '-' . $y;
                 $tdate = Carbon::parse($dt);
                 
                 $month_name = $tdate->format('M');
                 $month = \App\Month::where('monthName', 'like', '%' . $month_name . '%')->first();
                 $noOfdays = $month->noOfDays;
                 for($i=1; $i<=$noOfdays;$i++){
                     $dt = $i . '-' . $m . '-' . $y;
                     $tdate = Carbon::parse($dt);
                     $jdate = $tdate->format('Y-m-d');
                     $v = \App\Holiday::where('idSchool', '=', $student->idSchool)
                                                            ->whereDate('fromDate', '<=', $jdate)
                                                            ->whereDate('toDate', '>=', $jdate)
                                                            ->first();
                    if($tdate->dayOfWeek != '0' && $v==null)                                        
                    {
                        $totalDays=$totalDays+1;  
                    }
                 }
                $manualData=array();

                $from = date($y.'-'.$m.'-1');
				$to = date($y.'-'.$m.'-'.$noOfdays);

                $attendenceAutomatic= DB::table('attandance')
                              ->select(DB::raw('UPPER(attandance.status) as status'),'attandance.TimeStamp','attandance.date')
                              ->where('attandance.Enrollment_Number',$student->ecNo)
                              ->where('attandance.idSchool',$student->idSchool)
                              ->where('attandance.idMonth',$mid)
                              ->whereDate('attandance.date', '<=', $from)
                              ->orwhereDate('attandance.date', '>=', $to)
                              //->whereBetween('attandance.date', [$from, $to])
                              ->groupBy('attandance.date')->get(); 
                              
                foreach($attendenceAutomatic as $attendance)  {
                    $attendance->working=$totalDays;
                    array_push($manualData,$attendance);
                }  
                return json_encode($manualData);
            }else{
                return json_encode(array());
            }
         
    }

    public function getSAttendence($id,$mid,$year){
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        
           if($school->isActive == 'Y' && $student->isActive == 'Y'){
               //calculate no of working days
                $manualData = array();
                $holidays = 0;
                $presents = 0;
                $workingDays = 0;
                $now = Carbon::now();
                $m = $mid;
                $y = $year;
                $dt = 1 . '-' . $m . '-' . $y;
                $tdate = Carbon::parse($dt);
                $month_name = $tdate->format('M');
                $month = \App\Month::where('monthName', 'like', '%' . $month_name . '%')->first();
                $totalDays = $month->noOfDays;
                $todaydate = Carbon::now();

                for($i=1; $i<=$totalDays;$i++){
                   $dt = $i . '-' . $m . '-' . $y;
                   $tdate = Carbon::parse($dt);
                   $jdate = $tdate->format('Y-m-d');
                   $v = \App\Holiday::where('idSchool', '=', $school->idSchool)
                   ->where('idClass',$student->idClass)
                   ->whereDate('fromDate', '<=', $jdate)
                   ->whereDate('toDate', '>=', $jdate)
                   ->first();
                   if($v == null){
                    $v = \App\Holiday::where('idSchool', '=', $school->idSchool)
                        ->whereNull('idClass')
                        ->whereDate('fromDate', '<=', $jdate)
                        ->whereDate('toDate', '>=', $jdate)
                        ->first();
                   }

                    if($jdate <= $todaydate){
                        $workingDays = $workingDays + 1;
                        if($tdate->dayOfWeek == '0' || $v != null)                                        
                        {
                            $holidays = $holidays + 1;  
                            $attendance = [];
                            $attendance['status'] = "H";
                            if($v != null)
                            $attendance['eventName'] = $v->holidayName;
                            else  $attendance['eventName'] = "Week Off";
                            $attendance['date'] = $jdate;
                            $attendance['TimeStamp'] = $jdate;
                            array_push($manualData,$attendance); 
                        }
                        else{
                            if($school->idSchool == 82){
                                $attendance= DB::table('attandance')
                                            ->select('attandance.status','attandance.TimeStamp','attandance.date','attandance.routine')
                                            ->where('attandance.Enrollment_Number',$student->ecNo)
                                            ->where('attandance.idSchool',82)
                                            ->where('attandance.idMonth',$mid)
                                            ->whereDate('attandance.date', '=', $jdate)->get();
                                if($attendance != null){
                                    if($attendance->count() == 2)
                                    {
                                        if($attendance[0]->routine == "forenoon" 
                                        && $attendance[1]->routine == "afternoon" && $attendance[0]->status == "P" && $attendance[1]->status == "P"){
                                            $attendance[0]->status == "P";
                                            array_push($manualData,$attendance[0]);
                                        }else if($attendance[0]->routine == "afternoon" 
                                        && $attendance[1]->routine == "forenoon" && $attendance[0]->status == "P" && $attendance[1]->status == "P"){
                                            $attendance[0]->status == "P";
                                            array_push($manualData,$attendance[0]);
                                        }else if($attendance[0]->status == "A" && $attendance[1]->status == "P"){
                                            if($attendance[1]->routine == "afternoon"){
                                                $attendance[1]->status == "AN";
                                                array_push($manualData,$attendance[1]);
                                            }else{
                                                $attendance[1]->status == "FN";
                                                array_push($manualData,$attendance[1]);
                                            }
                                        }else if($attendance[0]->status == "P" && $attendance[1]->status == "A"){
                                            if($attendance[0]->routine == "afternoon"){
                                                $attendance[0]->status == "AN";
                                                array_push($manualData,$attendance[0]);
                                            }else{
                                                $attendance[0]->status == "FN";
                                                array_push($manualData,$attendance[0]);
                                            }
                                        }else{
                                            $attendance[0]->status == "A";
                                            array_push($manualData,$attendance[0]);
                                        }
                                    }else 
                                    if($attendance->count() == 1)
                                    {
                                        if($attendance[0]->routine == "forenoon" && $attendance[0]->status == "P"){
                                            $attendance[0]->status = "FN";
                                        }
                                        else if($attendance[0]->routine == "afternoon" && $attendance[0]->status == "P"){
                                            $attendance[0]->status = "AN";
                                        }else {
                                            $attendance[0]->status = "A";
                                        }
                                        array_push($manualData,$attendance[0]); 
                                    }
                                }            
                            }else{
                                $attendance= DB::table('attandance')
                                            ->select(DB::raw('UPPER(attandance.status) as status'),'attandance.TimeStamp','attandance.date')
                                            ->where('attandance.Enrollment_Number',$student->ecNo)
                                            ->where('attandance.idSchool',$student->idSchool)
                                            ->where('attandance.idMonth',$mid)
                                            ->whereIn('attandance.status',["IN","P","p","A"])
                                            ->whereDate('attandance.date', '=', $jdate)
                                            ->orderBy('ID','DESC')->first();
    
                                if($attendance != null){
                                    $presents = $presents + 1;
                                    array_push($manualData,$attendance); 
                                }
                            }
                            
                        }
                    }
                }
                
                $absent = $workingDays - ($holidays + $presents);
                $data = array(
                   "total" => $totalDays - $holidays,
                   "working" => $presents+$absent,
                   "holiday" => $holidays,
                   "present" => $presents,
                   "absent" =>  $workingDays - ($holidays + $presents),
                   "data" => $manualData

               );
               return json_encode($data);
           }else{
               return json_encode(array());
           }
        
    }
    
    //Transport Section
    public function getBusRoute($id){
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $stdtransport = \App\StudentTransport::where('student_transport.idStudent', '=', $student->idStudent)->first();
        if(isset($stdtransport)) {               
            $stopDetails=DB::table('route_stops')->select('stopName',DB::raw('IFNULL(longitude,0.0) as longitude'),DB::raw('IFNULL(latitude,0.0) as latitude'))->where('idStop','=',$stdtransport->idStop)->first();
            $allStops=DB::table('route_stops')->select('stopName',DB::raw('IFNULL(longitude,0.0) as longitude'),DB::raw('IFNULL(latitude,0.0) as latitude'))->where('idRoute','=',$stdtransport->idRoute)->get();
            $busDetails=DB::table('busroutes')
            ->join('buses', 'busroutes.idBus', '=', 'buses.idBus')
            ->select('busNo','busName','supporterName','contactNo','buses.idBus','routes')
            ->where('busroutes.idRoute','=',$stdtransport->idRoute)->first();
            if($busDetails != null){
                if($busDetails->routes == null){
                    $routes = DB::table('route_stops')->where('route_stops.idRoute', '=', $stdtransport->idRoute)->get();
                    $intermediate = [] ;
                            foreach($routes as $stop){
                                $loc['latitude'] = $stop->latitude;
                                $loc['longitude'] = $stop->longitude;
                                array_push($intermediate, [
                                    'location' => [
                                        'latLng' => $loc
                                    ]
                                ]);
                            }
                            $apiData["origin"] = $intermediate[0];
                            $apiData["destination"] = $intermediate[count($intermediate) - 1];
                            $apiData["travelMode"] = "DRIVE";
                            $apiData["routingPreference"] = "TRAFFIC_AWARE";
                            $apiData["computeAlternativeRoutes"] = false;
                            $modifiers = [];
                            $modifiers["avoidTolls"] = false;
                            $modifiers["avoidHighways"] = false;
                            $modifiers["avoidFerries"] = false;
                            $apiData["routeModifiers"] =$modifiers;
                            $apiData["languageCode"] = "en-US";
                            $apiData["units"] = "IMPERIAL";
                            $apiData["intermediates"] = $intermediate;
                            //call route api
                            $result = \App\Http\RouteApi::initiateRoute($apiData);
                            $lines = $result['routes'][0];
                            $polyline = $lines['polyline'];
                            $encodedPolyline = $polyline['encodedPolyline'];
                            DB::table('busroutes')->where('idBusRoute',$stdtransport->idRoute)->update(['routes' => $encodedPolyline]);
                    $busDetails->routes = $encodedPolyline;         
                }
            }          

            return response()->json(['success' => "SUCCESS", 'stop'=>$stopDetails,'bus'=>$busDetails,'routes'=>$allStops ], 200, ['app-status' => 'success']);
        }
        else 
        return response()->json(['success' => "Failed"], 200, ['app-status' => 'success']);
    }

    public function getInstallmentBusFee($student,$school,Request $req){
        $fy = array();
        $fetchSession = \App\FinancialYear::where('idFinancialYear','>=',$student->idFinancialYear)->get();
        foreach($fetchSession as $session){
            $promotions = \App\AdmEntry::where('idSchool', '=', $student->idSchool)
            ->where('father_mobile','=',$student->father_mobile)
            ->where('father_fname','=',$student->father_fname)
            ->where('ecNo','=',$student->ecNo)
            ->where('isActive','=','Y')
            ->where('idFinancialYear','=',$session->idFinancialYear)
            ->first();
            if($promotions != null)
                array_push($fy,array(
                    "id" => $promotions->idStudent,
                    "yearName" => $session->financialYearName,
                    "idFinancialYear" => $promotions->idFinancialYear
                ));
        }

        if($req->get('paymentType') != null){
            $plan = $req->get('paymentType');
        }else{
            $plan = '';
            $paidHeaders= \App\BusTransactionDetail::join('busfeeheads', 'bus_transaction_details.idBusFeehead', '=', 'busfeeheads.idBusFeehead')->select('feeheadLabel')
            ->where('idStudent', '=', $student->idStudent)->where(function($query) {
                $query->whereNull('status');
                $query->orWhere('status', '=', 'In-Process');
                $query->orWhere('status', '=', 'Cleared');
                $query->orWhere('status', '=', 'Success');
            })->get();
    
            if(count($paidHeaders) == 0){
                $lessHeaders = \App\BusLesserTransactionDetail::join('busfeeheads', 'bus_lesser_transaction_details.idBusFeehead', '=', 'busfeeheads.idBusFeehead')->select('feeheadLabel')
                ->where('idStudent', '=', $student->idStudent)->where(function($query) {
                    $query->whereNull('status');
                    $query->orWhere('status', '=', 'In-Process');
                    $query->orWhere('status', '=', 'Cleared');
                    $query->orWhere('status', '=', 'Success');
                })->get();
    
                if(count($lessHeaders) > 0){
                    foreach($lessHeaders as $transaction){
                        if (str_contains($transaction->feeheadLabel, 'Plan A')) {
                            $plan = 'Plan A';
                            break;
                        }else if (str_contains($transaction->feeheadLabel, 'Plan B')) {
                            $plan = 'Plan B';
                            break;
                        }
                    }
                }
            }else{
                foreach($paidHeaders as $transaction){
                    if (str_contains($transaction->feeheadLabel, 'Plan A')) {
                        $plan = 'Plan A';
                        break;
                    }else if (str_contains($transaction->feeheadLabel, 'Plan B')) {
                        $plan = 'Plan B';
                        break;
                    }
                }
            }
        }

        $stdtransport = \App\StudentTransport::where('student_transport.idFinancialYear', '=', $student->idFinancialYear)
                        ->where('student_transport.idStudent', '=', $student->idStudent)->first();
        $mode = array();
        if($plan == '') {
            $plan = 'Plan A';
            $mode[0]["plan"] = "Monthly";   
            $mode[0]["action"] = "Plan A";
            $mode[1]["plan"] = "Half yearly";
            $mode[1]["action"] = "Plan B"; 
        }                
       
        $feeheads = \App\BusFeehead::where('idStop', '=', $stdtransport->idStop)
                                        ->where('feeheadLabel', '=', $plan)
                                        ->orderBy('toDate')
                                        ->get();

        $discountfees = \App\BusFeeDiscount::where('idStudent', '=', $student->idStudent)->where('isActive', '=', 'Y')->get();  
        $i=0;  
        $isFirstPaid = 0;
        foreach($feeheads as $headers) {
            $paidHeaders= \App\BusTransactionDetail::where('idStudent', '=', $student->idStudent)->where('idBusFeehead', '=', $headers->idBusFeehead)->where(function($query) {
                                $query->whereNull('status');
                                $query->orWhere('status', '=', 'In-Process');
                                $query->orWhere('status', '=', 'Cleared');
                                $query->orWhere('status', '=', 'Success');
                            })->get()->toArray();
            $stepDiscount=0;            
            $isDiscount=\App\BusFeeDiscount::where('idStudent', '=', $student->idStudent)->where('idBusFeehead', '=', $headers->idBusFeehead)->where('isActive', '=', 'Y')->get();            
            foreach($isDiscount as $discount){
                $stepDiscount=$stepDiscount+$discount->amount;
            }
            $feeheads[$i]['discount']=$stepDiscount;
            if(sizeof($paidHeaders)>0){
                $feeheads[$i]['status']="Paid";
                if($headers->feeheadName == "1st Installment"){
                    $isFirstPaid++;
                }
            }else $feeheads[$i]['status']="Due";
            
            
            $startDate = Carbon::parse($headers->fromDate);
            $now = Carbon::now();
            $dueDiff = $startDate->diffInDays($now, false);

            if($plan != "Plan A")
            $feeheads[$i]['isEnabled'] = false;
            else 
            $feeheads[$i]['isEnabled'] = ($dueDiff > -1);
            $i++;   
        }
        
        $paidfees = \App\BusTransaction::select('bus_transaction.*',DB::raw('IFNULL(bus_transaction.excessAmountUsed,0.00) as excessAmount'))->where('idStudent', '=', $student->idStudent)
                            ->where(function($query) {
                                $query->whereNull('status');
                                $query->orWhere('status', '=', 'In-Process');
                                $query->orWhere('status', '=', 'Cleared');
                                $query->orWhere('status', '=', 'Success');
                            })->get();
         return json_encode(array(
                    'fees'=>$feeheads,
                    'transaction'=>$paidfees,
                    "forceFee" => $fy,
                    "current_mode" => $plan,
                    "mode" => $mode,
                    "discount" => $discountfees,
                ));                     
    }

    public function getRoyalTransportFee($student,$school,$request){
        $stdtransport = \App\StudentTransport::where('student_transport.idFinancialYear', '=', $student->idFinancialYear)
                        ->where('student_transport.idStudent', '=', $student->idStudent)->first();
        $fetchSession = \App\FinancialYear::where('idSchool',$student->idSchool)->get();
            $fy = array();
            foreach($fetchSession as $session){
                $promotions = \App\AdmEntry::where('idSchool', '=', $student->idSchool)
                ->where('father_mobile','=',$student->father_mobile)
                ->where('father_fname','=',$student->father_fname)
                ->where('ecNo','=',$student->ecNo)
                ->where('idFinancialYear','=',$session->idFinancialYear)
                ->first();
                if($promotions != null)
                array_push($fy,array(
                    "id" => $promotions->idStudent,
                    "yearName" => $session->financialYearName,
                    "idFinancialYear" => $promotions->idFinancialYear
                ));
            }
            $summary = [
                "feeTotal" => 0,
                "discount" => 0,
                "fine" => 0,
                "additional" => 0,
                "penaltyAmt" => 0,
                "paidFine" => 0,
                "totalAmount" => 0,
                "balance" => 0,
                "paidfees" => 0
            ];
            $k =0;
            $feeheaders = PaymentCalculation::calculateBusFee($student,$request,$stdtransport);
            foreach($feeheaders as $var){
                $summary['feeTotal'] = $summary['feeTotal'] + $var['amount'];
                $summary['discount'] = $summary['discount'] + $var['discount'];
                $summary['fine'] = $summary['fine'] + $var['fine'];
                $summary['paidFine'] = $summary['paidFine'] + $var['transaction']['paid_fine'];
                $summary['totalAmount'] = $summary['totalAmount'] + $var['total_amount'];
                $summary['balance'] = $summary['balance'] + $var['balance'];
                $summary['paidfees'] = $summary['paidfees'] + $var['transaction']['paid'];
                if($var['isPaid'] == "Partial Paid"){
                    $feeheaders[$k]['isEnabled'] = false;
                }
                $k++;
            }

            $plan = '';
            $paidfees = \App\BusTransaction::where('idStudent', '=', $student->idStudent)
            ->where('idFinancialYear',$student->idFinancialYear)
            ->where(function($query) {
                $query->whereNull('status');
                $query->orWhere('status', '=', 'In-Process');
                $query->orWhere('status', '=', 'Cleared');
                $query->orWhere('status', '=', 'Success');
            })->get();
            
            if($paidfees->count() > 0){
                foreach($paidfees as $paidfee){
                    $transactions = \App\BusTransactionDetail::where('idBusTransaction','=',$paidfee->idBusTransaction)->get();
                    foreach($transactions as $transaction){
                        $header = \App\BusFeehead::where('idBusFeehead',$transaction->idBusFeehead)->first();
                        if (str_contains($header->feeheadLabel, 'Plan A')) {
                            $plan = 'Plan A';
                            break;
                        }else if (str_contains($header->feeheadLabel, 'Plan B')) {
                            $plan = 'Plan B';
                            break;
                        }else if (str_contains($header->feeheadLabel, 'Plan C')) {
                            $plan = 'Plan C';
                            break;
                        }
                    }

                    if($plan != '') break;
                }
            }
            
            $transaction = new \Illuminate\Database\Eloquent\Collection; //Create empty collection which we know has the merge() method
            if($request->get('transaction') != "" && $request->get('transaction') != null){
                $paidfees = \App\BusTransaction::where('idStudent', '=', $student->idStudent)->get();
                $lessfees = \App\BusLesserTransaction::where('idStudent', '=', $student->idStudent)->get();
            }else{
                $paidfees = \App\BusTransaction::where('idStudent', '=', $student->idStudent)->where(function($query) {
                    $query->whereNull('status');
                    $query->orWhere('status', '=', 'In-Process');
                    $query->orWhere('status', '=', 'Cleared');
                    $query->orWhere('status', '=', 'Success');
                })->get();
                $lessfees = \App\BusLesserTransaction::where('idStudent', '=', $student->idStudent)->where(function($query) {
                    $query->whereNull('status');
                    $query->orWhere('status', '=', 'In-Process');
                    $query->orWhere('status', '=', 'Cleared');
                    $query->orWhere('status', '=', 'Success');
                })->get();
            }
            $transaction = $transaction->merge($lessfees);
            $transaction = $transaction->merge($paidfees);
            
            $discountfees = \App\BusFeeDiscount::where('idStudent', '=', $student->idStudent)->where('isActive', 'Y')->get();

        return json_encode(array(
            "paymode" => [],
            "current_plan" => $plan,
            "fees" => $feeheaders,
            "forceFee" => $fy,
            "paidFee" => $transaction,
            "discount" => $discountfees,
            "summary" => $summary
        ));
    }

    public function getRoyalBus($student,$school,$request){
        $stdtransport = \App\StudentTransport::where('student_transport.idFinancialYear', '=', $student->idFinancialYear)
                        ->where('student_transport.idStudent', '=', $student->idStudent)->first();
        if($request->get('paymode') != null){
            return $this->getRoyalTransportFee($student,$school,$request);
        }else{
            $fetchSession = \App\FinancialYear::where('idFinancialYear','>=',$student->idFinancialYear)->get();
            $fy = array();
            foreach($fetchSession as $session){
                $promotions = \App\AdmEntry::where('idSchool', '=', $student->idSchool)
                ->where('father_mobile','=',$student->father_mobile)
                ->where('father_fname','=',$student->father_fname)
                ->where('ecNo','=',$student->ecNo)
                ->where('idFinancialYear','=',$session->idFinancialYear)
                ->first();
                if($promotions != null)
                array_push($fy,array(
                    "id" => $promotions->idStudent,
                    "yearName" => $session->financialYearName,
                    "idFinancialYear" => $promotions->idFinancialYear
                ));
            }
            $plan = '';
            $paidfees = \App\BusTransaction::where('idStudent', '=', $student->idStudent)
            ->where(function($query) {
                $query->whereNull('status');
                $query->orWhere('status', '=', 'In-Process');
                $query->orWhere('status', '=', 'Cleared');
                $query->orWhere('status', '=', 'Success');
            })->get();

            if($paidfees->count() > 0){
                foreach($paidfees as $paidfee){
                    $transactions = \App\BusTransactionDetail::where('idBusTransaction','=',$paidfee->idBusTransaction)->get();
                    foreach($transactions as $transaction){
                        $header = \App\BusFeehead::where('idBusFeehead',$transaction->idBusFeehead)->first();
                        if (str_contains($header->feeheadLabel, 'Plan A')) {
                            $plan = 'Plan A';
                            break;
                        }else if (str_contains($header->feeheadLabel, 'Plan B')) {
                            $plan = 'Plan B';
                            break;
                        }else if (str_contains($header->feeheadLabel, 'Plan C')) {
                            $plan = 'Plan C';
                            break;
                        }
                    }

                    if($plan != '') break;
                }
            }
            if($plan != '') return $this->getRoyalTransportFee($student,$school,$request);
        }
        $paymodes = array();
        $plana_feeheads = \App\BusFeehead::where('idStop', '=', $stdtransport->idStop)
                                                ->where('feeheadLabel', 'LIKE', 'Plan A%')
                                                ->orderBy('toDate')
                                                ->get();
        $afeetotal = $plana_feeheads->sum('amount');
        array_push($paymodes,array(
            'feeheadName' => 'Fees in Full Payment',
            'isPaid' => 'Plan A',
            'amount'=> $afeetotal
        ));
        $planb_feeheads = \App\BusFeehead::where('idStop', '=', $stdtransport->idStop)
                                                ->where('feeheadLabel', 'LIKE', 'Plan B%')
                                                ->orderBy('toDate')
                                                ->get();
                                        $bfeetotal = $planb_feeheads->sum('amount');
                                        array_push($paymodes,array(
                                            'feeheadName' => 'Fees in Terms',
                                            'isPaid' => 'Plan B',
                                            'amount' => $bfeetotal
                                        ));                            
        return json_encode(array(
            "fees" => [],
            "paidFee" => [],
            "forceFee" => $fy,
            "paymode" => $paymodes
        ));  
    }
    
    public function getBusFee($id,Request $req){
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){

            if($student->idSchool == 140){
                return $this->getInstallmentBusFee($student,$school,$req);
            }
            if($student->idSchool == 25){
                return $this->getRoyalBus($student,$school,$req);
            }
            $stdtransport = \App\StudentTransport::where('student_transport.idFinancialYear', '=', $student->idFinancialYear)
                        ->where('student_transport.idStudent', '=', $student->idStudent)->first();
            $feeheads = \App\BusFeehead::where('idStop', '=', $stdtransport->idStop)
                                            ->orderBy('toDate')
                                            ->get();
            $i=0;  
            foreach($feeheads as $headers) {
                $paidHeaders= \App\BusTransactionDetail::where('idStudent', '=', $student->idStudent)->where('idBusFeehead', '=', $headers->idBusFeehead)->where(function($query) {
                                $query->whereNull('status');
                                $query->orWhere('status', '=', 'In-Process');
                                $query->orWhere('status', '=', 'Cleared');
                                $query->orWhere('status', '=', 'Success');
                            })->get()->toArray();
                $stepDiscount=0;            
                $isDiscount=\App\BusFeeDiscount::where('idStudent', '=', $student->idStudent)->where('idBusFeehead', '=', $headers->idBusFeehead)->where('isActive', '=', 'Y')->get();            
                foreach($isDiscount as $discount){
                    $stepDiscount=$stepDiscount+$discount->amount;
                }
                $feeheads[$i]['discount']=$stepDiscount;
                if(sizeof($paidHeaders)>0){
                    $feeheads[$i]['status']="Paid";
                }else $feeheads[$i]['status']="Due";
                $i++;
                            
            }              
            $paidfees = \App\BusTransaction::select('bus_transaction.*',DB::raw('IFNULL(bus_transaction.excessAmountUsed,0.00) as excessAmount'))->where('idStudent', '=', $student->idStudent)
                            ->where(function($query) {
                                $query->whereNull('status');
                                $query->orWhere('status', '=', 'In-Process');
                                $query->orWhere('status', '=', 'Cleared');
                                $query->orWhere('status', '=', 'Success');
                            })->get();
            return json_encode(array(
                'fees'=>$feeheads,
                'transaction'=>$paidfees
                ));                   
        }else{
            return json_encode(array());
        }
                     
    }

    public function printTransportReceipt($idStudent,$id){
        $transaction = \App\BusTransaction::where('idBusTransaction', '=', $id)->where('idStudent', '=', $idStudent)->first();
        if($transaction == null){
            $transaction = \App\BusLesserTransaction::where('idBusLesserTransaction', '=', $id)->where('idStudent', '=', $idStudent)->first();
        }
        $student = \App\AdmEntry::where('idStudent', '=', $idStudent)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        //Get All feehead
        $plan = '';
            $paidHeaders= \App\BusTransactionDetail::join('busfeeheads', 'bus_transaction_details.idBusFeehead', '=', 'busfeeheads.idBusFeehead')->select('feeheadLabel')
            ->where('idStudent', '=', $student->idStudent)->where(function($query) {
                $query->whereNull('status');
                $query->orWhere('status', '=', 'In-Process');
                $query->orWhere('status', '=', 'Cleared');
                $query->orWhere('status', '=', 'Success');
            })->get();
    
            if(count($paidHeaders) == 0){
                $lessHeaders = \App\BusLesserTransactionDetail::join('busfeeheads', 'bus_lesser_transaction_details.idBusFeehead', '=', 'busfeeheads.idBusFeehead')->select('feeheadLabel')
                ->where('idStudent', '=', $student->idStudent)->where(function($query) {
                    $query->whereNull('status');
                    $query->orWhere('status', '=', 'In-Process');
                    $query->orWhere('status', '=', 'Cleared');
                    $query->orWhere('status', '=', 'Success');
                })->get();
    
                if(count($lessHeaders) > 0){
                    foreach($lessHeaders as $feeTransaction){
                        if (str_contains($feeTransaction->feeheadLabel, 'Plan A')) {
                            $plan = 'Plan A';
                            break;
                        }else if (str_contains($feeTransaction->feeheadLabel, 'Plan B')) {
                            $plan = 'Plan B';
                            break;
                        }
                    }
                }
            }else{
                foreach($paidHeaders as $feeTransaction){
                    if (str_contains($feeTransaction->feeheadLabel, 'Plan A')) {
                        $plan = 'Plan A';
                        break;
                    }else if (str_contains($feeTransaction->feeheadLabel, 'Plan B')) {
                        $plan = 'Plan B';
                        break;
                    }
                }
            }
        $stdtransport = \App\StudentTransport::where('idStudent', '=', $student->idStudent)->where('idFinancialYear', '=', $student->idFinancialYear)->first();
        $feeheads = \App\BusFeehead::where('idStop', '=', $stdtransport->idStop)
                                        ->where('feeheadLabel', '=', $plan)
                                        ->orderBy('toDate')
                                        ->get();
        $feetotal = $feeheads->sum('amount');
        //dd($transaction->details);   
        //return response()->json(['Status' => $transaction], 404, ['app-status' => 'success']);     
        $pdf = PDF::loadView('schools.buses.print_receipt', ['margin_top' => 20], compact('transaction', 'school', 'student', 'feetotal'));
        return $pdf->stream('feereceipt.pdf');
    }

    
    
    public function printBusReceipt($id){
        $transaction = \App\BusTransaction::where('idBusTransaction', '=', $id)->first();
        $student = \App\AdmEntry::where('idStudent', '=', $transaction->idStudent)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
        //Get All feehead
        
        if($student->idSchool == 14){
            $feehead_ids = $transaction->details->pluck('idParent')->toArray();
            $demands = \App\NorthFeeHead::select('isParent')->where('isParent', '!=', '0')
                                ->whereIn('idFeehead', $feehead_ids)
                                ->distinct('isParent')
                                ->get();
            if($demands->count() == 0){
                $feehead_ids = $transaction->details->pluck('idBusFeehead')->toArray();
                $demands = \App\NorthFeeHead::select('isParent')->where('isParent', '!=', '0')
                                ->whereIn('idFeehead', $feehead_ids)
                                ->distinct('isParent')
                                ->get();
            }                    
            $student = \App\AdmEntry::where('idStudent', '=', $transaction->idStudent)->first();
            $class_feeheads = \DB::table('northfeeheads')->where('idClass', '=', $student->idClass)
                    ->where('idSection', '=', $student->idSection)
                    ->where('studentCategory', '=', $student->studentType)
                    ->where('isParent',0)
                    ->where('isActive','=','Y')
                    ->whereNull('idStudent');
            $feeheads = \DB::table('northfeeheads')->where('idStudent', '=', $student->idStudent)
                    ->where('isActive','=','Y')
                    ->where('isParent',0)
                    ->union($class_feeheads)
                    ->orderBy('toDate')
                    ->get();
            $feetotal = $feeheads->sum('amount');
            $pdf = PDF::loadView('schools.north.transaction.print_receipt', ['margin_top' => 20], compact('demands','transaction', 'school', 'student', 'feetotal'));
            return $pdf->stream('feereceipt.pdf');
        }else{
             $stdtransport = \App\StudentTransport::where('idStudent', '=', $student->idStudent)->where('idFinancialYear', '=', $student->idFinancialYear)->first();
            $feeheads = \App\BusFeehead::where('idStop', '=', $stdtransport->idStop)
                    ->orderBy('toDate')
                    ->get();
            $feetotal = $feeheads->sum('amount');
    
            $pdf = PDF::loadView('schools.buses.print_receipt', ['margin_top' => 20], compact('transaction', 'school', 'student', 'feetotal'));
            return $pdf->stream('feereceipt.pdf');
        }
    }
    
    public function getDeviceData($id,$busId){
         $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
         $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
         if($school->isActive == 'Y'){
            $gpsData=json_decode($this->getGPSData($school),true);
            //return response()->json(['Status' => gpsData], 404, ['app-status' => 'success']);
            $stdtransport =DB::table('buses')
                            ->where('buses.idBus', '=', $busId)->first();

                if(isset($gpsData['object'])){
                $gpsVehicle=$gpsData['object'];

                
                foreach($gpsVehicle as $vehicles){
                    if($vehicles['speed'] == 0){
                        $vehicles["Status"] = "STOP";
                    }else  $vehicles["Status"] = "MOVING";
                    if($vehicles['name']==$stdtransport->busNo){
                        $vehicles['lattitude'] = $vehicles['latitude'];
                        if( $vehicles['address'] != null)
                        $vehicles['CurrentLocation'] = $vehicles['address'];
                        else $vehicles['CurrentLocation'] = "Address, Not Available";
                        $route = DB::table('busroutes')->where('busroutes.idBus', '=', $busId)->latest()->first();
                        if($route != null)
                        $vehicles["stops"] = DB::table('route_stops')->where('route_stops.idRoute', '=', $route->idRoute)->get();
                        return $vehicles;
                    }
                }
            }
            return response()->json(['Status' => "Failed"], 404, ['app-status' => 'success']);
        }else{
            return response()->json(['success' => "Failed"], 404, ['app-status' => 'success']);
        }
         
    }
    
    public function addPaymentData(Request $request){
        $data=json_decode($request->getContent(), true)["nameValuePairs"];
        $rules = [];
        $rules += [
                'TxnAmount' => 'required',
                'CustomerID' => 'required'
                ];
        $messages = [
            'TxnAmount.required' => 'Some parameters are missing',
            'CustomerID.required' => 'Some parameters are missing'
        ];
        $request = new Request($data);
        $this->validate($request, $rules, $messages);
        $postData=json_decode($request->getContent(), true)["nameValuePairs"];
        
        if($this->isValidHash($postData["ReturnString"]) == 1){
            $onlineTransaction=DB::table('student_transaction_online')->where('idReference',$postData['CustomerID'])->first();
            $isAlreadyExists=DB::table('student_transaction')->where('receiptNo',$postData['TxnReferenceNo'])->first();
             $students = \App\AdmEntry::where('idStudent', '=', $onlineTransaction->idStudent)->first();
                if(isset($isAlreadyExists))
                {
                     return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
                }
            
            //in case of failure
            if($postData['AuthStatus']=="0300"){
                $selectedHeaders=json_decode($onlineTransaction->idFeehead, true);
                $penaltyAmount=$onlineTransaction->penaltyAmount;
                $excessAmount=$onlineTransaction->accessAmount;
                $idPenalty=json_decode($onlineTransaction->penaltyID, true);
                $idExcessAmount=$onlineTransaction->accessID;
                $amount=$onlineTransaction->amount;
                $paidAmount=$postData['TxnAmount'];
                $isFineTrue=0;
                $stdtransaction=null;
                if($amount == $paidAmount){
                    
                  $stdtransaction = new \App\StudentTransaction();
                    $stdtransaction->idStudent = $students->idStudent;
                    $stdtransaction->idFinancialYear = $students->idFinancialYear;
                    $stdtransaction->paymentDate = today_date();
                    $stdtransaction->totalPaid = $postData['TxnAmount'];
                    $stdtransaction->paymentMode = 'Online';
                    $stdtransaction->receiptNo = $postData['TxnReferenceNo'];
                    $stdtransaction->idSchool = $students->idSchool;
                    $stdtransaction->status = 'Success';
                    $stdtransaction->penaltyAmount = $penaltyAmount;
                    $stdtransaction->fine = $onlineTransaction->penaltyAmount-$penaltyAmount;
                    $stdtransaction->discount = 0;
                    $stdtransaction->save();

                    $totalFine = 0;
                    $totalDiscount = 0;
                    
                    //for loop for headers
                    $totalDiscount=0;
                    $selectedHeaders = json_decode($onlineTransaction->idFeehead, true);
                    
                    foreach($selectedHeaders as $headers){
                        if(isset($headers)){
                            $subheaders = \App\NorthFeeHead::where('isParent','=',$headers)->get()->toArray();
                            
                            foreach($subheaders as $headerIds)
                                {
                                    $stdtransaction_detail = new \App\StudentTransactionDetail();
                                    $stdtransaction_detail->idStudent = $students->idStudent;
                                    $stdtransaction_detail->idTransaction = $stdtransaction->idTransaction;
                                    $stdtransaction_detail->idFeehead = $headerIds['idFeehead'];
                                    $stdtransaction_detail->paymentDate = today_date();
                        
                                    $stdtransaction_detail->amountPaid = $headerIds['amount'];
                                    $stdtransaction_detail->fine = 0;
                                    $stdtransaction_detail->isNorth = 2;
                                    $stdtransaction_detail->discount = $headerIds['discount'];
                                    $totalDiscount=$totalDiscount+$headerIds['discount'];
                                    $stdtransaction_detail->save();
                                }
                        }
                    }
                    
                    if($totalDiscount >0){
                        $stdtransaction->discount = $totalDiscount;
                        $stdtransaction->update(); 
                    }
                    DB::table('student_transaction_online')
                                ->where('idOnline', $onlineTransaction->idOnline)
                                ->update([
                                    'onlineTransactionId' => $postData['TxnReferenceNo'],
                                    'paymentDate' => today_date(),
                                    'code' => $postData['AuthStatus'],
                                    'status' => 'Success',
                                    'remarks' =>$postData['BankID'],
                                    'errorMessage' => $postData['ErrorDescription']
                        ]);
                      return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
                }else{
                    return response()->json(['success' => "Failed"], 200, ['app-status' => 'success']);
                }
            }else{
                $stdtransaction = new \App\StudentTransaction();
                     $stdtransaction->paymentDate = today_date();
                    $stdtransaction->totalPaid = $postData['TxnAmount'];
                    $stdtransaction->paymentMode = 'Online';
                    $stdtransaction->receiptNo = $postData['TxnReferenceNo'];
                    $stdtransaction->idFinancialYear = $students->idFinancialYear;
                    $stdtransaction->idSchool = $students->idSchool;
                    $stdtransaction->idStudent = $students->idStudent;
                    $stdtransaction->status = 'Cancelled';
                    $stdtransaction->fine = 0;
                    $stdtransaction->excessAmountUsed = 0;
                    $stdtransaction->penaltyAmount = 0;
                    $stdtransaction->discount = 0;
                    $stdtransaction->save();

                    DB::table('student_transaction_online')
                            ->where('idOnline', $onlineTransaction->idOnline)
                            ->update([
                                'onlineTransactionId' => $postData['TxnReferenceNo'],
                                'paymentDate' => today_date(),
                                'code' => $postData['AuthStatus'],
                                'status' => 'Cancelled',
                                'remarks' =>$postData['BankID'],
                                'errorMessage' => $postData['ErrorDescription']
                    ]);
                    
                    return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
            }
        }else{
            return response()->json(['success' => "Failed"], 200, ['app-status' => 'success']);
        }
    }
    
    public function addBusPaymentData(Request $request){
        $data=json_decode($request->getContent(), true)["nameValuePairs"];
        $rules = [];
        $rules += [
                'TxnAmount' => 'required',
                'CustomerID' => 'required'
                ];
        $messages = [
            'TxnAmount.required' => 'Some parameters are missing',
            'CustomerID.required' => 'Some parameters are missing'
        ];
        $request = new Request($data);
        $this->validate($request, $rules, $messages);
        $postData=json_decode($request->getContent(), true)["nameValuePairs"];
        
        if($this->isValidBusHash($postData["ReturnString"]) == 1){
            $onlineTransaction=DB::table('student_transaction_online')->where('idReference',$postData['CustomerID'])->first();
            $isAlreadyExists=DB::table('bus_transaction')->where('receiptNo',$postData['TxnReferenceNo'])->first();
             $students = \App\AdmEntry::where('idStudent', '=', $onlineTransaction->idStudent)->first();
                if(isset($isAlreadyExists))
                {
                     return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
                }
            
            //in case of failure
            if($postData['AuthStatus']=="0300"){
                $selectedHeaders=json_decode($onlineTransaction->idFeehead, true);
                $penaltyAmount=$onlineTransaction->penaltyAmount;
                $excessAmount=$onlineTransaction->accessAmount;
                $idPenalty=json_decode($onlineTransaction->penaltyID, true);
                $idExcessAmount=$onlineTransaction->accessID;
                $amount=$onlineTransaction->amount;
                $paidAmount=$postData['TxnAmount'];
                $isFineTrue=0;
                $stdtransaction=null;
                if($amount == $paidAmount){
                    
                  $stdtransaction = new \App\BusTransaction();
                    $stdtransaction->idStudent = $students->idStudent;
                    $stdtransaction->idFinancialYear = $students->idFinancialYear;
                    $stdtransaction->paymentDate = today_date();
                    $stdtransaction->totalPaid = $postData['TxnAmount'];
                    $stdtransaction->paymentMode = 'Online';
                    $stdtransaction->receiptNo = $postData['TxnReferenceNo'];
                    $stdtransaction->idSchool = $students->idSchool;
                    $stdtransaction->status = 'Success';
                    $stdtransaction->penaltyAmount = $penaltyAmount;
                    $stdtransaction->fine = $onlineTransaction->penaltyAmount-$penaltyAmount;
                    $stdtransaction->discount = 0;
                    $stdtransaction->save();

                    $totalFine = 0;
                    $totalDiscount = 0;
                    
                    //for loop for headers
                    $totalDiscount=0;
                    $selectedHeaders = json_decode($onlineTransaction->idFeehead, true);
                    
                    foreach($selectedHeaders as $headers){
                        if(isset($headers)){
                            $subheaders = \App\NorthFeeHead::where('isParent','=',$headers)->get()->toArray();
                            
                             foreach($subheaders as $headerIds)
                                {
                                    $stdtransaction_detail = new \App\BusTransactionDetail();
                                    $stdtransaction_detail->idStudent = $students->idStudent;
                                    $stdtransaction_detail->idBusTransaction = $stdtransaction->idBusTransaction;
                                    $stdtransaction_detail->idBusFeehead = $headerIds['idFeehead'];
                                    $stdtransaction_detail->paymentDate = today_date();
                        
                                    $stdtransaction_detail->amountPaid = $headerIds['amount'];
                                    $stdtransaction_detail->fine = 0;
                                    $stdtransaction_detail->isNorth = 2;
                                    $stdtransaction_detail->discount = $headerIds['discount'];
                                    $totalDiscount=$totalDiscount+$headerIds['discount'];
                                    $stdtransaction_detail->save();
                                }
                        }
                    }
                    
                    if($totalDiscount >0){
                        $stdtransaction->discount = $totalDiscount;
                        $stdtransaction->update(); 
                    }
                    DB::table('student_transaction_online')
                                ->where('idOnline', $onlineTransaction->idOnline)
                                ->update([
                                    'onlineTransactionId' => $postData['TxnReferenceNo'],
                                    'paymentDate' => today_date(),
                                    'code' => $postData['AuthStatus'],
                                    'status' => 'Success',
                                    'remarks' =>$postData['BankID'],
                                    'errorMessage' => $postData['ErrorDescription']
                        ]);
                      return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
                }else{
                    return response()->json(['success' => "Failed"], 200, ['app-status' => 'success']);
                }
            }else{
                $stdtransaction = new \App\BusTransaction();
                     $stdtransaction->paymentDate = today_date();
                    $stdtransaction->totalPaid = $postData['TxnAmount'];
                    $stdtransaction->paymentMode = 'Online';
                    $stdtransaction->receiptNo = $postData['TxnReferenceNo'];
                    $stdtransaction->idFinancialYear = $students->idFinancialYear;
                    $stdtransaction->idSchool = $students->idSchool;
                    $stdtransaction->idStudent = $students->idStudent;
                    $stdtransaction->status = 'Cancelled';
                    $stdtransaction->fine = 0;
                    $stdtransaction->excessAmountUsed = 0;
                    $stdtransaction->penaltyAmount = 0;
                    $stdtransaction->discount = 0;
                    $stdtransaction->save();

                    DB::table('student_transaction_online')
                            ->where('idOnline', $onlineTransaction->idOnline)
                            ->update([
                                'onlineTransactionId' => $postData['TxnReferenceNo'],
                                'paymentDate' => today_date(),
                                'code' => $postData['AuthStatus'],
                                'status' => 'Cancelled',
                                'remarks' =>$postData['BankID'],
                                'errorMessage' => $postData['ErrorDescription']
                    ]);
                    
                    return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
            }
        }else{
            return response()->json(['success' => "Failed"], 200, ['app-status' => 'success']);
        }
    }
    
    public function addHostelPaymentData(Request $request){
        $data=json_decode($request->getContent(), true)["nameValuePairs"];
        $rules = [];
        $rules += [
                'TxnAmount' => 'required',
                'CustomerID' => 'required'
                ];
        $messages = [
            'TxnAmount.required' => 'Some parameters are missing',
            'CustomerID.required' => 'Some parameters are missing'
        ];
        $request = new Request($data);
        $this->validate($request, $rules, $messages);
        $postData=json_decode($request->getContent(), true)["nameValuePairs"];
        
        if($this->isValidHostelHash($postData["ReturnString"]) == 1){
            $onlineTransaction=DB::table('student_transaction_online')->where('idReference',$postData['CustomerID'])->first();
            $isAlreadyExists=DB::table('hostel_transaction')->where('receiptNo',$postData['TxnReferenceNo'])->first();
            $students = \App\AdmEntry::where('idStudent', '=', $onlineTransaction->idStudent)->first();
                if(isset($isAlreadyExists))
                {
                     return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
                }
            DB::table('student_transaction_online')
                                ->where('idOnline', $onlineTransaction->idOnline)
                                ->update([
                                    'onlineTransactionId' => $postData['TxnReferenceNo'],
                                    'paymentDate' => today_date(),
                                    'code' => $postData['AuthStatus'],
                                    'status' => 'Success',
                                    'remarks' =>$postData['BankID'],
                                    'errorMessage' => $postData['ErrorDescription']
                        ]);    
            
            //in case of failure
            if($postData['AuthStatus']=="0300"){
                $selectedHeaders=json_decode($onlineTransaction->idFeehead, true);
                $penaltyAmount=$onlineTransaction->penaltyAmount;
                $excessAmount=$onlineTransaction->accessAmount;
                $idPenalty=json_decode($onlineTransaction->penaltyID, true);
                $idExcessAmount=$onlineTransaction->accessID;
                $amount=$onlineTransaction->amount;
                $paidAmount=$postData['TxnAmount'];
                $isFineTrue=0;
                $stdtransaction=null;
                if($amount == $paidAmount){
                    
                  $stdtransaction = new \App\HostelTransaction();
                    $stdtransaction->idStudent = $students->idStudent;
                    $stdtransaction->idFinancialYear = $students->idFinancialYear;
                    $stdtransaction->paymentDate = today_date();
                    $stdtransaction->totalPaid = $postData['TxnAmount'];
                    $stdtransaction->paymentMode = 'Online';
                    $stdtransaction->receiptNo = $postData['TxnReferenceNo'];
                    $stdtransaction->idSchool = $students->idSchool;
                    $stdtransaction->status = 'Success';
                    $stdtransaction->penaltyAmount = $penaltyAmount;
                    $stdtransaction->fine = $onlineTransaction->penaltyAmount-$penaltyAmount;
                    $stdtransaction->discount = 0;
                    $stdtransaction->save();

                    $totalFine = 0;
                    $totalDiscount = 0;
                    
                    //for loop for headers
                    $totalDiscount=0;
                    $selectedHeaders = json_decode($onlineTransaction->idFeehead, true);
                    
                    foreach($selectedHeaders as $headers){
                        if(isset($headers)){
                            $subheaders = \App\NorthFeeHead::where('isParent','=',$headers)->get()->toArray();
                            
                            foreach($subheaders as $headerIds)
                                {
                                    $stdtransaction_detail = new \App\HostelTransactionDetail();
                                    $stdtransaction_detail->idStudent = $students->idStudent;
                                    $stdtransaction_detail->idHostelTransaction = $stdtransaction->idHostelTransaction;
                                    $stdtransaction_detail->idFeehead = $headerIds['idFeehead'];
                                    
                                    $stdtransaction_detail->paymentDate = today_date();
                        
                                    $stdtransaction_detail->amountPaid = $headerIds['amount'];
                                    $stdtransaction_detail->fine = 0;
                                    $stdtransaction_detail->isNorth = 2;
                                    $stdtransaction_detail->discount = $headerIds['discount'];
                                    $totalDiscount=$totalDiscount+$headerIds['discount'];
                                    $stdtransaction_detail->save();
                                }
                        }
                    }
                    
                    if($totalDiscount >0){
                        $stdtransaction->discount = $totalDiscount;
                        $stdtransaction->update(); 
                    }
                      return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
                }else{
                    return response()->json(['success' => "Failed"], 200, ['app-status' => 'success']);
                }
            }else{
                $stdtransaction = new \App\HostelTransaction();
                     $stdtransaction->paymentDate = today_date();
                    $stdtransaction->totalPaid = $postData['TxnAmount'];
                    $stdtransaction->paymentMode = 'Online';
                    $stdtransaction->receiptNo = $postData['TxnReferenceNo'];
                    $stdtransaction->idFinancialYear = $students->idFinancialYear;
                    $stdtransaction->idSchool = $students->idSchool;
                    $stdtransaction->idStudent = $students->idStudent;
                    $stdtransaction->status = 'Cancelled';
                    $stdtransaction->fine = 0;
                    $stdtransaction->excessAmountUsed = 0;
                    $stdtransaction->penaltyAmount = 0;
                    $stdtransaction->discount = 0;
                    $stdtransaction->save();

                    DB::table('student_transaction_online')
                            ->where('idOnline', $onlineTransaction->idOnline)
                            ->update([
                                'onlineTransactionId' => $postData['TxnReferenceNo'],
                                'paymentDate' => today_date(),
                                'code' => $postData['AuthStatus'],
                                'status' => 'Cancelled',
                                'remarks' =>$postData['BankID'],
                                'errorMessage' => $postData['ErrorDescription']
                    ]);
                    
                    return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
            }
        }else{
            return response()->json(['success' => "Failed"], 200, ['app-status' => 'success']);
        }
    }
    
    /* 
    function updateOnlineTransaction($onlineID,$postData){
       if(DB::table('student_transaction_online')
            ->where('idOnline', $onlineID)
            ->update(['onlineTransactionId' => $postData['TxnReferenceNo'],
            'status'=>$postData['AuthStatus']=="0300"?"Success":"Cancelled",
            'errorMessage'=>$postData['ErrorDescription'],
            'code'=>$postData['AuthStatus'],
            'remarks'=>$postData['BankID']]))
        return 1;
        else return 0;
            
    }*/
    
    
    function isValidHash($response){
        $response='ASPCS'.$response;
      
        $post_data=explode("|",$response);
        $hash_data=$post_data[0];
        for ($i=1;$i<sizeof($post_data)-2;$i++) {
    		$hash_data .= '|' .($post_data[$i]);
    	}
    	$checksum = hash_hmac('sha256',$hash_data,'3MZYkfUVPdW0', false); 
    	$checksum = strtoupper($checksum);
    	
    	$valid_hash = ($post_data[sizeof($post_data)-2]==$checksum)?'Yes':'No';
    	if($valid_hash == 'Yes') {
    	    return 1;
    	}else return 0;
    }
   
   function isValidBusHash($response){
        $response='ASPCSTFEE|'.$response;
      
        $post_data=explode("|",$response);
        $hash_data=$post_data[0];
        for ($i=1;$i<sizeof($post_data)-2;$i++) {
    		$hash_data .= '|' .($post_data[$i]);
    	}
    	$checksum = hash_hmac('sha256',$hash_data,'tMOaMSP14Aj3AgK5U63YUfl4trCbw34D', false); 
    	$checksum = strtoupper($checksum);
    	
    	$valid_hash = ($post_data[sizeof($post_data)-2]==$checksum)?'Yes':'No';
    	if($valid_hash == 'Yes') {
    	    return 1;
    	}else return 0;
    }
    
   function isValidHostelHash($response){
        $response='ASPCSHFEE|'.$response;
      
        $post_data=explode("|",$response);
        $hash_data=$post_data[0];
        for ($i=1;$i<sizeof($post_data)-2;$i++) {
    		$hash_data .= '|' .($post_data[$i]);
    	}
    	$checksum = hash_hmac('sha256',$hash_data,'D4oiuL6drtAx8A15r3IluOuXLuKWBmzO', false); 
    	$checksum = strtoupper($checksum);
    	
    	$valid_hash = ($post_data[sizeof($post_data)-2]==$checksum)?'Yes':'No';
    	if($valid_hash == 'Yes') {
    	    return 1;
    	}else return 0;
    }
    
    /*function updateFine($transactionID,$selectedHeaders){
        $transactions=\App\StudentTransactionDetail::where('idTransaction', '=', $transactionID)->get();
        foreach($transactions as $details){
                if($details->idFeehead == $selectedHeaders )
                {
                    $details->amountPaid= ( $details->amountPaid - $details->fine ) + 500;
                    $details->fine = 500;
                }
                else
                {
                    $details->amountPaid= ( $details->amountPaid - $details->fine );
                    $details->fine = 0;
                }
                $details->update();
        }
        return 1;
    } 
    
    function isLeeserHeader($postData,$onlineTransaction,$idPaidHeader){
         $lesser_transaction = DB::table('lesser_transaction_details')
                ->where('idStudent', '=', $onlineTransaction->idStudent)
                ->where('idFeehead', '=', $idPaidHeader)
                ->first();
        if(isset($lesser_transaction)){
             $stdtransaction = $this->addLesserTransaction($postData,$onlineTransaction);
             if($stdtransaction){
                
                    $stepDiscount = 0;
                    $stepFine = 0;
                    $stepAmount=0;
                    $headerObject = \App\FeeHead::where('idFeehead', '=', $idPaidHeader)->first()->toArray();
                    $date = Carbon::parse($headerObject['toDate']);
                    $now = Carbon::now();
                    $diff = $date->diffInDays($now, false);
            
                    if ($diff > 0) {
                        if ($headerObject['fine'] != null && $headerObject['fine'] != 0.00) {
                            $stepFine = ( $headerObject['fine'] * $diff);
                        } else
                        if ($headerObject['flatFine'] != null) {
                            $stepFine = $stepFine + $headerObject['flatFine'];
                        }
                    }
            
                    $discountfees = DB::table('student_discounts')->where('idFinancialYear', '=', $onlineTransaction->idFinancialYear)->where('idStudent', '=', $onlineTransaction->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\LesserTransactionDetail();
                    $stdtransaction_detail->idStudent = $onlineTransaction->idStudent;
                    $stdtransaction_detail->idLesserTransaction = $stdtransaction->idLesserTransaction;
                    $stdtransaction_detail->idFeehead = $idPaidHeader;
                    $stdtransaction_detail->paymentDate =  today_date();
                    
                    $stdtransaction_detail->amountPaid =$stepAmount;
                    if($postData['AuthStatus']=="0300")
                    $stdtransaction_detail->status="Success";
                    else $stdtransaction_detail->status="Cancelled";
        
                    $stdtransaction_detail->fine = $stepFine;
                    $stdtransaction_detail->discount = $stepDiscount;
                    $stdtransaction_detail->save();
    
                   return 1;    
             }else return 0;
        }else return 0;        
    }
    
    function addLesserTransaction($postData,$onlineTransaction){
        $stdtransaction = new \App\LesserTransaction();
        $stdtransaction->paymentDate = today_date();
        $stdtransaction->receiptNo = $postData['TxnReferenceNo'];
        $stdtransaction->idSchool = \App\AdmEntry::where('idStudent', '=', $onlineTransaction->idStudent)->first()->idSchool;
        $stdtransaction->idFinancialYear =$onlineTransaction->idFinancialYear ;
        $stdtransaction->idStudent = $onlineTransaction->idStudent;
        $stdtransaction->totalPaid =$onlineTransaction->amount;
        $stdtransaction->paymentMode = "Online";
        if($postData['AuthStatus']=="0300")
        {
            $stdtransaction->status="Success";
            $stdtransaction->excessAmountUsed = $onlineTransaction->accessAmount;
            if($onlineTransaction->accessID != 0)
           if($onlineTransaction->accessID != 0)
            {
                $stdtransaction->idExcessTransaction = $onlineTransaction->accessID;
                $excess = \App\ExcessTransaction::where('idExcessTransaction', '=', $onlineTransaction->accessID)->first(); //idTransaction is the  idExcessTransaction in excess table
                $excess->isActive = 'N';
                $excess->update();
            }
        }
        else $stdtransaction->status="Cancelled";
        $stdtransaction->penaltyAmount = $onlineTransaction->penaltyAmount;
        $stdtransaction->fine = 0;
        $stdtransaction->discount = 0;
       
        $stdtransaction->save();
        return  $stdtransaction;
            
    }
    
    function addSuccessTransaction($postData,$onlineTransaction){
        $stdtransaction = new \App\StudentTransaction();
        $stdtransaction->paymentDate = today_date();
        $stdtransaction->receiptNo = $postData['TxnReferenceNo'];
        $stdtransaction->idSchool = \App\AdmEntry::where('idStudent', '=', $onlineTransaction->idStudent)->first()->idSchool;
        $stdtransaction->idFinancialYear =$onlineTransaction->idFinancialYear ;
        $stdtransaction->idStudent = $onlineTransaction->idStudent;
        $stdtransaction->totalPaid =$onlineTransaction->amount;
        $stdtransaction->paymentMode = "Online";
        if($postData['AuthStatus']=="0300")
        {
            $stdtransaction->status="Success";
            $stdtransaction->excessAmountUsed = $onlineTransaction->accessAmount;
            if($onlineTransaction->accessID != 0)
            {
                $stdtransaction->idExcessTransaction = $onlineTransaction->accessID;
                $excess = \App\ExcessTransaction::where('idExcessTransaction', '=', $onlineTransaction->accessID)->first(); //idTransaction is the  idExcessTransaction in excess table
                $excess->isActive = 'N';
                $excess->update();
            }
        }
        else $stdtransaction->status="Cancelled";
        $stdtransaction->penaltyAmount = $onlineTransaction->penaltyAmount;
        $stdtransaction->fine = 0;
        $stdtransaction->discount = 0;
        $stdtransaction->save();
        return  $stdtransaction;
    }
    
    function addZeroTransaction(){
        
    }*/
   
    
    public function getGPSData($school){
        $endpoint = "http://track2.tpgpstrack.com/api/middleMan/getDeviceInfo";
        $client = new \GuzzleHttp\Client(['http_errors' => false]);
        $response = $client->request('GET', $endpoint, ['query' => [
            'accessToken' => $school->api_token
        ]]);
        $statusCode = $response->getStatusCode();
        if($statusCode==404) 
        return "";
        $content = $response->getBody();
        
        return $content;
    }
    
    public function addAttendance($id){
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $student->idSchool)->first();
         $current_timestamp = Carbon::now()->toDateTimeString();
        if($school->isActive == 'Y' && $student->isActive == 'Y'){
            
            $prevAttendance = \App\Attendance::where('Enrollment_Number', '=',$student->ecNo)
                        ->where('idSchool',$student->idSchool)
                        ->where('idType','M')
                        ->where('date',Carbon::parse($current_timestamp)->format('Y-m-d'))->first();
            if($prevAttendance){
                return response()->json(['success' => "Attendance has been marked","message" => "Redirecting.."], 200, ['app-status' => 'success']);
            }
            
            $attendance = new \App\Attendance();
            $attendance->Enrollment_Number = $student->ecNo;
            $attendance->idType='M';
            $attendance->status='P';
           
            $attendance->TimeStamp=Carbon::now()->timestamp;
            $attendance->idMonth=Carbon::createFromFormat('Y-m-d H:i:s', $current_timestamp)->month;
            $attendance->idSchool=$student->idSchool;
            $attendance->date=Carbon::parse($current_timestamp)->format('d-m-Y');
            $attendance->save();
            return response()->json(['success' => "Your attendance has been marked successfully"], 200, ['app-status' => 'success']);
        }else{
             return response()->json(['success' => "Failed to mark attendance try again"], 200, ['app-status' => 'success']);
        }
    }
    
    public function getLiveTV(){
         $school = \App\School::where('idSchool', '=', 14)->first();
         return response()->json(['success' => $school->livestream], 200, ['app-status' => 'success']);
    }

    function fys($user){
            $now = \Carbon\Carbon::now();
            $finyear = \App\FinancialYear::where('idSchool', '=', $user->idSchool)->get();
            foreach ($finyear as $fy) {
                $start_date = \Carbon\Carbon::parse($fy->startDate);
                $end_date = \Carbon\Carbon::parse($fy->endDate);
                if ($now->between($start_date, $end_date) == true || $end_date->diffInDays($now) == 0) {
                    return $fy->idFinancialYear;
                }
            }
        }
    
    /*
    
    $headerObject = \App\FeeHead::where('idFeehead', '=', $idHeaders)->first();
                  if(isset($headerObject)){
                  if($this->isLeeserHeader($postData,$onlineTransaction,$idHeaders)==0){
                      if($stdtransaction==null)
                      $stdtransaction=$this->addSuccessTransaction($postData,$onlineTransaction);
                      //Store details also
                        $stepDiscount = 0;
                        $stepFine = 0;
                        $stepAmount=0;
                            $headerObject=$headerObject->toArray();
                            $date = Carbon::parse($headerObject['toDate']);
                            $now = Carbon::now();
                            $diff = $date->diffInDays($now, false);
                    
                            if($diff > 0){
                                if($diff==0){
                                    $stepFine=$stepFine+0;
                                }elseif($diff > 90){
                                    $isFineTrue=$idHeaders;
                                }elseif($diff <= 30 ){
                                    $stepFine=$stepFine+100;
                                }elseif($diff <= 60){
                                    $stepFine=$stepFine+200;
                                }else{
                                    $stepFine=$stepFine+500;
                                }
                            }
                            $discountfees = DB::table('student_discounts')->where('idFinancialYear', '=', $onlineTransaction->idFinancialYear)->where('idStudent', '=', $onlineTransaction->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->idStudent = $onlineTransaction->idStudent;
                            $stdtransaction_detail->idTransaction = $stdtransaction->idTransaction;
                            $stdtransaction_detail->idFeehead = $idHeaders;
                            $stdtransaction_detail->paymentDate =  today_date();
                            
                            $stdtransaction_detail->amountPaid =$stepAmount;
                            if($postData['AuthStatus']=="0300")
                            $stdtransaction_detail->status="Success";
                            else $stdtransaction_detail->status="Cancelled";
                
                            $stdtransaction_detail->fine = $stepFine;
                            $stdtransaction_detail->discount = $stepDiscount;
                            $stdtransaction_detail->save();
                        }
                  }
                   if($isFineTrue > 0) $this->updateFine($stdtransaction->idTransaction,$isFineTrue);
                  
                 
    */

}

Copyright © 2021 - 2025 IMMREX7