IMMREX7

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

<?php

namespace App\Http\Controllers\School;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\School;
use Auth;
use Carbon\Carbon;
use \App\Http\WeatherApi;
use \App\Http\SendNotificationApi;
use DB;
use Session;

class SchoolController extends Controller {

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    protected $redirectTo = '/school';

    public function __construct() {
        $this->middleware('auth:school');
    }
    
    private function fetchLessTransaction($data){
        $transaction = DB::table('lesser_transaction')
        ->where('idSchool', Auth::guard('school')->user()->idSchool)
        ->where('idFinancialYear', Session::get('idFinancialYear'));
        if($data == "bounced")
        $transaction = $transaction->where('status','Bounced');
        else if($data == "tcheque")
        $transaction = $transaction->where(function($query) {
            $query->whereNull('status');
            $query->orWhere('status', '=', 'Cleared');
            $query->orWhere('status', '=', 'In-Process');
            $query->orWhere('status', '=', 'Success');
            $query->orWhere('status', '=', 'Bounced');
        });
        else
        $transaction = $transaction->where(function($query) {
            $query->whereNull('status');
            $query->orWhere('status', '=', 'Cleared');
            $query->orWhere('status', '=', 'In-Process');
            $query->orWhere('status', '=', 'Success');
        });
        if($data == "collection") return $transaction = $transaction->sum('totalPaid');
        if($data == "cash") return $transaction = $transaction->where('paymentMode','Cash')->sum('totalPaid');
        if($data == "cheque") return $transaction = $transaction->where('paymentMode','Cheque')->sum('totalPaid');
        if($data == "tcheque") return $transaction = $transaction->where('paymentMode','Cheque')->sum('totalPaid');
        if($data == "bounced") return $transaction = $transaction->where('paymentMode','Cheque')->sum('totalPaid');
        if($data == "online") return $transaction = $transaction->whereNotIn('paymentMode',['Cheque','Cash'])->sum('totalPaid');
    }
    private function fetchTransaction($data){
        $transaction = DB::table('student_transaction')
        ->where('idSchool', Auth::guard('school')->user()->idSchool)
        ->where('idFinancialYear', Session::get('idFinancialYear'));
        if($data == "bounced")
        $transaction = $transaction->where('status','Bounced');
        else if($data == "tcheque")
        $transaction = $transaction->where(function($query) {
            $query->whereNull('status');
            $query->orWhere('status', '=', 'Cleared');
            $query->orWhere('status', '=', 'In-Process');
            $query->orWhere('status', '=', 'Success');
            $query->orWhere('status', '=', 'Bounced');
        });
        else
        $transaction = $transaction->where(function($query) {
            $query->whereNull('status');
            $query->orWhere('status', '=', 'Cleared');
            $query->orWhere('status', '=', 'In-Process');
            $query->orWhere('status', '=', 'Success');
        });
        if($data == "collection") return $transaction = $transaction->sum('totalPaid');
        if($data == "cash") return $transaction = $transaction->where('paymentMode','Cash')->sum('totalPaid');
        if($data == "cheque") return $transaction = $transaction->where('paymentMode','Cheque')->sum('totalPaid');
        if($data == "tcheque") return $transaction = $transaction->where('paymentMode','Cheque')->sum('totalPaid');
        if($data == "bounced") return $transaction = $transaction->where('paymentMode','Cheque')->sum('totalPaid');
        if($data == "online") return $transaction = $transaction->whereNotIn('paymentMode',['Cheque','Cash'])->sum('totalPaid');
    }
    public function financialDashboard(Request $request) {
       $uid = '';
       if($request->get('url') != null && $request->get('url') != ""){
            $uid = $this->guidv4();
            DB::table('student_payment_session')->insert([
                'idSchool' => Auth::guard('school')->user()->idSchool,
                'idStudent' => Session::get('idFinancialYear'),
                'idExam' => 0,
                'uhid' => $uid
            ]);
       } 
       $data = [];
       $financialYear = DB::table('financial_years')->where('idSchool', Auth::guard('school')->user()->idSchool)->where('idFinancialYear',Session::get('idFinancialYear'))->first();
       $classes = DB::table('classes')->where('idSchool', Auth::guard('school')->user()->idSchool)->get();
       $data['total_collection'] = $this->fetchTransaction("collection") + $this->fetchLessTransaction("collection");
       $data['cash'] = $this->fetchTransaction("cash") + $this->fetchLessTransaction("cash");
       $data['cheque'] = $this->fetchTransaction("cheque") + $this->fetchLessTransaction("cheque");
       $data['online'] = $this->fetchTransaction("online") + $this->fetchLessTransaction("online");
       $data['tcheque'] = $this->fetchTransaction("tcheque") + $this->fetchLessTransaction("tcheque");
       $data['bounced'] = $this->fetchTransaction("bounced") + $this->fetchLessTransaction("bounced");
       $data['estimated_fees'] = 0;
       $data['overdue_fees'] = 0;
        
        $classesArr = DB::table('classes')->where('idSchool', Auth::guard('school')->user()->idSchool)->get()->pluck('idClass')->toArray();
        foreach($classesArr as $key =>$value){
            $data['class_'.$value] = 0;
            $data['overdue_class_'.$value] = 0;
        }
        $students = DB::table('students')->select('idClass','idSection','idStudent','idFinancialYear','studentType','idSchool')->whereIn('idClass',$classesArr)->where('idFinancialYear',Session::get('idFinancialYear'))->where('idSchool', Auth::guard('school')->user()->idSchool)->where('isActive','Y')->groupBy('idClass','idSection','idStudent','idFinancialYear','studentType','idSchool')->get();
        foreach($students as $student){
            if($student->idSchool == 25){
                //fetch plan
                $plan = 'Plan A';
                $header = \App\StudentTransaction::select('feeheadLabel')->join('student_transaction_details','student_transaction.idTransaction','=','student_transaction_details.idTransaction')
                            ->join('feeheads','student_transaction_details.idFeehead','=','feeheads.idFeehead')
                            ->where('student_transaction.idStudent', '=', $student->idStudent)
                            ->where('student_transaction.idFinancialYear',$student->idFinancialYear)
                            ->whereIn('feeheadLabel',['Plan A','Plan B','Plan C'])
                            ->where(function($query) {
                                $query->whereNull('student_transaction.status');
                                $query->orWhere('student_transaction.status', '=', 'In-Process');
                                $query->orWhere('student_transaction.status', '=', 'Cleared');
                                $query->orWhere('student_transaction.status', '=', 'Success');
                            })->first();
                if($header != null){
                    if (str_contains($header->feeheadLabel, 'Plan A')) {
                        $plan = 'Plan A';
                    }else if (str_contains($header->feeheadLabel, 'Plan B')) {
                        $plan = 'Plan B';
                    }else if (str_contains($header->feeheadLabel, 'Plan C')) {
                        $plan = 'Plan C';
                    }
                }
                $class_feeheads = DB::table('feeheads')->where('idClass', '=', $student->idClass)
                        ->where('idSection', '=', $student->idSection)
                        ->where('idFinancialYear','=', $student->idFinancialYear)
                        ->where('studentCategory', '=', $student->studentType)
                        ->where('feeheadLabel', 'LIKE', $plan.'%')
                        ->whereNull('idStudent');
                $allcat_feeheads = DB::table('feeheads')->where('idClass', '=', $student->idClass)
                        ->where('idSection', '=', $student->idSection)
                        ->where('studentCategory', '=', 'All')
                        ->where('idFinancialYear','=', $student->idFinancialYear)
                        ->where('feeheadLabel', 'LIKE', $plan.'%')
                        ->whereNull('idStudent');
                $feeheads = DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                        ->where('idFinancialYear','=', $student->idFinancialYear)
                        ->where('feeheadLabel', 'LIKE', $plan.'%')
                        ->union($class_feeheads)
                        ->union($allcat_feeheads)
                        ->orderBy('idFeehead','ASC')
                        ->orderBy('toDate')
                        ->get();
                $data['estimated_fees'] = $data['estimated_fees'] + $feeheads->sum('amount');   
                $data['class_'.$student->idClass] = $data['class_'.$student->idClass] + $feeheads->sum('amount');   
            }else if($student->idSchool == 140 || $student->idSchool == 135 || $student->idSchool == 159 || $student->idSchool == 160 || $student->idSchool == 139){
                $plan = 'Plan A';
                $header = \App\StudentTransaction::select('feeheadLabel')->join('student_transaction_details','student_transaction.idTransaction','=','student_transaction_details.idTransaction')
                            ->join('feeheads','student_transaction_details.idFeehead','=','feeheads.idFeehead')
                            ->where('student_transaction.idStudent', '=', $student->idStudent)
                            ->where('student_transaction.idFinancialYear',$student->idFinancialYear)
                            ->where(function($query) {
                                $query->whereNull('student_transaction.status');
                                $query->orWhere('student_transaction.status', '=', 'In-Process');
                                $query->orWhere('student_transaction.status', '=', 'Cleared');
                                $query->orWhere('student_transaction.status', '=', 'Success');
                            })->first();
                if($header != null){
                    if (str_contains($header->feeheadName, 'Plan A')) {
                        $plan = 'Plan A';
                    }else if (str_contains($header->feeheadName, 'Plan B')) {
                        $plan = 'Plan B';
                    }
                }
                $class_feeheads = DB::table('feeheads')->where('idClass', '=', $student->idClass)
                        ->where('idSection', '=', $student->idSection)
                        ->where('idFinancialYear','=', $student->idFinancialYear)
                        ->where('studentCategory', '=', $student->studentType)
                        ->where('feeheadName', 'LIKE', $plan.'%')
                        ->whereNull('idStudent');
                $allcat_feeheads = DB::table('feeheads')->where('idClass', '=', $student->idClass)
                        ->where('idSection', '=', $student->idSection)
                        ->where('studentCategory', '=', 'All')
                        ->where('idFinancialYear','=', $student->idFinancialYear)
                        ->where('feeheadName', 'LIKE', $plan.'%')
                        ->whereNull('idStudent');
                $p_feeheads = DB::table('feeheads')->where('idClass', '=', $student->idClass)
                        ->where('idSection', '=', $student->idSection)
                        ->where('studentCategory', '=', 'All')
                        ->where('idFinancialYear','=', $student->idFinancialYear)
                        ->where('feeheadName', 'LIKE', 'P%')
                        ->whereNull('idStudent');   
                $admission_feeheads = DB::table('feeheads')->where('idClass', '=', $student->idClass)
                        ->where('idSection', '=', $student->idSection)
                        ->where('studentCategory', '=', $student->studentType)
                        ->where('idFinancialYear','=', $student->idFinancialYear)
                        ->where('feeheadName', 'LIKE', 'Admission%')
                        ->whereNull('idStudent');       
                $feeheads = DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                        ->where('idFinancialYear','=', $student->idFinancialYear)
                        ->where('feeheadName', 'LIKE', $plan.'%')
                        ->union($class_feeheads)
                        ->union($p_feeheads)
                        ->union($admission_feeheads)
                        ->union($allcat_feeheads)
                        ->orderBy('idFeehead','ASC')
                        ->orderBy('toDate')
                        ->get();       
                $data['estimated_fees'] = $data['estimated_fees'] + $feeheads->sum('amount');
                $amount = getOverdue($student,$plan); 
                $data['overdue_fees'] = $data['overdue_fees'] + $amount;   
                $data['overdue_class_'.$student->idClass] = $data['overdue_class_'.$student->idClass] + $amount;
                $data['class_'.$student->idClass] = $data['class_'.$student->idClass] + $feeheads->sum('amount');
            }else{
                $class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                    ->where('idSection', '=', $student->idSection)
                    ->where('idFinancialYear','=', $student->idFinancialYear)
                    ->where('studentCategory', '=', $student->studentType)
                    ->whereNull('idStudent');
                $allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                        ->where('idSection', '=', $student->idSection)
                        ->where('studentCategory', '=', 'All')
                        ->where('idFinancialYear','=',$student->idFinancialYear)
                        ->whereNull('idStudent');
                $feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                        ->where('idFinancialYear','=', $student->idFinancialYear)
                        ->union($class_feeheads)
                        ->union($allcat_feeheads)
                        ->orderBy('toDate')
                        ->get();
                $data['estimated_fees'] = $data['estimated_fees'] + $feeheads->sum('amount');   
                $data['class_'.$student->idClass] = $data['class_'.$student->idClass] + $feeheads->sum('amount');
            }
        }
       $idSchool =  Auth::guard('school')->user()->idSchool;
       $idFinancialYear = Session::get('idFinancialYear');
       return view('schools.financial-dashboard',compact('data','financialYear','classes','uid','idSchool','idFinancialYear'));
    }

    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 attendanceDashboard(){
        $data = [];
        $data['stotal'] = DB::table('students')->where('idFinancialYear', Session::get('idFinancialYear'))->where('idSchool', Auth::guard('school')->user()->idSchool)->count();
        $data['etotal'] = DB::table('employees')->where('idSchool', Auth::guard('school')->user()->idSchool)->count();

        $data['spresent'] = DB::table('attandance')->select('Enrollment_Number')->whereDate('date', Carbon::now()->format('Y-m-d'))->whereIn('status',['IN','P'])->where('idSchool', Auth::guard('school')->user()->idSchool)->groupBy('Enrollment_Number')->get()->count();
		$data['sabsent'] = $data['etotal'] - $data['spresent'];
		
        $data['epresent'] = DB::table('employee_attendance')->whereDate('date', Carbon::now()->format('Y-m-d'))->whereIn('status',['IN','P'])->where('idSchool', Auth::guard('school')->user()->idSchool)->count();
		$data['eabsent'] = DB::table('employee_attendance')->whereDate('date', Carbon::now()->format('Y-m-d'))->whereNotIn('status',['IN','P','H'])->where('idSchool', Auth::guard('school')->user()->idSchool)->count();
		
        
        $empArr = DB::table('employees')->select('idEmployee','enrollmentNo')->where('idSchool', Auth::guard('school')->user()->idSchool)->get()->pluck('enrollmentNo')->toArray();
        $data['top_emp'] = DB::table('employee_attendance')
                                ->select('Enrollment_Number as ecNo',DB::raw('COUNT(*) as total'))
                                ->where('idMonth', Carbon::now()->format('m'))
                                ->whereDate('date','>=', Carbon::parse("01-".Carbon::now()->format('m')."-".Carbon::now()->format('Y'))->format('Y-m-d'))
                                ->whereIn('status',['IN','P'])
                                ->where('idSchool', Auth::guard('school')->user()->idSchool)
                                ->whereIn('Enrollment_Number',$empArr)
                                ->orderBy('total','DESC')
                                ->groupBy('ecNo')
                                ->limit(5)
                                ->get();
        $tdate = Carbon::now();
        $jdate = $tdate->format('Y-m-d');              
        $emp = DB::table('employees')->select('idEmployee','enrollmentNo')->where('idSchool', Auth::guard('school')->user()->idSchool)->get();
        $school = \App\School::where('idSchool', '=', Auth::guard('school')->user()->idSchool)->first();
        $data['late'] = 0;
        $data['leave'] = 0;
        $data['unapprove'] = 0;
        $data['early'] = 0;
        foreach($emp as $var){
            $late = "00:00";
            $emp_shift = \App\AssignShift::where('idEmployee', '=', $var->idEmployee)->first();
            $lateMaster = \App\LateArrivalMaster::where('idEmployee', '=', $var->idEmployee)->where('idFinancialYear',Session::get('idFinancialYear'))->first();
            if($lateMaster != null){
                $late = $lateMaster->lateAllowed;
            }
            $holiday = \App\HrmsHoliday::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
            ->where('idEmployee',$var->idEmployee)
            ->whereDate('fromDate', '<=', $jdate)
            ->whereDate('toDate', '>=', $jdate)
            ->first();
            $paidLeave = DB::table('employee_leave')
                ->whereDate('leave_from', '<=', $jdate)
                ->whereDate('leave_to', '>=', $jdate)
                ->where('idEmployee', $var->idEmployee)
                ->where('status','Approve with PL(Paid Leave)')
                ->first();
            if($paidLeave != null){
                //on leave
                $data['leave'] = $data['leave'] + 1;
            }    
            $unpaidLeave = DB::table('employee_leave')
                                        ->whereDate('leave_from', '<=', $jdate)
                                        ->whereDate('leave_to', '>=', $jdate)
                                        ->where('idEmployee', $var->idEmployee)
                                        ->where('status','Approve Without PL')
                                        ->first();
            if($unpaidLeave != null){
                //on leave
                $data['leave'] = $data['leave'] + 1;
            } 
            $data['unapprove'] = $data['unapprove'] + DB::table('employee_leave')
                                        ->whereDate('leave_from', '<=', $jdate)
                                        ->whereDate('leave_to', '>=', $jdate)
                                        ->where('idEmployee', $var->idEmployee)
                                        ->whereNull('status')
                                        ->count();

            if ($holiday == null && $emp_shift != null){
                $shifts = DB::table('shift_details')
                            ->select('fromTime','toTime','weekOff')
                            ->join('weekdays', 'shift_details.idWeekday', '=', 'weekdays.idWeekday')
                            ->where('idShift', '=', $emp_shift->idShift)
                            ->where('dayName', '=', date('l', strtotime($tdate)))
                            ->first();
                if($shifts->weekOff == "N"){
                    $aintime = \App\EmpAttendance::where('Enrollment_Number', '=', $var->enrollmentNo)
                                            ->where('Device_ID', '=', $school->Device_ID)
                                            ->whereDate('date', '=', $jdate)
                                            ->where('status','P')
                                            ->first();
                    $intime = \App\EmpAttendance::where('Enrollment_Number', '=', $var->enrollmentNo)
                                            ->where('Device_ID', '=', $school->Device_ID)
                                            ->whereDate('date', '=', $jdate)
                                            ->where('status', '=', 'IN')
                                            ->where('idType', '=', 'A')
                                            ->first();

                    if(isset($intime->TimeStamp)){
                        $start = Carbon::parse($shifts->fromTime);
                        $arrival = Carbon::parse($intime->TimeStamp->format('h:i:s'));
                        $lateTime = $arrival->diffForHumans($start,[]);
                        if(str_contains($lateTime ,"after")){
                            if($late != "00:00"){
                                $allowedTime = explode(':',$late);
                                $addOnMinutes = $allowedTime[0]*60 + $allowedTime[1];
                                $cstart = Carbon::parse($shifts->fromTime)->addMinutes($addOnMinutes);
                                $carrival = Carbon::parse($intime->TimeStamp->format('h:i:s'));
                                if(str_contains($carrival->diffForHumans($cstart,[]) ,"after")){
                                    //late
                                    $data['late'] = $data['late'] + 1;
                                }
                            }else{
                                //late
                                $data['late'] = $data['late'] + 1;
                            }
                        }else{
                            //before
                            $data['early'] = $data['early'] + 1;
                        }
                    }
                }
            }
        }
        $classes = DB::table('classes')->select('idClass','className')->where('idSchool', Auth::guard('school')->user()->idSchool)->orderBy('idClass')->get()->pluck('className')->toArray();
        $classwise = [];
        $classId = DB::table('classes')->select('idClass','className')->where('idSchool', Auth::guard('school')->user()->idSchool)->orderBy('idClass')->get();
        foreach($classId as $var){
            $en =  DB::table('students')->where('idFinancialYear', Session::get('idFinancialYear'))->where('idClass',$var->idClass)->where('idSchool', Auth::guard('school')->user()->idSchool)->pluck('ecNo')->toArray();
            $total = DB::table('attandance')->whereDate('date', Carbon::now()->format('Y-m-d'))->whereIn('Enrollment_Number',$en)->whereIn('status',['IN','P'])->where('idSchool', Auth::guard('school')->user()->idSchool)->count();
            array_push( $classwise,$total);
        }
        return view('schools.attendance-dashboard',compact('data','classes','classwise'));
	}
    
	public function libraryDashboard(){
        $data = [];
        $data['total'] = DB::table('books')->where('idSchool', Auth::guard('school')->user()->idSchool)->count();
        $data['issue'] = DB::table('book_issue_return')->where('idSchool', Auth::guard('school')->user()->idSchool)->where('idFinancialYear', Session::get('idFinancialYear'))->where('isReturn','N')->count();
		$data['return'] = DB::table('book_issue_return')->where('idSchool', Auth::guard('school')->user()->idSchool)->where('idFinancialYear', Session::get('idFinancialYear'))->where('isReturn','Y')->count();
        $data['not-return'] = DB::table('book_issue_return')->whereDate('expectedReturnDate','<',Carbon::now()->format('Y-m-d'))->where('idSchool', Auth::guard('school')->user()->idSchool)->where('idFinancialYear', Session::get('idFinancialYear'))->where('isReturn','N')->count();

        $data['new-book'] = DB::table('books')->where('idSchool', Auth::guard('school')->user()->idSchool)->where('idFinancialYear', Session::get('idFinancialYear'))->count();
        $data['lost-book'] = DB::table('books')->where('idSchool', Auth::guard('school')->user()->idSchool)->where('idFinancialYear', Session::get('idFinancialYear'))->whereNull('bookStatus')->count();
        $data['total-fine'] = DB::table('libraryfines')->where('idSchool', Auth::guard('school')->user()->idSchool)->where('idFinancialYear', Session::get('idFinancialYear'))->sum('amount');
        $data['e-book'] = DB::table('books')->where('idSchool', Auth::guard('school')->user()->idSchool)->whereNotNull('ebook')->where('idFinancialYear', Session::get('idFinancialYear'))->count();

        $types =  DB::table('books')
                  ->join('book_types', 'books.idBookType', '=', 'book_types.idBookType')
                  ->select('typeName',DB::raw('COUNT(*) as total'))
                  ->where('books.idSchool', Auth::guard('school')->user()->idSchool)
                  ->groupBy('typeName')
                  ->get()->pluck('total','typeName')->toArray();

        $issued = DB::table('book_issue_return')
                            ->selectRaw('MONTH(issueDate) as month, COUNT(*) as count')
                            ->where('idSchool', Auth::guard('school')->user()->idSchool)->where('idFinancialYear', Session::get('idFinancialYear'))
                            ->where('isReturn','N')
                            ->groupBy('month')->get()->pluck('count','month')->toArray();
        $returned = DB::table('book_issue_return')
                            ->selectRaw('MONTH(returnDate) as month, COUNT(*) as count')
                            ->where('idSchool', Auth::guard('school')->user()->idSchool)->where('idFinancialYear', Session::get('idFinancialYear'))
                            ->where('isReturn','Y')
                            ->groupBy('month')->get()->pluck('count','month')->toArray();

        $monthName = ['','January','February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; 
        foreach($monthName as $key => $value){
            if(!array_key_exists($key,$issued)){
                $issued[$key] = 0;
            } 
        }
        ksort($issued);
        foreach($monthName as $key => $value){
            if(!array_key_exists($key,$returned)){
                $returned[$key] = 0;
            } 
        }
        ksort($returned);
        array_shift($issued);
        array_shift($returned);
        return view('schools.library-dashboard',compact('data','issued','returned','types'));
	}
	
	public function hostelDashboard(){
        $data = [];
        $data['hostelite'] =  DB::table('hostel_students')->where('idSchool', Auth::guard('school')->user()->idSchool)->where('idFinancialYear', Session::get('idFinancialYear'))->count();
        $data['rooms'] =  DB::table('hostel_rooms')->where('idSchool', Auth::guard('school')->user()->idSchool)->count();
        $data['beds'] =  DB::table('hostel_beds')->where('idSchool', Auth::guard('school')->user()->idSchool)->count();
        $data['assign'] =  DB::table('hostel_students')->where('idFinancialYear', Session::get('idFinancialYear'))->where('idSchool', Auth::guard('school')->user()->idSchool)->whereNotNull('idBed')->count();
        $data['approve'] =  DB::table('hostelite_leaves')->where('idSchool', Auth::guard('school')->user()->idSchool)->whereNotNull('status')->where('idFinancialYear', Session::get('idFinancialYear'))->count();
		$data['unapproved'] =  DB::table('hostelite_leaves')->where('idSchool', Auth::guard('school')->user()->idSchool)->whereNull('status')->where('idFinancialYear', Session::get('idFinancialYear'))->count();
        
        $data['total'] =  DB::table('hostel_transaction')
                        ->where('idSchool', Auth::guard('school')->user()->idSchool)
                        ->where('idFinancialYear', Session::get('idFinancialYear'))
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })
                        ->select(DB::raw('SUM(totalPaid) as totalPaid'))->first()->totalPaid;

        $data['total'] = $data['total'] + DB::table('hostel_lesser_transaction')
                        ->where('idSchool', Auth::guard('school')->user()->idSchool)
                        ->where('idFinancialYear', Session::get('idFinancialYear'))
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })
                        ->select(DB::raw('SUM(totalPaid) as totalPaid'))->first()->totalPaid;

        $data['fine'] = DB::table('hostel_transaction')
                        ->where('idSchool', Auth::guard('school')->user()->idSchool)
                        ->where('idFinancialYear', Session::get('idFinancialYear'))
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })
                        ->select(DB::raw('SUM(fine) as finePaid'))->first()->finePaid;

        $data['fine'] = $data['fine'] + DB::table('hostel_lesser_transaction')
                        ->where('idSchool', Auth::guard('school')->user()->idSchool)
                        ->where('idFinancialYear', Session::get('idFinancialYear'))
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })
                        ->select(DB::raw('SUM(fine) as finePaid'))->first()->finePaid;

        $idClass =  DB::table('hostel_students')->join('students', 'hostel_students.idStudent', '=', 'students.idStudent')->where('hostel_students.idSchool', Auth::guard('school')->user()->idSchool)->where('hostel_students.idFinancialYear', Session::get('idFinancialYear'))->pluck('idClass')->toArray();
        $idSection = DB::table('hostel_students')->join('students', 'hostel_students.idStudent', '=', 'students.idStudent')->where('hostel_students.idSchool', Auth::guard('school')->user()->idSchool)->where('hostel_students.idFinancialYear', Session::get('idFinancialYear'))->pluck('idSection')->toArray();
        $studentType = DB::table('hostel_students')->join('students', 'hostel_students.idStudent', '=', 'students.idStudent')->where('hostel_students.idSchool', Auth::guard('school')->user()->idSchool)->where('hostel_students.idFinancialYear', Session::get('idFinancialYear'))->pluck('studentType')->toArray();
        $idStudent = DB::table('hostel_students')->join('students', 'hostel_students.idStudent', '=', 'students.idStudent')->where('hostel_students.idSchool', Auth::guard('school')->user()->idSchool)->where('hostel_students.idFinancialYear', Session::get('idFinancialYear'))->pluck('hostel_students.idStudent')->toArray();
        $data['overdue'] = 0;
        $oclass_feeheads = \DB::table('hostel_feeheads')->whereIn('idClass',$idClass)
                        ->whereIn('idSection',$idSection)
                        ->whereIn('studentCategory', $studentType)
                        ->whereDate('toDate','<',Carbon::now()->format('Y-m-d'))
                        ->whereNull('idStudent');
        $ofeeheads = \DB::table('hostel_feeheads')->whereIn('idStudent',$idStudent)
                        ->whereDate('toDate','<',Carbon::now()->format('Y-m-d'))
                        ->union($oclass_feeheads)
                        ->orderBy('toDate')
                        ->get();
        $data['overdue'] = $ofeeheads->sum('amount');
        $feeheader_ids = $ofeeheads->pluck('idHostelFeehead')->toArray();
        $lesser_transaction = $data['overdue']  - DB::table('hostel_lesser_transaction')
                ->join('hostel_lesser_transaction_details', 'hostel_lesser_transaction_details.idHostelLesserTransaction', '=', 'hostel_lesser_transaction.idHostelLesserTransaction')
                ->where('hostel_lesser_transaction.idFinancialYear', Session::get('idFinancialYear'))
                ->whereIn('idFeehead', $feeheader_ids)
                ->where(function($query) {
                    $query->whereNull('hostel_lesser_transaction.status');
                    $query->orWhere('hostel_lesser_transaction.status', '=', 'Cleared');
                    $query->orWhere('hostel_lesser_transaction.status', '=', 'In-Process');
                    $query->orWhere('hostel_lesser_transaction.status', '=', 'Success');
                })
                ->select(DB::raw('SUM(totalPaid) as totalPaid'))
                ->first()->totalPaid - DB::table('hostel_transaction')
                ->join('hostel_transaction_details', 'hostel_transaction.idHostelTransaction', '=', 'hostel_transaction_details.idHostelTransaction')
                ->where('hostel_transaction.idFinancialYear', Session::get('idFinancialYear'))
                ->whereIn('idFeehead', $feeheader_ids)
                ->where(function($query) {
                    $query->whereNull('hostel_transaction.status');
                    $query->orWhere('hostel_transaction.status', '=', 'Cleared');
                    $query->orWhere('hostel_transaction.status', '=', 'In-Process');
                    $query->orWhere('hostel_transaction.status', '=', 'Success');
                })
                ->select(DB::raw('SUM(totalPaid) as totalPaid'))
                ->first()->totalPaid;

        $class_feeheads = \DB::table('hostel_feeheads')->whereIn('idClass',$idClass)
                        ->whereIn('idSection',$idSection)
                        ->whereIn('studentCategory', $studentType)
                        ->whereNull('idStudent');
        $feeheads = \DB::table('hostel_feeheads')->whereIn('idStudent',$idStudent)
                        ->union($class_feeheads)
                        ->orderBy('toDate')
                        ->get();
        $data['fee'] = $feeheads->sum('amount');
        $data ["student_calendar"] = \App\Holiday::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
        ->select('holidayName','fromDate','toDate')
        ->groupBy('holidayName','fromDate','toDate')->get();
        $classes = [];
        $classId = DB::table('classes')->select('idClass','className')->where('idSchool', Auth::guard('school')->user()->idSchool)->orderBy('idClass')->get();
        foreach($classId as $var){
            $temp = [];
            $temp['className'] = $var->className;
            $temp['count'] = DB::table('hostel_students')
                ->join('students', 'hostel_students.idStudent', '=', 'students.idStudent')
                ->where('hostel_students.idSchool', Auth::guard('school')->user()->idSchool)
                ->where('hostel_students.idFinancialYear', Session::get('idFinancialYear'))
                ->where('students.idClass', $var->idClass)
                ->count();
            array_push($classes,$temp);
        }
        return view('schools.hostel-dashboard',compact('data','classes'));
	}
	
	public function admissionDashboard(){
        $data = [];
        $enquiry = [];
        $enquiryClass = [];
        $registrationClass = [];
        $classes = DB::table('classes')->select('idClass','className')->where('idSchool', Auth::guard('school')->user()->idSchool)->orderBy('idClass')->get()->pluck('className')->toArray();
        $classId = DB::table('classes')->select('idClass','className')->where('idSchool', Auth::guard('school')->user()->idSchool)->orderBy('idClass')->get();
        $financialYear = DB::table('financial_years')->select('idFinancialYear','financialYearName','startDate')->where('idSchool', Auth::guard('school')->user()->idSchool)->get();
        foreach($classId as $var){
            $countR = DB::table('student-registration')
                ->where('idSchool', Auth::guard('school')->user()->idSchool)
                ->where('idClass', $var->idClass)
                ->where('form_type', 'R')
                ->where('idFinancialYear', Session::get('idFinancialYear'))
                ->count();
            $countE = DB::table('student-registration')
                ->where('idSchool', Auth::guard('school')->user()->idSchool)
                ->where('idClass', $var->idClass)
                ->where('form_type', 'E')
                ->where('idFinancialYear', Session::get('idFinancialYear'))
                ->count();
            array_push($registrationClass,$countR);
            array_push($enquiryClass,$countE);
        }

        foreach($financialYear as $var){
            $temp = [];
            $temp['registration'] = DB::table('student-registration')
                ->where('idSchool', Auth::guard('school')->user()->idSchool)
                ->where('form_type', 'R')
                ->where('idFinancialYear', '=', $var->idFinancialYear)
                ->count();
            $temp['enquiry'] = DB::table('student-registration')
                ->where('idSchool', Auth::guard('school')->user()->idSchool)
                ->where('form_type', 'E')
                ->where('idFinancialYear', '=', $var->idFinancialYear)
                ->count();
            $temp['period'] = Carbon::parse($var->startDate)->format('Y');
            array_push($enquiry,$temp);
        }

        $data['enquiry'] = DB::table('student-registration')
                            ->select('idRegistration')
                            ->where('idSchool', Auth::guard('school')->user()->idSchool)
                            ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                            ->where('form_type', 'E')
                            ->count();
        $data['registration'] = DB::table('student-registration')
                            ->select('idRegistration')
                            ->where('idSchool', Auth::guard('school')->user()->idSchool)
                            ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                            ->where('form_type', 'R')
                            ->count();
        $data['registration-pending'] = DB::table('student-registration')
                            ->select('idRegistration')
                            ->where('idSchool', Auth::guard('school')->user()->idSchool)
                            ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                            ->where('form_type', 'R')
                            ->where('admitted', 'N')
                            ->count();
        $data['registration-admitted'] = DB::table('student-registration')
                            ->select('idRegistration')
                            ->where('idSchool', Auth::guard('school')->user()->idSchool)
                            ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                            ->where('form_type', 'R')
                            ->whereIn('admitted', ['A','Y'])
                            ->count();
        $data['registration-rejected'] = DB::table('student-registration')
                            ->select('idRegistration')
                            ->where('idSchool', Auth::guard('school')->user()->idSchool)
                            ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                            ->where('form_type', 'R')
                            ->where('admitted', 'R')
                            ->count();
		return view('schools.admission-dashboard',compact('data','enquiry','classes','enquiryClass','registrationClass'));
	}

    public function creative(){
        // Create a blank image and add some text
        $im =imagecreatefromjpeg('https://staging001.daikinindia.com/daikinnearme/authorised-dealers//assets/images/review-bg.jpg');
        $text_color = imagecolorallocate($im, 233, 14, 91);
        imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

        // Set the content type header - in this case image/jpeg
        header('Content-Type: image/jpeg');
        header('Content-Disposition: attachment; filename=file-name.jpg'); // This will tell the browser to download it

        // Output the image
        imagejpeg($im);

        // Free up memory
        imagedestroy($im);
    }
   
    
    public function setSession(Request $request) {
        $idFinancialYear = $request->idFinancialYear;
        if($request->idFinancialYear == null){
            Session::put('idFinancialYear', getFinancialYear());
            return redirect('/school');
        }
        Session::put('idFinancialYear', $request->idFinancialYear);
        return redirect('/school');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function dashboard() {
        if(Auth::guard('school')->user()->forcedUpdate == 'N' && Auth::guard('school')->user()->isSchool == 'N')
        return redirect('/school/updtfpassword');

        $school = \App\School::where('idSchool', '=', Auth::guard('school')->user()->idSchool)->first();
        $months = \App\Month::get()->pluck('monthName', 'idMonth')->toArray();
        Carbon::setWeekStartsAt(Carbon::SUNDAY);
        Carbon::setWeekEndsAt(Carbon::SATURDAY);
        $stds_birday = \App\AdmEntry::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                ->whereRaw("DATE_FORMAT((studentDob),'%m-%d') = DATE_FORMAT(NOW(),'%m-%d')")
                // ->whereBetween('studentDob', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])
                ->get();
        //  Data::whereBetween('created_at', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])->get();
        $todaycashamt = $this->getTodayCollection();
        $weekcashamt = $this->getWeeklyCollection();
        $monthcashamt = $this->getMonthlyCollection();
        $yearcashamt = $this->getYearlyCollection();

        $holidays = \App\Holiday::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))->get();
        $classes = \App\ClassM::where('idSchool', '=', Auth::guard('school')->user()->idSchool)->get();

        $students = \App\AdmEntry::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                ->where('isActive', '=', 'Y')
                ->select(DB::raw('COUNT(idStudent) as students'))->first();
        $employees = DB::table('employees')
                ->join('designations', 'employees.idDesignation', '=', 'designations.idDesignation')
                ->select(DB::raw("CONCAT(firstName,' ',lastName,' ',enrollmentNo) AS name"), 'idEmployee')
                ->where('employees.idSchool', '=', Auth::guard('school')->user()->idSchool)
                ->where('designationName', '=', 'Teacher')
                ->select(DB::raw('COUNT(idEmployee) as teachers'))->first();
        $staffs = \App\Employee::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                //->where('idFinancialYear','=',Session::get('idFinancialYear'))
                ->select(DB::raw('COUNT(idEmployee) as staffs'))->first();
        
        $chqamt = \App\StudentTransaction::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->where('paymentMode', '=', 'Cheque')
                        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                        ->where(function($query) {
                            //$query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            // $query->orWhere('status', '=', 'Success');
                        })->select(DB::raw('SUM(totalPaid) as totalPaid'))->first();
        $cashamt = \App\StudentTransaction::where('idSchool', '=', Auth::guard('school')->user()->idSchool)->where('paymentMode', '=', 'Cash')->where(function($query) {
                    $query->whereNull('status')->where('idFinancialYear', '=', Session::get('idFinancialYear'));
                })->select(DB::raw('SUM(totalPaid) as totalPaid'))->first();
        $cashlessamt = \App\LesserTransaction::where('idSchool', '=', Auth::guard('school')->user()->idSchool)->where('paymentMode', '=', 'Cash')->where(function($query) {
                    $query->whereNull('status')->where('idFinancialYear', '=', Session::get('idFinancialYear'));
                })->select(DB::raw('SUM(totalPaid) as totalPaid'))->first();
        $onlineamt = \App\StudentTransaction::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                        ->where('paymentMode', '=', 'Online')->where(function($query) {
                    $query->orWhere('status', '=', 'Success');
                })->select(DB::raw('SUM(totalPaid) as totalPaid'))->first();
                
        $boys = \App\AdmEntry::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                    ->where('gender', '=', 'Male')
                    ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                    ->select(DB::raw('COUNT(idStudent) as totboys'))->first();
        $girls = \App\AdmEntry::where('idSchool','=',Auth::guard('school')->user()->idSchool)
                                            ->where('idFinancialYear','=',Session::get('idFinancialYear'))
                                            ->where('gender','=','FeMale')
                ->select(DB::raw('COUNT(idStudent) as totgirls'))->first();
        $updateWeather = \App\School::where('idSchool', '=', Auth::guard('school')->user()->idSchool)->first();
        $time = Carbon::parse($updateWeather->updated_at);
        $now = Carbon::now();
        $diff = $time->diffInHours($now);
        if ($updateWeather->weatherResponse == null || $diff > 1) {
            $weather = $this->getWeatherData(trim($updateWeather->city));
            $updateWeather->weatherResponse = $weather;
            $updateWeather->update();
        } else
            $weather = $updateWeather->weatherResponse;
        $city = trim($updateWeather->city) . ",IN";
        
        return view('schools.dashboard', compact('girls','boys','girls','onlineamt', 'cashamt', 'cashlessamt', 'chqamt', 'staffs', 'employees', 'students', 'stds_birday', 'months', 'classes', 'school', 'holidays', 'weekcashamt', 'monthcashamt', 'yearcashamt', 'todaycashamt','weather', 'city'));
    }

    public function getWeatherData($city) {
        $endpoint = "https://api.openweathermap.org/data/2.5/forecast";
        $client = new \GuzzleHttp\Client(['http_errors' => false]);
        $response = $client->request('GET', $endpoint, ['query' => [
                'q' => $city . ",IN",
                'appid' => '6dee0cb7efa5312a639ec1a54ca8bea8',
                'units' => 'metric'
        ]]);

        $statusCode = $response->getStatusCode();
        if ($statusCode == 404)
            return "";
        $content = $response->getBody();

        return $content;
    }

    public function getTodayCollection() {
        $lesspaid = DB::table('lesser_transaction')->where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                        ->whereDate('paymentDate', '=', \Carbon\Carbon::now()->today())
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })
                        ->select(DB::raw('SUM(totalPaid) as totalPaid'))->first();
        $fullpaid = DB::table('student_transaction')->where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                        ->whereDate('paymentDate', '=', \Carbon\Carbon::now()->today())
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })
                        //  ->union($lesspaid)
                        ->select(DB::raw('SUM(totalPaid) as totalPaid'))->first();
        $lessbusfeepaid = \App\BusLesserTransaction::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                        ->whereDate('paymentDate', '=', \Carbon\Carbon::now()->today())
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })
                        ->select(DB::raw('SUM(totalPaid) as totalPaid'))->first();
        $fullbusfeepaid = \App\BusTransaction::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                        ->whereDate('paymentDate', '=', \Carbon\Carbon::now()->today())
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })
                        //  ->union($lessbusfeepaid)
                        ->select(DB::raw('SUM(totalPaid) as totalPaid'))->first();
        $lesshostelfeepaid = \App\HostelLesserTransaction::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                        ->whereDate('paymentDate', '=', \Carbon\Carbon::now()->today())
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })
                        ->select(DB::raw('SUM(totalPaid) as totalPaid'))->first();
        $fullhostelfeepaid = \App\HostelTransaction::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                        ->whereDate('paymentDate', '=', \Carbon\Carbon::now()->today())
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })
                        // ->union($lesshostelfeepaid)
                        ->select(DB::raw('SUM(totalPaid) as totalPaid'))->first();
        $totalcashamt["fees"] =$fullpaid->totalPaid + $lesspaid->totalPaid;
        $totalcashamt["bus"] = $fullbusfeepaid->totalPaid + $lessbusfeepaid->totalPaid ;
        $totalcashamt["hostel"] = $fullhostelfeepaid->totalPaid  + $lesshostelfeepaid->totalPaid;
        return $totalcashamt;
    }

    public function getWeeklyCollection() {

        $lesspaid = \App\LesserTransaction::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                        ->whereBetween('paymentDate', [\Carbon\Carbon::now()->startOfWeek(), \Carbon\Carbon::now()->endOfWeek()])
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })
                        ->select(DB::raw('SUM(totalPaid) as totalPaid'))->first();
        $fullpaid = \App\StudentTransaction::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                        ->whereBetween('paymentDate', [\Carbon\Carbon::now()->startOfWeek(), \Carbon\Carbon::now()->endOfWeek()])
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })
                        //   ->union($lesspaid)
                        ->select(DB::raw('SUM(totalPaid) as totalPaid'))->first();
        $lessbusfeepaid = \App\BusLesserTransaction::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                        ->whereBetween('paymentDate', [\Carbon\Carbon::now()->startOfWeek(), \Carbon\Carbon::now()->endOfWeek()])
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })
                        ->select(DB::raw('SUM(totalPaid) as totalPaid'))->first();
        $fullbusfeepaid = \App\BusTransaction::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                        ->whereBetween('paymentDate', [\Carbon\Carbon::now()->startOfWeek(), \Carbon\Carbon::now()->endOfWeek()])
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })
                        //  ->union($lessbusfeepaid)
                        ->select(DB::raw('SUM(totalPaid) as totalPaid'))->first();
        $lesshostelfeepaid = \App\HostelLesserTransaction::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                        ->whereBetween('paymentDate', [\Carbon\Carbon::now()->startOfWeek(), \Carbon\Carbon::now()->endOfWeek()])
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })
                        ->select(DB::raw('SUM(totalPaid) as totalPaid'))->first();
        $fullhostelfeepaid = \App\HostelTransaction::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                        ->whereBetween('paymentDate', [\Carbon\Carbon::now()->startOfWeek(), \Carbon\Carbon::now()->endOfWeek()])
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })
                        // ->union($lesshostelfeepaid)
                        ->select(DB::raw('SUM(totalPaid) as totalPaid'))->first();
        //$totalcashamt = $fullhostelfeepaid->totalPaid + $fullbusfeepaid->totalPaid + $fullpaid->totalPaid + $lesshostelfeepaid->totalPaid + $lessbusfeepaid->totalPaid + $lesspaid->totalPaid;
        $totalcashamt["fees"] =$fullpaid->totalPaid + $lesspaid->totalPaid;
        $totalcashamt["bus"] = $fullbusfeepaid->totalPaid + $lessbusfeepaid->totalPaid ;
        $totalcashamt["hostel"] = $fullhostelfeepaid->totalPaid  + $lesshostelfeepaid->totalPaid;
        return $totalcashamt;
    }

    public function getMonthlyCollection() {
        $lesspaid = \App\LesserTransaction::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                        ->whereMonth('paymentDate', Carbon::now()->month)
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })
                        ->select(DB::raw('SUM(totalPaid) as totalPaid'))->first();
        $fullpaid = \App\StudentTransaction::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                        ->whereMonth('paymentDate', Carbon::now()->month)
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })
                        //   ->union($lesspaid)
                        ->select(DB::raw('SUM(totalPaid) as totalPaid'))->first();
        $lessbusfeepaid = \App\BusLesserTransaction::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                        ->whereMonth('paymentDate', Carbon::now()->month)
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })
                        ->select(DB::raw('SUM(totalPaid) as totalPaid'))->first();
        $fullbusfeepaid = \App\BusTransaction::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                        ->whereMonth('paymentDate', Carbon::now()->month)
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })
                        //  ->union($lessbusfeepaid)
                        ->select(DB::raw('SUM(totalPaid) as totalPaid'))->first();
        $lesshostelfeepaid = \App\HostelLesserTransaction::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                        ->whereMonth('paymentDate', Carbon::now()->month)
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })
                        ->select(DB::raw('SUM(totalPaid) as totalPaid'))->first();
        $fullhostelfeepaid = \App\HostelTransaction::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                        ->whereMonth('paymentDate', Carbon::now()->month)
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })
                        //   ->union($lesshostelfeepaid)
                        ->select(DB::raw('SUM(totalPaid) as totalPaid'))->first();
        //$totalcashamt = $fullhostelfeepaid->totalPaid + $fullbusfeepaid->totalPaid + $fullpaid->totalPaid + $lesshostelfeepaid->totalPaid + $lessbusfeepaid->totalPaid + $lesspaid->totalPaid;
        $totalcashamt["fees"] =$fullpaid->totalPaid + $lesspaid->totalPaid;
        $totalcashamt["bus"] = $fullbusfeepaid->totalPaid + $lessbusfeepaid->totalPaid ;
        $totalcashamt["hostel"] = $fullhostelfeepaid->totalPaid  + $lesshostelfeepaid->totalPaid;
        return $totalcashamt;
    }

    public function getYearlyCollection() {
        $lesspaid = DB::table('lesser_transaction')->where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                        //        ->whereYear('paymentDate', Carbon::now()->year)
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })
                        ->select(DB::raw('SUM(totalPaid) as totalPaid'))->first();
        $fullpaid = DB::table('student_transaction')->where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                        //    ->whereYear('paymentDate', Carbon::now()->year)
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })
                        //  ->union($lesspaid)
                        ->select(DB::raw('SUM(totalPaid) as totalPaid'))->first();
        $lessbusfeepaid = \App\BusLesserTransaction::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
//                        ->whereYear('paymentDate', Carbon::now()->year)
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })
                        ->select(DB::raw('SUM(totalPaid) as totalPaid'))->first();
        $fullbusfeepaid = \App\BusTransaction::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                        //   ->whereYear('paymentDate', Carbon::now()->year)
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })
                        //->union($lessbusfeepaid)
                        ->select(DB::raw('SUM(totalPaid) as totalPaid'))->first();
        $lesshostelfeepaid = \App\HostelLesserTransaction::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                        //     ->whereYear('paymentDate', Carbon::now()->year)
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })
                        ->select(DB::raw('SUM(totalPaid) as totalPaid'))->first();
        $fullhostelfeepaid = \App\HostelTransaction::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                        //        ->whereYear('paymentDate', Carbon::now()->year)
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })
                        // ->union($lesshostelfeepaid)
                        ->select(DB::raw('SUM(totalPaid) as totalPaid'))->first();
        //$totalcashamt = $fullhostelfeepaid->totalPaid + $fullbusfeepaid->totalPaid + $fullpaid->totalPaid + $lesshostelfeepaid->totalPaid + $lessbusfeepaid->totalPaid + $lesspaid->totalPaid;
        $totalcashamt["fees"] =$fullpaid->totalPaid + $lesspaid->totalPaid;
        $totalcashamt["bus"] = $fullbusfeepaid->totalPaid + $lessbusfeepaid->totalPaid ;
        $totalcashamt["hostel"] = $fullhostelfeepaid->totalPaid  + $lesshostelfeepaid->totalPaid;
        return $totalcashamt;
    }


    public function editPassword() {
        return view('schools.force_updt_password');
    }

    public function updatePassword(Request $request) {
        $rules = [];
        $user = \App\SchoolUser::where('email', '=', Auth::guard('school')->user()->email)->first();
        $this->validate($request, $rules + [
            'password' => 'required|min:6|confirmed',
        ]);
        $user->pwd = $request['password'];
        $user->password = bcrypt($request['password']);
        $user->forcedUpdate = 'Y';
        $user->update();
        Auth::login($user);
        flash()->success('Password updated successfully.');
        return redirect('/school');
    }
	

    private function fetchCom(){
        $json = array();
        $homework = DB::table('homework')->where('idSchool', '=', Auth::guard('school')->user()->idSchool)
               ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
               ->select(DB::raw('COUNT(idHomework) as total'))->first();
        $json["homework"] = $homework->total;
        $homeworkGraph = DB::table('homework')->where('idSchool', '=', Auth::guard('school')->user()->idSchool)
               ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
               ->select(DB::raw('COUNT(idHomework) as total'))->groupBy('publishDate')->orderBy('publishDate','DESC')->limit(2)->offset(0)->get();   
        $graph = "+0";
        if(count($homeworkGraph) > 1){
            if($homeworkGraph[1]->total > $homeworkGraph[0]->total)
            $graph = "+".$homeworkGraph[1]->total;
            else $graph = "-".$homeworkGraph[1]->total;
        }      
        $json["homeworkGraph"] = $graph;
        
        $noticeboard = DB::table('noticeboard')->where('idSchool', '=', Auth::guard('school')->user()->idSchool)
               ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
               ->select(DB::raw('COUNT(idNoticeboard) as total'))->first();
        $json["noticeboard"] = $noticeboard->total;
        $noticeboardGraph = DB::table('noticeboard')->where('idSchool', '=', Auth::guard('school')->user()->idSchool)
               ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
               ->select(DB::raw('COUNT(idNoticeboard) as total'))->groupBy('publishDate')->orderBy('publishDate','DESC')->limit(2)->offset(0)->get();   
        $graph = "+0";
        if(count($noticeboardGraph) > 1){
            if($noticeboardGraph[1]->total > $noticeboardGraph[0]->total)
            $graph = "+".$noticeboardGraph[1]->total;
            else $graph = "-".$noticeboardGraph[1]->total;
        }      
        $json["noticeboardGraph"] = $graph;       
        
        $gallery = DB::table('gallery')->where('idSchool', '=', Auth::guard('school')->user()->idSchool)
               ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
               ->select(DB::raw('COUNT(idGallery) as total'))->first();
        $json["gallery"] = $gallery->total;
        $galleryGraph = DB::table('gallery')->where('idSchool', '=', Auth::guard('school')->user()->idSchool)
               ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
               ->select(DB::raw('COUNT(idGallery) as total'))->groupBy('idFolder')->orderBy('created_at','DESC')->limit(2)->offset(0)->get();   
               $graph = "+0";
               if(count($galleryGraph) > 1){
                   if($galleryGraph[1]->total > $galleryGraph[0]->total)
                   $graph = "+".$galleryGraph[1]->total;
                   else $graph = "-".$galleryGraph[1]->total;
               }      
               $json["galleryGraph"] = $graph;    
        
        $practice = DB::table('practice_sets')->where('idSchool', '=', Auth::guard('school')->user()->idSchool)
               ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
               ->select(DB::raw('COUNT(idSet) as total'))->first();
        $json["practice"] = $practice->total;
        $practiceGraph = DB::table('practice_sets')->where('idSchool', '=', Auth::guard('school')->user()->idSchool)
               ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
               ->select(DB::raw('COUNT(idSet) as total'))->groupBy('publishDate')->orderBy('publishDate','DESC')->limit(2)->offset(0)->get();   
               $graph = "+0";
               if(count($practiceGraph) > 1){
                   if($practiceGraph[1]->total > $practiceGraph[0]->total)
                   $graph = "+".$practiceGraph[1]->total;
                   else $graph = "-".$practiceGraph[1]->total;
               }
               $json["practiceGraph"] = $graph; 
        
        $short = DB::table('short_stories')->where('idSchool', '=', Auth::guard('school')->user()->idSchool)
               ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
               ->select(DB::raw('COUNT(idStory) as total'))->first();
        $json["short"] = $short->total;
        $shortGraph = DB::table('short_stories')->where('idSchool', '=', Auth::guard('school')->user()->idSchool)
               ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
               ->select(DB::raw('COUNT(idStory) as total'))->groupBy('publishDate')->orderBy('publishDate','DESC')->limit(2)->offset(0)->get();  
               $graph = "+0";
               if(count($shortGraph) > 1){
                   if($shortGraph[1]->total > $shortGraph[0]->total)
                   $graph = "+".$shortGraph[1]->total;
                   else $graph = "-".$shortGraph[1]->total;
               } 
        $json["shortGraph"] = $graph; 

        $thought = DB::table('weekly_thoughts')->where('idSchool', '=', Auth::guard('school')->user()->idSchool)
        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
        ->select(DB::raw('COUNT(idThought) as total'))->first();
        $json["thought"] = $thought->total;
        $thoughtGraph = DB::table('weekly_thoughts')->where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                ->select(DB::raw('COUNT(idThought) as total'))->groupBy('publishDate')->orderBy('publishDate','DESC')->limit(2)->offset(0)->get();
                $graph = "+0";
               if(count($thoughtGraph) > 1){
                   if($thoughtGraph[1]->total > $thoughtGraph[0]->total)
                   $graph = "+".$thoughtGraph[1]->total;
                   else $graph = "-".$thoughtGraph[1]->total;
               }    
        $json["thoughtGraph"] =$graph; 


        $positive = DB::table('positive_news')->where('idSchool', '=', Auth::guard('school')->user()->idSchool)
        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
        ->select(DB::raw('COUNT(idNews) as total'))->first();
        $json["positive"] = $positive->total;
        $positiveGraph = DB::table('positive_news')->where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                ->select(DB::raw('COUNT(idNews) as total'))->groupBy('publishDate')->orderBy('publishDate','DESC')->limit(2)->offset(0)->get();
                $graph = "+0";
               if(count($positiveGraph) > 1){
                   if($positiveGraph[1]->total > $positiveGraph[0]->total)
                   $graph = "+".$positiveGraph[1]->total;
                   else $graph = "-".$positiveGraph[1]->total;
               }    
        $json["positiveGraph"] =$graph; 
        
        return $json;       
    }

    public function addTodo(Request $request){
        if($request->event_time == null || $request->description == null || $request->subject == null){
            return response()->json(['message' => 'All fields are mandatory'], 200);
        }else{
            DB::table('school_todo')->insert([
                'subject' => $request->subject,
                'description' => $request->description,
                'idSchool' => Auth::guard('school')->user()->idSchool,
                'idSchoolUser' => Auth::guard('school')->user()->idSchoolUser,
                'idFinancialYear' => Session::get('idFinancialYear'),
                'publishDate' => Carbon::parse($request->event_time)->format('Y-m-d'),
                'isCompleted' => $request->subject,
            ]);
            return response()->json(['message' => 'Added'], 200);
        }
    }

    public function fetchtoDo(Request $request){
        $toDo = DB::table('school_todo')->select('description','idTodo','isCompleted','publishDate','subject')->where('idSchool', '=', Auth::guard('school')->user()->idSchool)
        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
        ->where('isCompleted', '=', '0')
        ->where('idSchoolUser', '=', Auth::guard('school')->user()->idSchoolUser)
        ->orderBy('publishDate','DESC')->paginate();
        return response()->json(['data' => $toDo], 200);
    }

    public function updateTodo($id){
        DB::table('school_todo')->where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                ->where('idSchoolUser', '=', Auth::guard('school')->user()->idSchoolUser)
                ->where('idTodo',$id)->update(['isCompleted' => 1]);
        return response()->json(['message' => 'Updated'], 200);
    }

    public function fetchDasboard(){
        $json = array();
        $updateWeather = \App\School::where('idSchool', '=', Auth::guard('school')->user()->idSchool)->first();
        $time = Carbon::parse($updateWeather->updated_at);
        $now = Carbon::now();
        $diff = $time->diffInHours($now);
        if ($updateWeather->weatherResponse == null || $diff > 4) {
            $weather = WeatherApi::fetch(trim(urlencode($updateWeather->city)));
            $updateWeather->weatherResponse = $weather;
            $updateWeather->update();
        } else
            $weather = $updateWeather->weatherResponse;
        
        $api = json_decode($weather,true); 
        
        $days = array();
        if (array_key_exists('list', $api)){
            $temperature = $api["list"];
            if($temperature != null){
                $json ["temp"] = $temperature[0]["main"]["feels_like"];
                $json ["pressure"] = $temperature[0]["main"]["pressure"];
                $json ["humidity"] = $temperature[0]["main"]["humidity"];
                $json ["wind"] = $temperature[0]["wind"]["speed"];
                $json ["cloud"] = $temperature[0]["clouds"]["all"];
                $json ["weather"] = $temperature[0]["weather"][0]["main"];
                $json ["time"] = Carbon::now()->format('g:i A');
                $json["defaultDate"] = Carbon::now()->format('Y-m-d');
                $json ["grnd_level"] = $temperature[0]["main"]["grnd_level"];
                if($weather != null){
                    foreach($temperature as $weather){
                        $days[explode(" ",$weather["dt_txt"])[0]] = $weather["weather"][0]["main"];
                    }
                }
            } 
        } 
        $json ["forecast"] = $days;
        $json ["city"] = trim($updateWeather->city) . ",IN";
        $json ["employee_calendar"] = \App\HrmsHoliday::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
        ->select('holidayName','fromDate','toDate')
        ->groupBy('holidayName','fromDate','toDate')->get();
        $json ["student_calendar"] = \App\Holiday::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
        ->select('holidayName','fromDate','toDate')
        ->groupBy('holidayName','fromDate','toDate')->get();
        return response()->json(['data' => $json], 200);
    }

    public function birthdayMessage(Request $request){
        if($request->idStudent == null || $request->msg == null){
            return response()->json(['message' => 'All fields are mandatory'], 404);
        }else{
            $reg_ids = DB::table('students')
                                        ->join('parents', 'students.father_mobile', '=', 'parents.mobile')
                                        ->select('parents.idFirebase')
                                        ->where('students.idStudent', $request->idStudent)
                                        ->get()->pluck('idFirebase')->toArray();
            if(isset($reg_ids))                            
            SendNotificationApi::sendSingleNotification($reg_ids, $request->msg);
            return response()->json(['message' => 'Sent'], 200);
        }
    }

	public function dashboardAnalytics(Request $request){
        if(Auth::guard('school')->user()->forcedUpdate == 'N' && Auth::guard('school')->user()->isSchool == 'N')
        return redirect('/school/updtfpassword');

        if(Auth::guard('school')->user()->isSchool == 'N' && Auth::guard('school')->user()->idReference > 0)
        return redirect('/school/food-vendor-dashboard');

        if(Auth::guard('school')->user()->idSchool == 180){
            return $this->stockDashboard($request);
        }

        $school = \App\School::where('idSchool', '=', Auth::guard('school')->user()->idSchool)->first();
        $ts = \App\AdmEntry::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
        ->where('isActive', '=', 'Y')
        ->select(DB::raw('COUNT(idStudent) as total'))->first();

        $te = \App\Employee::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
        ->select(DB::raw('COUNT(idEmployee) as total'))->first();

        $tc = \App\ClassM::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
        ->select(DB::raw('COUNT(idClass) as total'))->first();

        $stu_at = DB::table('attandance')->where('idSchool', '=', Auth::guard('school')->user()->idSchool)
               ->select('date')->whereIn('status',['IN','P','p'])->groupBy('date')->orderBy('id','DESC')->skip(0)->limit(15)->get();
        $emp_at = DB::table('employee_attendance')->where('idSchool', '=', Auth::guard('school')->user()->idSchool)
               ->select(DB::raw('COUNT(ID) as total'),'date')->whereIn('status',['IN','P','p'])->groupBy('date')->orderBy('date','DESC')->get(15)->pluck('total','date')->toArray();
        
        
        $classwise = \App\AdmEntry::where('students.idSchool', '=', Auth::guard('school')->user()->idSchool)
               ->join('classes', 'students.idClass', '=', 'classes.idClass')
               ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
               ->where('isActive', '=', 'Y')
               ->select(DB::raw('COUNT(idStudent) as total'),'className')->groupBy('students.idClass')->get();

        $comm = $this->fetchCom();

        $stds_birday = \App\AdmEntry::join('classes', 'students.idClass', '=', 'classes.idClass')
                ->join('sections', 'students.idSection', '=', 'sections.idSection')
                ->select('firstName', 'middleName', 'lastName','className', 'sectionName','photo','idStudent')
                ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                ->where('students.idSchool', '=', Auth::guard('school')->user()->idSchool)
                ->whereRaw("DATE_FORMAT((studentDob),'%m-%d') = DATE_FORMAT(NOW(),'%m-%d')")
                ->get();

        return view('dashboarddata-analytics', compact('ts','te','tc','emp_at','stu_at','classwise','comm','stds_birday','school'));
	}

    public function stockDashboard(Request $request){
        $idSchool = Auth::guard('school')->user()->idSchool;
        $idFy = Session::get('idFinancialYear');
        
        $chartSale = DB::table('invoice_details')->join('invoices','invoice_details.idInvoice','=','invoices.idInvoice')->select(DB::raw('SUM(quantity) as total'),'poMonth')->where('idSchool', $idSchool);
        $chartPurchase = DB::table('purchase_order_details')->join('purchase_orders','purchase_order_details.idPurchaseOrder','=','purchase_orders.idPurchaseOrder')->select(DB::raw('SUM(quantity) as total'),'poMonth')->where('idSchool', $idSchool);

        $lnRevenue = DB::table('invoices')->select(DB::raw('SUM(amountPayable) as total'),'idFinancialYear')->where('idSchool', $idSchool);
        $lnSales = DB::table('stock_invoicepayment')->select(DB::raw('SUM(paidAmount) as total'),'idFinancialYear')->where('idSchool', $idSchool)->where('paymentStatus', 'Success');
        
        $lnSupplier = DB::table('suppliers')->select(DB::raw('COUNT(*) as total'),'idFinancialYear')->where('idSchool', $idSchool);
        $lnOrders = DB::table('invoices')->select(DB::raw('COUNT(*) as total'),'idFinancialYear')->where('idSchool', $idSchool);
        
        $tinv = DB::table('invoices')->where('idSchool', $idSchool);
        $tsales = DB::table('invoices')->where('idSchool', $idSchool);
        $today_sales = DB::table('invoices')->where('idSchool', $idSchool);
        $sampleInvoice = DB::table('invoices')->where('idSchool', $idSchool);
        $orders = DB::table('invoice_details')->join('invoices','invoice_details.idInvoice','=','invoices.idInvoice')->where('idSchool', $idSchool);
        $top = DB::table('invoice_details')->join('invoices','invoice_details.idInvoice','=','invoices.idInvoice')->join('products','invoice_details.idProduct','=','products.idProduct')->select('productName',DB::raw('SUM(quantity) as total_quantity'),DB::raw('SUM(productTotal) as total'))->where('invoices.idSchool', $idSchool);
        $sales = DB::table('invoice_details')->join('invoices','invoice_details.idInvoice','=','invoices.idInvoice')->join('products','invoice_details.idProduct','=','products.idProduct')->select('productName','quantity','productTotal as total')->where('invoices.idSchool', $idSchool);
        $quotation = DB::table('quotations')->join('suppliers','quotations.idSupplier','=','suppliers.idSupplier')->select('bussinessName','quotations.*')->where('quotations.idSchool', $idSchool);
        $invoice = DB::table('invoices')->join('customers','invoices.idCustomer','=','customers.idCustomer')->select('customerName','invoices.*')->where('invoices.idSchool', $idSchool);
        $top_customer = DB::table('invoices')->join('customers','invoices.idCustomer','=','customers.idCustomer')->select('invoices.idCustomer','customerName',DB::raw('SUM(amountPayable) as total'),DB::raw('COUNT(*) AS orders'))->where('invoices.idSchool', $idSchool);
        $orders_details = DB::table('invoice_details')->join('invoices','invoice_details.idInvoice','=','invoices.idInvoice')->select('idProduct',DB::raw('COUNT(*) as total'))->where('invoices.idSchool', $idSchool);
        
        $week_sales = DB::table('invoices')->where('idSchool', $idSchool);
        $month_sales = DB::table('invoices')->where('idSchool', $idSchool);
        $total_payment_done = DB::table('stock_invoicepayment')->join('invoices','stock_invoicepayment.idInvoice','=','invoices.idInvoice')->where('stock_invoicepayment.idSchool', $idSchool);
        
        
        if($request->get('idFinancialYear') != ""){
            $tinv->where('idFinancialYear', $request->get('idFinancialYear'));
            $chartSale->where('idFinancialYear', $request->get('idFinancialYear'));
            $chartPurchase->where('idFinancialYear', $request->get('idFinancialYear'));
            $tsales->where('idFinancialYear', $request->get('idFinancialYear'));
            $today_sales->where('idFinancialYear', $request->get('idFinancialYear'));
            $orders->where('idFinancialYear', $request->get('idFinancialYear'));
            $top->where('invoices.idFinancialYear', $request->get('idFinancialYear'));
            $quotation->where('quotations.idFinancialYear', $request->get('idFinancialYear'));
            $sales->where('invoices.idFinancialYear', $request->get('idFinancialYear'));
            $orders_details->where('invoices.idFinancialYear', $request->get('idFinancialYear'));
            $top_customer->where('invoices.idFinancialYear', $request->get('idFinancialYear'));
            $sampleInvoice->where('idFinancialYear', $request->get('idFinancialYear'));
            $invoice->where('idFinancialYear', $request->get('idFinancialYear'));
            $total_payment_done->where('stock_invoicepayment.idFinancialYear', $request->get('idFinancialYear'));
            $week_sales->where('idFinancialYear', $request->get('idFinancialYear'));
            $month_sales->where('idFinancialYear', $request->get('idFinancialYear'));
        }else{
            $tinv->where('idFinancialYear', $idFy);
            $chartSale->where('idFinancialYear', $idFy);
            $chartPurchase->where('idFinancialYear', $idFy);
            $tsales->where('idFinancialYear', $idFy);
            $today_sales->where('idFinancialYear', $idFy);
            $orders->where('idFinancialYear', $idFy);
            $top->where('invoices.idFinancialYear', $idFy);
            $quotation->where('quotations.idFinancialYear', $idFy);
            $sales->where('invoices.idFinancialYear', $idFy);
            $invoice->where('idFinancialYear', $idFy);
            $total_payment_done->where('stock_invoicepayment.idFinancialYear', $idFy);
            $sampleInvoice->where('idFinancialYear', $idFy);
            $week_sales->where('idFinancialYear', $idFy);
            $orders_details->where('invoices.idFinancialYear', $idFy);
            $top_customer->where('invoices.idFinancialYear', $idFy);
            $month_sales->where('invoices.idFinancialYear', $idFy);
        }

        if($request->get('month') != ""){
            $tinv->where('poMonth',$request->get('month'));
            $tsales->where('poMonth',$request->get('month'));
            $orders->where('poMonth',$request->get('month'));
            $top->where('poMonth',$request->get('month'));
            $sales->where('poMonth',$request->get('month'));
            $top_customer->where('poMonth',$request->get('month'));
            $orders_details->where('poMonth',$request->get('month'));
            $invoice->where('poMonth',$request->get('month'));
            $total_payment_done->where('stock_invoicepayment.poMonth',$request->get('month'));
            $today_sales->whereRaw('MONTH(invoiceDate) = ?', [$request->get('month')]);
            $sampleInvoice->where('poMonth',$request->get('month'));
            $month_sales->where('poMonth',$request->get('month'));
            $sampleInvoice = $sampleInvoice->first();
            if($sampleInvoice != null){
                $gd = Carbon::parse($sampleInvoice->invoiceDate);
                $week_sales->whereBetween('invoiceDate', [$gd->startOfWeek(), $gd->endOfWeek()]);
            }else{
                $week_sales = null;
            }
        }else{
            $month_sales->whereRaw('MONTH(invoiceDate) = ?', [Carbon::now()->format('m')]);
            $today_sales->whereDate('invoiceDate',date('Y-m-d'));
            $week_sales->whereBetween('invoiceDate', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()]);
        }

        $data['d1'] = $chartPurchase->groupBy('poMonth')->get()->pluck('total','poMonth')->toArray();
        $data['d2'] = $chartSale->groupBy('poMonth')->get()->pluck('total','poMonth')->toArray();
        $data['d3'] = $lnRevenue->groupBy('idFinancialYear')->get()->pluck('total','idFinancialYear')->toArray();
        $data['d4'] = $lnSales->groupBy('idFinancialYear')->get()->pluck('total','idFinancialYear')->toArray();
        $data['d5'] = $lnSupplier->groupBy('idFinancialYear')->get()->pluck('total','idFinancialYear')->toArray();
        $data['d6'] = $lnOrders->groupBy('idFinancialYear')->get()->pluck('total','idFinancialYear')->toArray();
        $data['orders_details'] = count($orders_details->groupBy('idProduct')->having('total','>',2)->get());
        $data['top_customer'] = $top_customer->groupBy('invoices.idCustomer','customerName')->orderBy('total','DESC')->limit(7)->get();
        $data['invoice'] = $invoice->orderByDesc('invoices.idInvoice')->limit(5)->get();
        $data['quotation'] = $quotation->orderByDesc('quotations.idQuotation')->limit(5)->get();
        $data['sales'] = $sales->groupBy('invoice_details.idProduct')->orderByDesc('idInvoiceDetail')->limit(5)->get(); 
        $data['top'] = $top->groupBy('invoice_details.idProduct')->orderByDesc('total_quantity')->limit(5)->get();
        $data['orders'] = $orders->sum('quantity');
        $pendignTotal = $tsales->where('idSchool', $idSchool)->sum('amountPayable');
        $pendingPayment = $total_payment_done->where('paymentStatus','Success')->sum('paidAmount');
        $pending =  $pendignTotal - $pendingPayment;
        $data['tsales'] = formatAmountInIndianCurrency($pendignTotal);
        $data['today_sales'] = formatAmountInIndianCurrency($today_sales->where('idSchool', $idSchool)->sum('amountPayable'));
        $data['tinv'] = $tinv->where('idSchool', $idSchool)->count();
        $data['total_payments'] = formatAmountInIndianCurrency($pendingPayment);
        $data['total_pending'] = formatAmountInIndianCurrency($pending);

        if($week_sales != null)
        $data['week_sales'] = formatAmountInIndianCurrency($week_sales->sum('amountPayable'));
        else $data['week_sales'] = 0;
        $data['month_sales'] = formatAmountInIndianCurrency($month_sales->sum('amountPayable'));

        $transaction_sales = DB::table('stock_invoicepayment')->join('invoices','stock_invoicepayment.idInvoice','=','invoices.idCustomer')->join('customers','invoices.idCustomer','=','customers.idCustomer')->select('customerName','stock_invoicepayment.*')->where('invoices.idSchool', $idSchool);
        
        $data['total_products'] = DB::table('products')->where('idSchool', $idSchool)->count();
        $data['total_categories'] = DB::table('product_categories')->where('idSchool', $idSchool)->count();
        $data['categories'] = DB::table('products')->join('product_categories','products.idProductCategory','=','product_categories.idProductCategory')->select(DB::raw('COUNT(*) as total'),'categoryName')->where('products.idSchool', $idSchool)->groupBy('products.idProductCategory')->get();
        $data['suppliers'] = DB::table('suppliers')->where('idSchool', $idSchool)->count();
        $data['customer'] = DB::table('customers')->where('idSchool', $idSchool)->count();
        $data['low'] = DB::table('stockledger')->join('products','stockledger.idProduct','=','products.idProduct')->select('productName','quantityInStock')->where('stockledger.idSchool', $idSchool)->where('quantityInStock','<',10)->limit(5)->get();
        
        $purchase = DB::table('purchase_orders')->join('suppliers','purchase_orders.idSupplier','=','suppliers.idSupplier')->select('bussinessName','purchase_orders.*');
        $poTotal = DB::table('purchase_orders');
        $tpo = DB::table('purchase_orders');
        if($request->get('idFinancialYear') != ""){
            $purchase->where('purchase_orders.idFinancialYear', $request->get('idFinancialYear'));
            $poTotal->where('idFinancialYear', $request->get('idFinancialYear'));
            $tpo->where('idFinancialYear', $request->get('idFinancialYear'));
            $transaction_sales->where('stock_invoicepayment.idFinancialYear', $request->get('idFinancialYear'));
        }else{
            $purchase->where('purchase_orders.idFinancialYear', $idFy);
            $poTotal->where('idFinancialYear', $idFy);
            $tpo->where('idFinancialYear', $idFy);
            $transaction_sales->where('stock_invoicepayment.idFinancialYear', $idFy);
        }
        if($request->get('month') != ""){
            $purchase->where('purchase_orders.poMonth', $request->get('month'));
            $poTotal->where('purchase_orders.poMonth', $request->get('month'));
            $tpo->where('purchase_orders.poMonth', $request->get('month'));
            $transaction_sales->where('stock_invoicepayment.poMonth', $request->get('month'));
        }
        $data['purchase'] = $purchase->where('purchase_orders.idSchool', $idSchool)->orderByDesc('purchase_orders.idPurchaseOrder')->limit(5)->get();
        $data['poTotal'] =  formatAmountInIndianCurrency($poTotal->where('idSchool', $idSchool)->sum('totalAmount'));
        $data['tpo'] = $tpo->where('idSchool', $idSchool)->count();
        
        $data['transaction_sales'] = $transaction_sales->orderByDesc('stock_invoicepayment.idInvoicePayment')->limit(5)->get();

        $currency = \App\School::where('idSchool', '=', Auth::guard('school')->user()->idSchool)->first();
        if($currency->idCountry == 2)
        return view('stock-analytics-qatar',compact('data'));
        else return view('stock-analytics',compact('data'));
    }

}

Copyright © 2021 - 2025 IMMREX7