IMMREX7

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

<?php

namespace App\Http\Controllers\API;

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

class TeacherMController extends Controller {

    public function fetchEmployeeLeave($limit){
        $user = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
        if($school->isActive == 'Y'){
            //check for permission
            $checkAuth = DB::table('leave_approval_master')->where('idEmployee', '=', $user->idEmployee)->first();
            if($checkAuth == null){
                return json_encode(["result" => 0 , "leave_taken" => []]);
            }
            $desginations = DB::table('leave_approval_details')->where('idPermitUser',$checkAuth->id)->whereNull('idEmployee')->get()->pluck('idDesignation')->toArray();
            $employee = DB::table('leave_approval_details')->where('idPermitUser',$checkAuth->id)->whereNotNull('idEmployee')->get()->pluck('idEmployee')->toArray();
            $fetchEmployee = DB::table('employees')->select('idEmployee')->whereIn('idDesignation',$desginations)->get()->pluck('idEmployee')->toArray();
            $emp_leaves = \App\EmployeeLeave::where('idSchool', '=', $user->idSchool)
                            ->whereIn('idEmployee', array_merge($employee,$fetchEmployee))
                            ->whereNull('status')
                            ->orderBy('idLeave','DESC')->get();
            return json_encode(["result" => 1, "leave_taken" => $emp_leaves]);
        
        }else return json_encode(array());
    }

    public function manageLeave(Request $request){
        $user = Auth::guard('teacher-api')->user();
        $rules = [
            'idLeave' => 'required',
        ];
        $messages = [
            'idLeave.required' => 'Select Employee First.',
        ];
        $this->validate($request, $rules, $messages);

        $empleave = \App\EmployeeLeave::where('idLeave',$request->idLeave)->first();
        $employee = \App\Employee::where('idEmployee', '=', $empleave->idEmployee)->first();
        if($request->status == "Approve with PL(Paid Leave)"){
            $date = Carbon::parse($empleave->leave_from);
            $now = Carbon::parse($empleave->leave_to);
            $diff = $date->diffInDays($now) + 1;
            //check max allowed
            $designationWise = \App\LeaveMaster::where('idSchool', '=', $employee->idSchool)
                ->where('idDesignation',$employee->idDesignation)
                ->where('idFinancialYear',$this->fys())
                ->whereNull('idEmployee')->first();
            if($designationWise != null){
                if($designationWise->max_allowed > 0){
                    if($diff > $designationWise->max_allowed){
                          return json_encode(['result' => 1, 'message' => "You have surpassed the allowed max days per month."]);  
                    }
                }
            }else{
                $paidLeaves = \App\LeaveMaster::where('idSchool', '=', $employee->idSchool)
                    ->where('idDesignation',$employee->idDesignation)
                    ->where('idEmployee',$employee->idEmployee)
                    ->where('idFinancialYear',$this->fys())->first();
                if($paidLeaves != null){
                    if($paidLeaves->max_allowed > 0){
                        if($diff > $paidLeaves->max_allowed){
                            return json_encode(['result' => 0, 'message' => "You have surpassed the allowed max days per month."]);  
                        }
                    }
                }    
            }    
            
            $empleave->save();

            $empleave->status = $request->status;
            if(isset($request->remarks))
            $empleave->remarks = $request->remarks;
            $empleave->status_date = Carbon::now()->format("Y-m-d");
            $empleave->isEmployee = $user->idEmployee;

            DB::table('employee_leaves')->insert([
                "idSchool" =>  $user->idSchool,
                "idEmployee" => $empleave->idEmployee,
                "idFinancialYear" =>  $this->fys(),
                "idLeave" => $empleave->idLeave,
                "idMonth" => $date->format('m'),
                "leave_date" => $date->format("Y-m-d")
            ]);
            if($empleave->leave_from != $empleave->leave_to){
                for ($x = 1; $x < $diff; $x++) {
                    $currentDay = $date->addDays(1);
                    DB::table('employee_leaves')->insert([
                        "idSchool" =>  $user->idSchool,
                        "idEmployee" => $empleave->idEmployee,
                        "idFinancialYear" =>  $this->fys(),
                        "idLeave" => $empleave->idLeave,
                        "idMonth" => $currentDay->format("m"),
                        "leave_date" => $currentDay->format("Y-m-d")
                    ]);
                } 
            }
        }else{
            $empleave->save();

            $empleave->status = $request->status;
            if(isset($request->remarks))
            $empleave->remarks = $request->remarks;
            $empleave->status_date = Carbon::now()->format("Y-m-d");
            $empleave->isEmployee = $user->idEmployee;
        }
        $empleave->update();
        return json_encode(['result' => 1, 'message' => 'Leave request has been updated with status '.$request->status]);
    }

    public function fetchLeaveBalance($idEmployee,$month){
        $user = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
        if($school->isActive == 'Y'){
            $leaves = array();
            $employee = \App\Employee::where('idEmployee', '=', $idEmployee)->first();
            if($employee == null){
                return json_encode($leaves);
            }
            $designationWise = \App\LeaveMaster::where('idSchool', '=', $employee->idSchool)
                ->where('idDesignation',$employee->idDesignation)
                ->where('idFinancialYear',$this->fys())
                ->where('leaveType',"monthly")
                ->whereNull('idEmployee')
                ->sum('paidLeaves') * 12;
            $paidLeaves = \App\LeaveMaster::where('idSchool', '=', $employee->idSchool)
                ->where('idDesignation',$employee->idDesignation)
                ->where('idEmployee',$employee->idEmployee)
                ->where('idFinancialYear',$this->fys())
                ->where('leaveType',"monthly")
                ->sum('paidLeaves') * 12;
            
            $monthlyAllowedLeave =   \App\LeaveMaster::where('idSchool', '=', $employee->idSchool)
            ->where('idDesignation',$employee->idDesignation)
            ->where('idFinancialYear',$this->fys())
            ->where('leaveType',"monthly")
            ->whereNull('idEmployee')
            ->sum('paidLeaves');
            if($monthlyAllowedLeave == null){
                $monthlyAllowedLeave = \App\LeaveMaster::where('idSchool', '=', $employee->idSchool)
                ->where('idDesignation',$employee->idDesignation)
                ->where('idEmployee',$employee->idEmployee)
                ->where('idFinancialYear',$this->fys())
                ->where('leaveType',"monthly")
                ->sum('paidLeaves');
            }  

            $leaves["totalMonthLeaves"] = $designationWise + $paidLeaves;

            $designationYearWise = \App\LeaveMaster::where('idSchool', '=', $employee->idSchool)
                ->where('idDesignation',$employee->idDesignation)
                ->where('idFinancialYear',$this->fys())
                ->where('leaveType',"yearly")
                ->whereNull('idEmployee')
                ->sum('paidLeaves');
            $paidYearLeaves = \App\LeaveMaster::where('idSchool', '=', $employee->idSchool)
                ->where('idDesignation',$employee->idDesignation)
                ->where('idEmployee',$employee->idEmployee)
                ->where('idFinancialYear',$this->fys())
                ->where('leaveType',"yearly")
                ->sum('paidLeaves');

            //check for leave balance
            $leaveBalance = \App\LeaveBalance::where('idSchool', '=', $employee->idSchool)
            ->where('idEmployee',$employee->idEmployee)
            ->where('idFinancialYear',$this->fys())
            ->sum('balance');   
            $leaves["totalYearLeaves"] = $designationYearWise + $paidYearLeaves;
        
            $leaves["emp_leaves_taken"] = DB::table('employee_leaves')->where('idFinancialYear',$this->fys())->where('idSchool', '=', $employee->idSchool)->where('idEmployee', '=', $employee->idEmployee)->count();
            if($leaveBalance == 0)
            $leaves["left_leaves"] = ($leaves["totalMonthLeaves"] + $leaves["totalYearLeaves"]) - $leaves["emp_leaves_taken"]; 
            else $leaves["left_leaves"] = ($leaves["totalMonthLeaves"] + $leaves["totalYearLeaves"]) - $leaves["emp_leaves_taken"]  - $leaveBalance; 

            $leaves["monthly_allowed"] = $monthlyAllowedLeave;
            $leaves["monthly_token"] = DB::table('employee_leaves')->where('idFinancialYear',$this->fys())->where('idSchool', '=', $employee->idSchool)->where('idMonth', '=', $month)->where('idEmployee', '=', $employee->idEmployee)->count();

            return json_encode($leaves);
        }else return json_encode(array());
    }

    public function fetchExams(Request $request){
        $user = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
        if($school->isActive == 'Y'){
            $idExam = \App\MarkExams::where('idClass',$request->idClass)->where('idFinancialYear', $this->fys())->whereRaw('idSection IS NULL OR idSection = ?', [$request->idSection])->groupBy('idType')->get()->pluck('idType')->toArray();
            $data = \App\MarkExamType::whereIn('idType', $idExam)
            ->orderBy('idType')->paginate()->items();
            return json_encode($data);
        }else return json_encode(array());
    }

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

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

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

    public function fetchLeave($limit){
        $user = Auth::guard('teacher-api')->user();
        $leaves = DB::table('leave_types')->select('name')->get()->pluck('name')->toArray();
        $leaveManage = $this->fetchEmployeeLeaves($user);
        $emp_leaves = \App\EmployeeLeave::where('idSchool', '=', $user->idSchool)->where('idEmployee', '=', $user->idEmployee)->orderBy('idLeave','DESC')->get();
        $data = [
            'leave_types' => $leaves,
            'leave_overview' => $leaveManage,
            'leave_taken' => $emp_leaves,
        ];
        return json_encode($data);
    }

    public function fetchEmployeeLeaves($user){
        $leaves = array();
        $designationWise = \App\LeaveMaster::where('idSchool', '=', $user->idSchool)
        ->where('idDesignation',$user->idDesignation)
        ->where('idFinancialYear',$this->fys())
        ->where('leaveType',"monthly")
        ->whereNull('idEmployee')
        ->sum('paidLeaves');
        $paidLeaves = \App\LeaveMaster::where('idSchool', '=', $user->idSchool)
        ->where('idDesignation',$user->idDesignation)
        ->where('idEmployee',$user->idEmployee)
        ->where('idFinancialYear',$this->fys())
        ->where('leaveType',"monthly")
        ->sum('paidLeaves');
        $leaves["totalMonthLeaves"] = $designationWise + $paidLeaves;

        $designationYearWise = \App\LeaveMaster::where('idSchool', '=', $user->idSchool)
        ->where('idDesignation',$user->idDesignation)
        ->where('idFinancialYear',$this->fys())
        ->where('leaveType',"yearly")
        ->whereNull('idEmployee')
        ->sum('paidLeaves');
        $paidYearLeaves = \App\LeaveMaster::where('idSchool', '=', $user->idSchool)
        ->where('idDesignation',$user->idDesignation)
        ->where('idEmployee',$user->idEmployee)
        ->where('idFinancialYear',$this->fys())
        ->where('leaveType',"yearly")
        ->sum('paidLeaves');
        
        $leaves["totalYearLeaves"] = $designationYearWise + $paidYearLeaves;
        if($leaves["totalMonthLeaves"] > 0){
            $now = Carbon::now();
            $leaves["emp_leaves_taken"] = DB::table('employee_leaves')->where('idFinancialYear',$this->fys())->where('idMonth',$now->format('m'))->where('idSchool', '=', $user->idSchool)->where('idEmployee', '=', $user->idEmployee)->count();
        }else
        $leaves["emp_leaves_taken"] = DB::table('employee_leaves')->where('idFinancialYear',$this->fys())->where('idSchool', '=', $user->idSchool)->where('idEmployee', '=', $user->idEmployee)->count();
        return $leaves;
    }

    public function storeLeave(Request $request){
        $teacher = Auth::guard('teacher-api')->user();
        $rules = [
            'leave_type' => 'required',
            'fromDate' => 'required',
            'toDate' => 'required'
        ];
        $messages = [
            'leave_type.required' => 'Select Leave Type First.',
        ];
        $this->validate($request, $rules, $messages);
        $empleave = new \App\EmployeeLeave();
        $empleave->idSchool = $teacher->idSchool;
        $empleave->idEmployee = $teacher->idEmployee;
        $empleave->leave_type = $request->leave_type;
        $empleave->leave_from =Carbon::parse($request->fromDate)->format("Y-m-d");
        $empleave->leave_to = Carbon::parse($request->toDate)->format("Y-m-d");
        $empleave->leave_message = $request->adminMessage;
        $leaves = $this->fetchEmployeeLeaves($teacher);
        $empleave->paid_avialable = "Monthly : ".$leaves["totalMonthLeaves"]." Yearly :".$leaves["totalYearLeaves"];
        $empleave->idFinancialYear = $this->fys();
        $empleave->save();
        /*if ($request->hasFile('leaveFile')) {
            $hw = 'leave_file_' . $empleave->idLeave . '.' . $request->file('leaveFile')->getClientOriginalExtension();
            $request->file('leaveFile')->storeAs('public/schools/' . $teacher->idSchool . '/leaves/', $hw);
            $empleave->documents = $hw;
            $empleave->update();
        }*/
        return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
    }


    public function sendAttendanceNotification(Request $request){
        //return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
        $user = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
        //$k = 0;
        if ($school->isActive == 'Y') {
            $obj = json_decode($request->getContent(), true);
            foreach ($obj['values'] as $key => $value) {
                $status = $value['nameValuePairs']['studentStatus'] == 'P' ? "present" : "absent";
                $student = \App\AdmEntry::where('ecNo', '=', $value['nameValuePairs']['ecNo'])->where('idSchool', '=', $user->idSchool)->first();
                $reg_ids = DB::table('students')
                                        ->join('parents', 'students.father_mobile', '=', 'parents.mobile')
                                        ->select('parents.idFirebase')
                                        ->where('students.idStudent', $student->idStudent)
                                        ->get()->pluck('idFirebase')->toArray();
                //SendNotificationApi::sendSingleNotification($reg_ids, "Manual Attendance : Dear Parent, Your Child " . $student->firstName . " is " . $status . " in class");
                /*$reg_ids = DB::table('students')
                                        ->join('parents', 'students.mother_mobile', '=', 'parents.mobile')
                                        ->select('parents.idFirebase')
                                        ->where('students.idStudent', $student->idStudent)
                                        ->get()->pluck('idFirebase')->toArray();
                SendNotificationApi::sendSingleNotification($reg_ids, "Manual Attendance : Dear Parent, Your Child " . $student->firstName . " is " . $status . " in class");
                $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
                $student = \App\AdmEntry::where('ecNo', '=', $value['nameValuePairs']['ecNo'])->where('idSchool', '=', $school->idSchool)->first();
                */
                if($school->smsmode == "auto"){
                $phone_number = implode(',', array($student->father_mobile));
                $message = 'Dear Parent, Your Child ' .$student->firstName. ' is ' .$status. ' Today - ' .$school->schoolName.'Regards  '.$school->sms_regard_text.'.';
                $template = \App\SchoolSmsTemplate::where('idSchool', '=', $school->idSchool)->where('template_name', '=', 'manual_present')->first();
                    if (!empty($template)) {
                        $tempid = $template->template_id;
                        if($template->status == "Y")
                        \App\Http\SendSmsApi::getUserNumber($phone_number, $message, $school, $tempid);
                    }
                    DB::table('student_attendance_notification')->insert([
                            'idStudent' => $student->idStudent,
                            'notification' => $message,
                            'created_at' => date('Y-m-d'),
                        ]);
                }
            }
        
        }

        return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
    }

    public function addManualAttendance(Request $request) {
        $user = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
        if ($school->isActive == 'Y') {
            $obj = json_decode($request->getContent(), true);
            foreach ($obj['values'] as $key => $value) {
                $studentStatus = $value['nameValuePairs']['studentStatus'];
                $attendance = new \App\Attendance();
                if($request->get('session') != null){
                    $attendance->routine = $request->get('session');
                }
                $attendance->Enrollment_Number = $value['nameValuePairs']['ecNo'];
                if ($value['nameValuePairs']['studentStatus'] != 'I') {
                    $attendance->idType = 'M';
                    if (is_null($attendance->status))
                        $attendance->status = 'A';
                    $attendance->status = $value['nameValuePairs']['studentStatus'];

                    $current_timestamp = Carbon::now()->toDateTimeString();
                    if (array_key_exists('pastDate', $value['nameValuePairs'])) {
                        if($value['nameValuePairs']['pastDate'] != ""){
                            $pastDate =  Carbon::createFromFormat('Y-m-d H:i:s', $value['nameValuePairs']['pastDate'].' 00:00:00');
                            $current_timestamp = $pastDate->toDateTimeString();
                            $attendance->TimeStamp = $pastDate->timestamp;
                        }else{
                            $attendance->TimeStamp = Carbon::now()->timestamp;           
                        }
                    }else $attendance->TimeStamp = Carbon::now()->timestamp;        
                    
                    $attendance->idMonth = Carbon::createFromFormat('Y-m-d H:i:s', $current_timestamp)->month;
                    $attendance->idSchool = $user->idSchool;
                    $attendance->date = Carbon::parse($current_timestamp)->format('d-m-Y');
                    $status = $value['nameValuePairs']['studentStatus'] == 'P' ? "present" : "absent";
                    $prevAttendance = \App\Attendance::where('Enrollment_Number', '=', $value['nameValuePairs']['ecNo'])
                                    ->where('idSchool', $user->idSchool)
                                    ->where('idType', 'M')
                                    ->where('date', Carbon::parse($current_timestamp)->format('Y-m-d'))->first();

                    if ($prevAttendance) {
                        $prevAttendance->status = $value['nameValuePairs']['studentStatus'];
                        $current_timestamp = Carbon::now()->toDateTimeString();
                        if (array_key_exists('pastDate', $value['nameValuePairs'])) {
                            if($value['nameValuePairs']['pastDate'] != ""){
                                $pastDate =  Carbon::createFromFormat('Y-m-d H:i:s', $value['nameValuePairs']['pastDate'].' 00:00:00');
                                $current_timestamp = $pastDate->toDateTimeString();
                                $prevAttendance->TimeStamp = $pastDate->timestamp;
                            }else{
                                $prevAttendance->TimeStamp = Carbon::now()->timestamp;           
                            }
                        }else $prevAttendance->TimeStamp = Carbon::now()->timestamp; 
                        $prevAttendance->idMonth = Carbon::createFromFormat('Y-m-d H:i:s', $current_timestamp)->month;
                        $prevAttendance->idSchool = $user->idSchool;
                        $prevAttendance->date = Carbon::parse($current_timestamp)->format('d-m-Y');
                        $prevAttendance->update();
                        
                        /*if($school->smsmode == "auto" && $school->idSchool != 135 && $school->idSchool != 140 ){
                            $student = \App\AdmEntry::where('ecNo', '=', $value['nameValuePairs']['ecNo'])->where('idSchool', '=', $user->idSchool)->first();
                            $reg_ids = DB::table('students')
                                            ->join('parents', 'students.father_mobile', '=', 'parents.mobile')
                                            ->select('parents.idFirebase')
                                            ->where('students.idStudent', $student->idStudent)
                                            ->get()->pluck('idFirebase')->toArray();
                            SendNotificationApi::sendSingleNotification($reg_ids, "Manual Attendance : Dear Parent, Your Child " . $student->firstName . " is " . $status . " in class");
                            $reg_ids = DB::table('students')
                                            ->join('parents', 'students.mother_mobile', '=', 'parents.mobile')
                                            ->select('parents.idFirebase')
                                            ->where('students.idStudent', $student->idStudent)
                                            ->get()->pluck('idFirebase')->toArray();
                            SendNotificationApi::sendSingleNotification($reg_ids, "Manual Attendance : Dear Parent, Your Child " . $student->firstName . " is " . $status . " in class");
    
                            $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
                            $student = \App\AdmEntry::where('ecNo', '=', $value['nameValuePairs']['ecNo'])->where('idSchool', '=', $school->idSchool)->first();
                            $phone_number = implode(',', array($student->father_mobile));
                            $message = 'Dear Parent, Your Child ' .$student->firstName. ' is ' .$status. ' Today - ' .$school->schoolName.'Regards  '.$school->sms_regard_text.'.';
                            $template = \App\SchoolSmsTemplate::where('idSchool', '=', $school->idSchool)->where('template_name', '=', 'manual_present')->first();
                            if (!empty($template)) {
                                $tempid = $template->template_id;
                                \App\Http\SendSmsApi::getUserNumber($phone_number, $message, $school, $tempid);
                            }
                        }*/

                        if($school->smsmode == "auto" && $school->idSchool != 135 && $school->idSchool != 140 ){
                            $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
                            $student = \App\AdmEntry::where('ecNo', '=', $value['nameValuePairs']['ecNo'])->where('idSchool', '=', $school->idSchool)->first();
                            $phone_number = implode(',', array($student->father_mobile));
                            $message = 'Dear Parent, Your Child ' .$student->firstName. ' is ' .$status. ' Today - ' .$school->schoolName.'Regards  '.$school->sms_regard_text.'.';
                            $template = \App\SchoolSmsTemplate::where('idSchool', '=', $school->idSchool)->where('template_name', '=', 'manual_present')->first();
                            if (!empty($template)) {
                                $tempid = $template->template_id;
                                if($template->status == "Y")
                                \App\Http\SendSmsApi::getUserNumber($phone_number, $message, $school, $tempid);
                            }
                        }

                        if($school->notificationmode == "auto" && $school->idSchool != 135 && $school->idSchool != 140 ){
                            $student = \App\AdmEntry::where('ecNo', '=', $value['nameValuePairs']['ecNo'])->where('idSchool', '=', $user->idSchool)->first();
                            $reg_ids = DB::table('students')
                                                ->join('parents', 'students.father_mobile', '=', 'parents.mobile')
                                                ->select('parents.idFirebase')
                                                ->where('students.idStudent', $student->idStudent)
                                                ->get()->pluck('idFirebase')->toArray();
                            SendNotificationApi::sendSingleNotification($reg_ids, "Manual Attendance : Dear Parent, Your Child " . $student->firstName . " is " . $status . " in class");
                        }
                        
                    } else {
                        $attendance->save();

                        /*if($school->smsmode == "auto"){
                            $student = \App\AdmEntry::where('ecNo', '=', $value['nameValuePairs']['ecNo'])->where('idSchool', '=', $user->idSchool)->first();
                            $reg_ids = DB::table('students')
                                            ->join('parents', 'students.father_mobile', '=', 'parents.mobile')
                                            ->select('parents.idFirebase')
                                            ->where('students.idStudent', $student->idStudent)
                                            ->get()->pluck('idFirebase')->toArray();
                            SendNotificationApi::sendSingleNotification($reg_ids, "Manual Attendance : Dear Parent, Your Child " . $student->firstName . " is " . $status . " in class");
                            $reg_ids = DB::table('students')
                                            ->join('parents', 'students.mother_mobile', '=', 'parents.mobile')
                                            ->select('parents.idFirebase')
                                            ->where('students.idStudent', $student->idStudent)
                                            ->get()->pluck('idFirebase')->toArray();
                            SendNotificationApi::sendSingleNotification($reg_ids, "Manual Attendance : Dear Parent, Your Child " . $student->firstName . " is " . $status . " in class");

                            $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
                            $student = \App\AdmEntry::where('ecNo', '=', $value['nameValuePairs']['ecNo'])->where('idSchool', '=', $school->idSchool)->first();
                            $phone_number = implode(',', array($student->father_mobile));
                            // $message = 'Dear Parent, Your Child '.$student->firstName.' is '.$status.' today '.$school->schoolName;

                            $message = 'Dear Parent, Your Child ' .$student->firstName. ' is ' .$status. ' Today - ' .$school->schoolName. ' Regards  '.$school->sms_regard_text.'.';
                            $template = \App\SchoolSmsTemplate::where('idSchool', '=', $school->idSchool)->where('template_name', '=', 'manual_present')->first();
                            if (!empty($template)) {
                                $tempid = $template->template_id;
                                \App\Http\SendSmsApi::getUserNumber($phone_number, $message, $school, $tempid);
                            }
                        }*/
                        if($school->smsmode == "auto" && $school->idSchool != 135 && $school->idSchool != 140 ){
                            $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
                            $student = \App\AdmEntry::where('ecNo', '=', $value['nameValuePairs']['ecNo'])->where('idSchool', '=', $school->idSchool)->first();
                            $phone_number = implode(',', array($student->father_mobile));
                            $message = 'Dear Parent, Your Child ' .$student->firstName. ' is ' .$status. ' Today - ' .$school->schoolName.'Regards  '.$school->sms_regard_text.'.';
                            $template = \App\SchoolSmsTemplate::where('idSchool', '=', $school->idSchool)->where('template_name', '=', 'manual_present')->first();
                            if (!empty($template)) {
                                $tempid = $template->template_id;
                                if($template->status == "Y")
                                \App\Http\SendSmsApi::getUserNumber($phone_number, $message, $school, $tempid);
                            }
                        }

                        if($school->idSchool != 135 && $school->idSchool != 140 ){
                            $student = \App\AdmEntry::where('ecNo', '=', $value['nameValuePairs']['ecNo'])->where('idSchool', '=', $user->idSchool)->first();
                            $reg_ids = DB::table('students')
                                                ->join('parents', 'students.father_mobile', '=', 'parents.mobile')
                                                ->select('parents.idFirebase')
                                                ->where('students.idStudent', $student->idStudent)
                                                ->get()->pluck('idFirebase')->toArray();

                            if($school->notificationmode == "auto")                     
                            SendNotificationApi::sendSingleNotification($reg_ids, "Manual Attendance : Dear Parent, Your Child " . $student->firstName . " is " . $status . " in class");
                        }
                    }
                }
            }
            return response()->json(['success' => "SUCCESS",'mode' => $school->smsmode], 200, ['app-status' => 'success']);
        } else {
            return response()->json(['success' => "FAILED"], 404, ['app-status' => 'success']);
        }
    }

    public function getStudentDocuments(Request $request, $id , $type ,$limit){
        $user = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
        if ($school->isActive == 'Y') {
            $documents = null;
            if($type == "H"){
                $documents = \App\Homework::where('idHomework', '=', $id)->first();    
            }else if($type == "P"){
                $documents = \App\PracticeSet::where('idSet', '=', $id)->first();
            }else{

            }

            if($request->get('filter') == "Y"){
                $result = DB::table('students')
                ->leftJoin('home_files','students.idStudent','=','home_files.idStudent')
                ->select('students.firstName', 'students.middleName', 'students.lastName','students.idSchool', 'students.ecNo', 'home_files.*')
                ->where('students.idClass', $documents->idClass)
                ->where('students.idSection', $documents->idSection)
                ->where('idFinancialYear', $this->fys())
                ->where('students.idSchool', $user->idSchool)
                ->where('home_files.idTopic', $id)
                ->where('home_files.idType', $type)
                ->get();
            }else{
                $idStudent = DB::table('home_files')->select('idStudent')->where('home_files.idTopic', $id)->where('home_files.idType', $type)->pluck('idStudent')->toArray();
                $result = DB::table('students')
                        ->select('students.firstName', 'students.middleName', 'students.lastName', 'students.ecNo')
                        ->where('students.idClass', $documents->idClass)
                        ->where('students.idSection', $documents->idSection)
                        ->whereNotIn('idStudent',$idStudent)->get();
            }
            return json_encode($result);
        }else{
            return json_encode(array());
        }
    }

    public function getDetails() {
        $user = Auth::guard('teacher-api')->user();
        $user['schoolName'] = DB::table('schools')->where('idSchool', $user->idSchool)->value('schoolName');
        $user['login_type'] = "Teacher";
        if(isset($user->idDepartment)){
            $department = \App\Department::where('idDepartment',$user->idDepartment)->first();
            if($department->departmentName == "Security"){
                $user['login_type'] = "Visitor";
            }
        }  
        if(isset($user->idDesignation)){
            $designation = \App\Designation::where('idDesignation',$user->idDesignation)->first();
            if($designation->designationName == "Guard"){
                $user['login_type'] = "Visitor";
            }else if($designation->designationName != "Teacher"){
                $user['login_type'] = "Employee";
            }
        } 
        $assign = DB::table('teacher_classes')
                        ->join('classes', 'teacher_classes.idClass', '=', 'classes.idClass')
                        ->join('sections', 'teacher_classes.idSection', '=', 'sections.idSection')
                        ->select('classes.className', 'sections.sectionName', 'teacher_classes.idClass', 'teacher_classes.idSection', 'teacher_classes.*')
                        ->where('teacher_classes.idEmployee', $user->idEmployee)
                        ->where('teacher_classes.idFinancialYear', $this->fys())
                        ->where('teacher_classes.idSchool', $user->idSchool)->get();
        $user["idTeacher"] = $user["idEmployee"];
        $sessions = \App\FinancialYear::where('idSchool', '=', $user->idSchool)->select('financialYearName', 'idFinancialYear')->orderBy('startDate', 'DESC')->get();
        return json_encode(array(
            "profile" => $user,
            "class" => $assign,
            'session' => $sessions,
            'user' => $user['login_type']
        ));
    }

    public function getAllStudents($id, $secId, $date, Request $request) {
        $user = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
        if ($school->isActive == 'Y') {
            $students = DB::table('students')
                    ->select('students.firstName', 'students.middleName', 'students.lastName', 'students.ecNo', 'students.idStudent')//,'attandance.status')
                    ->where('students.idClass', $id)
                    ->where('students.isActive', 'Y')
                    ->where('students.idSection', $secId)
                    ->where('idFinancialYear', $this->fys())
                    ->where('students.idSchool', $user->idSchool)
                    ->get();

            $result = array();
            foreach ($students as $student) {
                $attendance = DB::table('attandance')
                        ->where('Enrollment_Number', '=', $student->ecNo)
                        ->where('status', '!=', 'OUT')
                        ->where('idSchool', '=', $user->idSchool)
                        ->where('date', '=', $date);
                if($request->get('session') != null){
                    $attendance = $attendance->where('routine', '=', $request->get('session'));
                }     
                $attendance = $attendance->first();
                if ($attendance) {
                    $attendanceData = array(
                        'firstName' => $student->firstName,
                        'middleName' => $student->middleName,
                        'lastName' => $student->lastName,
                        'ecNo' => $student->ecNo,
                        'idStudent' => $student->idStudent,
                        'status' => $attendance->status
                    );
                } else {
                    $attendanceData = array(
                        'firstName' => $student->firstName,
                        'middleName' => $student->middleName,
                        'lastName' => $student->lastName,
                        'ecNo' => $student->ecNo,
                        'idStudent' => $student->idStudent,
                        'status' => null
                    );
                }
                array_push($result, $attendanceData);
            }
            return json_encode($result);
        } else {
            return json_encode(array());
        }
    }


    public function geCardStudent($idSchool,$id, $secId){
        $result = [];
        $data = \App\CardView::select(DB::raw("'link' AS type"),'studentName as firstName','parentName as father_fname', 'className as ecNo','id as idCard','idStudent','isChecked as isProcessed')
        ->where('idSchool', $idSchool)
        ->where('idClass', $id)
        ->where(function($query) use ($secId) {
            $query->where('idSection', $secId)
            ->whereNotNull('idSection');
        })
        ->get();
        foreach($data as $var){
            if($var->idStudent == null)
            array_push($result,[
                'firstName' => $var->firstName,
                'father_fname' => $var->father_fname,
                'ecNo' => $var->ecNo,
                'type' => 'link',
                'idStudent' => $var->id,
                'isProcessed' => $var->isProcessed,
            ]);
            else 
            array_push($result,[
                'firstName' => $var->firstName,
                'father_fname' => $var->father_fname,
                'ecNo' => $var->ecNo,
                'idStudent' => $var->idStudent,
                'isProcessed' => $var->isProcessed,
            ]);

        }
        return json_encode($result);
    }

    public function geCardStudents($id, $secId, Request $request) {
        $user = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
        if ($school->isActive == 'Y') {
            //check for empty sections
            $card = \App\CardView::whereNull('idStudent')->where('idSchool', '=', $user->idSchool)->first();
            if($card != null) return $this->geCardStudent($user->idSchool,$id, $secId);
            $students = DB::table('students')
                    ->leftJoin('virtual_card_view','students.idStudent','=','virtual_card_view.idStudent')
                    ->select('students.firstName', 'students.middleName', 'students.lastName', 'students.ecNo','students.father_fname','students.father_lname', 'students.idStudent',DB::raw('IFNULL(isChecked, "N") as isProcessed'))
                    ->where('students.idClass', $id)
                    ->where('students.isActive', 'Y')
                    ->where('students.idSection', $secId);
            if($request->get('session') != "" && $request->get('session') != null){
                $students = $students->where('students.idFinancialYear', $request->get('session'));
            }else {
                $students = $students->where('students.idFinancialYear', $this->fys());  
            }      
            $students = $students->where('students.idSchool', $user->idSchool)
                    ->get();
            return json_encode($students);
        } else {
            return json_encode(array());
        }
    }

    public function saveVirtualCard($id, Request $request){
        $user = Auth::guard('teacher-api')->user();
        if($request->get('link') != null){
            if($request->get('link') == "Y"){
                $card = \App\CardView::whereNull('idStudent')->first();
                if($card != null){
                    $isVerified = \App\CardView::where('id',$id)->where('idSchool', '=', $user->idSchool)->first();
                    if($isVerified != null){
                        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
                        if($request->type == "edit"){
                            $isVerified->studentName = $request->name;
                            $isVerified->address = $request->address;
                            $isVerified->pincode = $request->pincode;
                            $isVerified->city = $request->city;
                            $isVerified->student_dob = $request->dob;
                            $isVerified->contact_alternative = $request->mother_contact;
                            $isVerified->contactNo = $request->father_contact;

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

                            if(isset($request->idSection)){
                                $isVerified->sectionName = \App\Section::select('sectionName','idSection')->where('idSection',$request->idSection)->first()->sectionName;
                                $isVerified->idSection = $request->idSection;
                                $isVerified->update();
                            }
                        }
                        $isVerified->idEmployee = $user->idEmployee;
                        $isVerified->isChecked = 'Y';
                        $isVerified->verificationDate= Carbon::today()->format('Y-m-d');
                        $isVerified->update();
                        return json_encode(array(
                                'success' => 'SUCCESS',
                                "message" => "Card details are saved."
                            ));
                    }            
                }
            }
        }        

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

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

                if($request->type == "edit"){
                    DB::table('students')
                    ->where('idStudent', $id)
                    ->update(['firstName' => $request->name,'middleName' => '','lastName' => '','studentDob' => Carbon::parse($request->dob)->format('Y-m-d'),'photo' => $card->photo ,'contactPersonMobile' => $request->father_contact,'contactPersonTel' => $request->mother_contact,'resAddress' => $request->address,'resCity' => $request->city,'resPincode' => $request->pincode]);
                }

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

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

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

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

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

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

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

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

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

                $isVerified->idEmployee = $user->idEmployee;
                $isVerified->isChecked = 'Y';
                $isVerified->verificationDate= Carbon::today()->format('Y-m-d');
                $isVerified->update();

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

    public function viewHomework($limit,Request $request) {
        $user = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
        if ($school->isActive == 'Y') {
            $idClass = DB::table('teacher_classes')->where('teacher_classes.idEmployee', $user->idEmployee)->get()->pluck('idClass')->toArray();
            $homeworks = \App\Homework::select('homework.*','classes.className','sections.sectionName')->leftJoin('classes', 'homework.idClass', '=', 'classes.idClass')
                    ->leftJoin('sections', 'homework.idSection', '=', 'sections.idSection')
                    ->where('homework.idSchool', '=', $user->idSchool)
                    ->whereRaw('homework.idFinancialYear IS NOT NULL AND homework.idFinancialYear = ?', [$this->fys()])
                    ->whereNull('homework.idClass')
                    ->where('isPublished', 'Y')
                    ->orWhere(function($query) use ($idClass) {
                        $query->whereIn('homework.idClass', $idClass)
                        ->whereNotNull('homework.idFinancialYear');
                    });
            if($request->get('search') != "" || $request->get('date') != ""){
                if($request->get('search') != "")
                    $homeworks->where('subject','LIKE','%'.$request->get('search').'%');
                if($request->get('date') != ""){
                    $now = Carbon::parse($request->get('date'));
                    $homeworks->whereDate('publishDate',$now);
                }
            }
            $homeworks = $homeworks->orderBy('idHomework', 'desc')
                    ->skip($limit)
                    ->take(20)->get();
            return json_encode($homeworks);
        } else {
            return json_encode(array());
        }
    }

    public function getLiveConference($skip) {
        $user = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();

        if ($school->isActive == 'Y' && $school->isActive == 'Y') {
            $data = DB::table('video_confernce')->where('idFinancialYear', '=', $this->fys())
                    ->where('idSchool', '=', $user->idSchool)
                    ->orderBy('idConference', 'desc')
                    ->skip($skip)
                    ->take(15)
                    ->get();
            return json_encode($data);
        } else {
            return json_encode(array());
        }
    }

    public function startLiveConference($id) {
        $teacher = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $teacher->idSchool)->first();
        $liveClass = DB::table('video_confernce')->where('idTeacher', $teacher->idEmployee)->where('idFinancialYear', $this->fys())->where('idConference', $id)->first();

        $affected = DB::table('video_confernce')
                ->where('idConference', $id)
                ->update(['isActive' => "Y"]);

        $reg_ids = DB::table('students')
                        ->join('parents', 'students.father_mobile', '=', 'parents.mobile')
                        ->select('parents.idFirebase')->where('students.idClass', $liveClass->idClass);

        if ($liveClass->idSection != null)
            $reg_ids = $reg_ids->where('students.idSection', $liveClass->idSection);

        $reg_ids = $reg_ids->where('students.idFinancialYear', $this->fys())
                        ->where('students.idSchool', $school->idSchool)
                        ->get()->pluck('idFirebase')->toArray();

        SendNotificationApi::sendNotification($reg_ids, "Live Video Class : " . $liveClass->title . " has been started click here to join or go to the app click on live video class menu");

        $reg_ids = DB::table('students')
                        ->join('parents', 'students.mother_mobile', '=', 'parents.mobile')
                        ->select('parents.idFirebase')->where('students.idClass', $liveClass->idClass);

        if ($liveClass->idSection != null)
            $reg_ids = $reg_ids->where('students.idSection', $liveClass->idSection);

        $reg_ids = $reg_ids->where('students.idFinancialYear', $this->fys())
                        ->where('students.idSchool', $school->idSchool)
                        ->get()->pluck('idFirebase')->toArray();
        SendNotificationApi::sendNotification($reg_ids, "Live Video Class : " . $liveClass->title . " has been started click here to join or go to the app click on live video class menu");
        return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
    }

    public function endLiveConference($id) {
        $teacher = Auth::guard('teacher-api')->user();
        if ($id == "none") {
            return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
        }
        $school = \App\School::where('idSchool', '=', $teacher->idSchool)->first();
        $liveClass = DB::table('video_confernce')->where('idTeacher', $teacher->idEmployee)->where('idFinancialYear', $this->fys())->where('idConference', $id)->first();
        $affected = DB::table('video_confernce')
                ->where('idConference', $id)
                ->update(['isActive' => "W"]);
        $reg_ids = DB::table('students')
                        ->join('parents', 'students.father_mobile', '=', 'parents.mobile')
                        ->select('parents.idFirebase')->where('students.idClass', $liveClass->idClass);

        if ($liveClass->idSection != null)
            $reg_ids = $reg_ids->where('students.idSection', $liveClass->idSection);

        $reg_ids = $reg_ids->where('students.idFinancialYear', $this->fys())
                        ->where('students.idSchool', $school->idSchool)
                        ->get()->pluck('idFirebase')->toArray();

        SendNotificationApi::sendNotification($reg_ids, "Live Video Class : " . $liveClass->title . " has been ended");

        $reg_ids = DB::table('students')
                        ->join('parents', 'students.mother_mobile', '=', 'parents.mobile')
                        ->select('parents.idFirebase')->where('students.idClass', $liveClass->idClass);

        if ($liveClass->idSection != null)
            $reg_ids = $reg_ids->where('students.idSection', $liveClass->idSection);

        $reg_ids = $reg_ids->where('students.idFinancialYear', $this->fys())
                        ->where('students.idSchool', $school->idSchool)
                        ->get()->pluck('idFirebase')->toArray();
        SendNotificationApi::sendNotification($reg_ids, "Live Video Class : " . $liveClass->title . " has been ended");

        return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
    }

    public function deleteLiveConference($id) {
        $liveClass = DB::table('video_confernce')->where('idConference', $id)->delete();
        return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
    }

    public function addLiveConference(Request $request) {
        $rules = [
            'idClass' => 'required',
            'description' => 'required|max:120',
            'key' => 'required|max:500',
            'title' => 'required'
        ];
        $messages = [
            'idClass.required' => 'Class must be selected.'
        ];
        $this->Validate($request, $rules, $messages);
        if ($request->idHost == 1 || $request->idHost == 2) {
            if (!str_contains($request->key, 'https://')) {
                $request->key = 'https://' . $request->key;
            }
        }
        $teacher = \App\Employee::where('idEmployee', '=', Auth::guard('teacher-api')->user()->idEmployee)->first();
        $school = \App\School::where('idSchool', '=', $teacher->idSchool)->first();
        if ($school->isActive == 'Y') {
            foreach ($request->section as $key1 => $value1) {
                if ($request->$value1 == "All") {
                    $id = DB::table('video_confernce')->insertGetId(
                            [
                                'idSchool' => $teacher->idSchool,
                                'idFinancialYear' => $this->fys(),
                                'idClass' => $request->idClass,
                                'idTeacher' => $teacher->idEmployee,
                                'title' => $request->title,
                                'description' => $request->description,
                                'type' => $request->type,
                                'videoType' => $request->idHost,
                                'videoKey' => $request->key
                            ]
                    );
                } else
                    $id = DB::table('video_confernce')->insertGetId(
                            [
                                'idSchool' => $teacher->idSchool,
                                'idFinancialYear' => $this->fys(),
                                'idClass' => $request->idClass,
                                'idSection' => $value1,
                                'idTeacher' => $teacher->idEmployee,
                                'title' => $request->title,
                                'description' => $request->description,
                                'videoType' => $request->idHost,
                                'type' => $request->type,
                                'videoKey' => $request->key
                            ]
                    );
            }
            return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);

            $reg_ids = DB::table('students')
                            ->join('parents', 'students.father_mobile', '=', 'parents.mobile')
                            ->select('parents.idFirebase')->where('students.idClass', $request->idClass);

            $isAll = "";
            if (is_array($request->idSection)) {
                foreach ($request->section as $key1 => $value1) {
                    if ($request->$value1 != "All") {
                        $reg_ids = $reg_ids->where('students.idSection', $request->idSection);

                        $reg_ids = $reg_ids->where('students.idFinancialYear', Session::get('idFinancialYear'))
                                        ->where('students.idSchool', $teacher->idSchool)
                                        ->get()->pluck('idFirebase')->toArray();
                        SendNotificationApi::sendNotification($reg_ids, "Live Video Class : " . $liveClass->title . " has been created.");
                    } else {
                        $isAll = "All";
                    }
                }

                if ($isAll == "All") {
                    $reg_ids = $reg_ids->where('students.idFinancialYear', Session::get('idFinancialYear'))
                                    ->where('students.idSchool', $teacher->idSchool)
                                    ->get()->pluck('idFirebase')->toArray();
                    SendNotificationApi::sendNotification($reg_ids, "Live Video Class : " . $liveClass->title . " has been created.");
                }
            } else {
                $reg_ids = $reg_ids->where('students.idFinancialYear', Session::get('idFinancialYear'))
                                ->where('students.idSchool', $teacher->idSchool)
                                ->get()->pluck('idFirebase')->toArray();
                SendNotificationApi::sendNotification($reg_ids, "Live Video Class : " . $liveClass->title . " has been created.");
            }

            $reg_ids = DB::table('students')
                            ->join('parents', 'students.mother_mobile', '=', 'parents.mobile')
                            ->select('parents.idFirebase')->where('students.idClass', $request->idClass);

            $isAll = "";
            if (is_array($request->idSection)) {
                foreach ($request->section as $key1 => $value1) {
                    if ($request->$value1 != "All") {
                        $reg_ids = $reg_ids->where('students.idSection', $request->idSection);

                        $reg_ids = $reg_ids->where('students.idFinancialYear', Session::get('idFinancialYear'))
                                        ->where('students.idSchool', $teacher->idSchool)
                                        ->get()->pluck('idFirebase')->toArray();
                        SendNotificationApi::sendNotification($reg_ids, "Live Video Class : " . $liveClass->title . " has been created.");
                    } else {
                        $isAll = "All";
                    }
                }

                if ($isAll == "All") {
                    $reg_ids = $reg_ids->where('students.idFinancialYear', Session::get('idFinancialYear'))
                                    ->where('students.idSchool', $teacher->idSchool)
                                    ->get()->pluck('idFirebase')->toArray();
                    SendNotificationApi::sendNotification($reg_ids, "Live Video Class : " . $liveClass->title . " has been created.");
                }
            } else {
                $reg_ids = $reg_ids->where('students.idFinancialYear', Session::get('idFinancialYear'))
                                ->where('students.idSchool', $teacher->idSchool)
                                ->get()->pluck('idFirebase')->toArray();
                SendNotificationApi::sendNotification($reg_ids, "Live Video Class : " . $liveClass->title . " has been created.");
            }
        } else {
            return response()->json(['success' => "FAILED"], 404, ['app-status' => 'success']);
        }
    }

    public function updateLiveConference(Request $request, $id) {
        $rules = [
            'description' => 'required|max:120',
            'key' => 'required|max:500',
            'title' => 'required'
        ];
        $messages = [
        ];
        $this->Validate($request, $rules, $messages);
        $teacher = \App\Employee::where('idEmployee', '=', Auth::guard('teacher-api')->user()->idEmployee)->first();
        $school = \App\School::where('idSchool', '=', $teacher->idSchool)->first();
        if ($school->isActive == 'Y') {
            //foreach ($request->sections as $key1 => $value1) {
            //if ($request->$value1 == "All") {
            $id = DB::table('video_confernce')
                    ->where('idConference', $id)
                    ->update([
                'title' => $request->title,
                'description' => $request->description,
                'type' => $request->type,
                'videoType' => $request->idHost,
                'videoKey' => $request->key
                    ]
            );
            //}else
            // }
            return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
        } else {
            return response()->json(['success' => "FAILED"], 404, ['app-status' => 'success']);
        }
    }

    public function viewTHomeworkDoc($id) {
        $homework = \App\Homework::findOrFail($id);
        $path = storage_path('app/public/schools/' . $homework->idSchool . '/homeworks/' . $homework->homeworkFile);
        return response()->file($path);
    }

    public function viewStudentImage($id) {
        $exam = DB::table('exam_mcq_response')->where('idValidation', $id)->first();
        $school = \App\School::where('idSchool', '=', Auth::guard('teacher-api')->user()->idSchool)->first();
        $nw = 'mcq_' . $exam->idStudent . '_result_' . $exam->idQuestion . '.jpg';
        $path = storage_path('app/public/schools/' . $school->idSchool . '/mcq/' . $nw);
        return response()->file($path);
    }

    public function getStudents($id) {
        $user = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
        if ($school->isActive == 'Y') {
            $sections_ids = array_map('intval', explode(',', $id));
            $students = \App\AdmEntry::select('students.firstName', 'students.middleName', 'students.lastName', 'students.idStudent', 'students.ecNo')->whereIn('idSection', $sections_ids)->where('students.idFinancialYear', $this->fys())->where('students.isActive', 'Y')->get();
            return json_encode($students);
        } else {
            return json_encode(array());
        }
    }

    public function storeHomework(Request $request) {
        $rules = [
            'idClass' => 'required',
            'subject' => 'required|max:120',
            'homework' => 'required|max:500',
            'homeworkFile' => 'mimes:doc,jpg,png,jpeg,pdf,docx|max:25000'
        ];
        $messages = [
            'idClass.required' => 'Class must be selected.',
            'idSection.required' => 'Section must be selected.'
        ];
        $this->Validate($request, $rules, $messages);
        $teacher = \App\Employee::where('idEmployee', '=', Auth::guard('teacher-api')->user()->idEmployee)->first();
        $school = \App\School::where('idSchool', '=', $teacher->idSchool)->first();
        if ($school->isActive == 'Y') {
            if (is_array($request->students)) {
                foreach ($request->students as $key => $value) {
                    $std = \App\AdmEntry::where('idStudent', '=', $value)->first();
                    $homework = new \App\Homework();
                    $homework->fill($request->all());
                    $homework->idFinancialYear = $this->fys();
                    $homework->idStudent = $value;
                    $homework->idSection = $std->idSection;
                    $homework->idSchool = $teacher->idSchool;
                    $homework->publishDate = today_date();
                    $homework->isPublished = 'Y';
                    DB::beginTransaction();
                    $homework->save();
                    if ($request->hasFile('homeworkFile')) {
                        $hw = 'homework_' . $homework->idHomework . '.' . $request->file('homeworkFile')->getClientOriginalExtension();
                        $request->file('homeworkFile')->storeAs('public/schools/' . $teacher->idSchool . '/homeworks/', $hw);
                        $homework->homeworkFile = $hw;
                    }
                    $homework->total_student = 1;
                    $homework->update();
                    DB::commit();
                    /* $reg_ids=DB::table('students')
                      ->join('parents', 'students.father_mobile', '=', 'parents.mobile')
                      ->select('parents.idFirebase')
                      ->where('students.idStudent',  $value)
                      ->get()->pluck('idFirebase')->toArray();
                      SendNotificationApi::sendSingleNotification( $reg_ids,"Homework : ".$request->homework);
                      $reg_ids=DB::table('students')
                      ->join('parents', 'students.mother_mobile', '=', 'parents.mobile')
                      ->select('parents.idFirebase')
                      ->where('students.idStudent',  $value)

                      ->get()->pluck('idFirebase')->toArray();
                      SendNotificationApi::sendSingleNotification( $reg_ids,"Homework : ".$request->homework); */
                }
            } else {
                foreach ($request->sections as $key1 => $value1) {
                    $homework = new \App\Homework();
                    $homework->fill($request->all());
                    $homework->idSection = $value1;
                    $homework->idSchool = $teacher->idSchool;
                    $homework->publishDate = today_date();
                    $homework->idFinancialYear = $this->fys();
                    $homework->isPublished = 'Y';
                    DB::beginTransaction();
                    $homework->save();
                    if ($request->hasFile('homeworkFile')) {
                        $hw = 'homework_' . $homework->idHomework . '.' . $request->file('homeworkFile')->getClientOriginalExtension();
                        $request->file('homeworkFile')->storeAs('public/schools/' . $teacher->idSchool . '/homeworks/', $hw);
                        $homework->homeworkFile = $hw;
                    }
                    $homework->update();
                    $totalStudents = DB::table('students')
                        ->where('students.idSection', $value1)
                        ->where('students.idClass', $request->idClass)
                        ->where('students.idFinancialYear', $this->fys())
                        ->count();    
                    $homework->total_student = $totalStudents;     
                    $homework->update();
                    DB::commit();
                    /* $reg_ids=DB::table('students')
                      ->join('parents', 'students.father_mobile', '=', 'parents.mobile')
                      ->select('parents.idFirebase')
                      ->where('students.idSection', $value1)
                      ->where('students.idClass', $request->idClass)
                      ->where('students.idFinancialYear', $this->fys())
                      ->where('students.idSchool', $teacher->idSchool)
                      ->get()->pluck('idFirebase')->toArray();
                      SendNotificationApi::sendNotification( $reg_ids,"Homework : ".$request->homework);
                      $reg_ids=DB::table('students')
                      ->join('parents', 'students.mother_mobile', '=', 'parents.mobile')
                      ->select('parents.idFirebase')
                      ->where('students.idSection', $value1)
                      ->where('students.idClass', $request->idClass)
                      ->where('students.idSchool', $teacher->idSchool)
                      ->where('students.idFinancialYear', $this->fys())
                      ->get()->pluck('idFirebase')->toArray();
                      SendNotificationApi::sendNotification( $reg_ids,"Homework : ".$request->homework); */
                }
            }
            return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
        } else {
            return response()->json(['success' => "FAILED"], 404, ['app-status' => 'success']);
        }
    }

    public function viewTimetable($idClass, $idSection) {
        $teacher = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $teacher->idSchool)->first();
        if ($school->isActive == 'Y') {
            $classes = DB::table('teacher_subjects')
                            ->select('subjects.subjectName')
                            ->join('subjects', 'teacher_subjects.idSubject', '=', 'subjects.idSubject')
                            ->where('teacher_subjects.idEmployee', '=', $teacher->idEmployee)
                            ->where('teacher_subjects.idClass', '=', $idClass)
                            ->orderBy('teacher_subjects.idTeacherSubject')->get();
            $periods = \App\Period::leftJoin('timetable', 'periods.idPeriod', '=', 'timetable.idPeriod')
                            ->leftJoin('subjects', 'subjects.idSubject', '=', 'timetable.idSubject')
                            ->leftJoin('employees', 'timetable.idEmployee', '=', 'employees.idEmployee')
                            ->select('subjects.subjectName', 'periods.*', 'timetable.idSubject', 'timetable.idWeekday', 'employees.firstName', 'employees.lastName')
                            ->where('periods.idSchool', '=', $teacher->idSchool)
                            ->where('periods.idClass', '=', $idClass)
                            ->where('periods.idSection', '=', $idSection)
                            ->orderBy('periods.idPeriod', 'asc')->get();
            return json_encode(array(
                "periods" => $periods,
                "classes" => $classes
            ));
        } else {
            return json_encode(array());
        }
    }

    public function viewNoticeboards($limit,Request $request) {
        $user = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
        if ($school->isActive == 'Y') {
            $idClass = DB::table('teacher_classes')->where('teacher_classes.idEmployee', $user->idEmployee)->get()->pluck('idClass')->toArray();
            $notices = \App\Noticeboard::select('noticeboard.*','classes.className','sections.sectionName')->leftJoin('classes', 'noticeboard.idClass', '=', 'classes.idClass')
                    ->leftJoin('sections', 'noticeboard.idSection', '=', 'sections.idSection')
                    ->where('noticeboard.idSchool', '=', $user->idSchool)
                    ->whereRaw('noticeboard.idFinancialYear IS NOT NULL AND noticeboard.idFinancialYear = ?', [$this->fys()])
                    ->whereNull('noticeboard.idClass')
                    ->where('isPublished', 'Y')
                    ->orWhere(function($query) use ($idClass) {
                        $query->whereIn('noticeboard.idClass', $idClass)
                        ->whereNotNull('noticeboard.idFinancialYear');
                    });
            if($request->get('search') != "" || $request->get('date') != ""){
                if($request->get('search') != "")
                    $notices->where('subject','LIKE','%'.$request->get('search').'%');
                if($request->get('date') != ""){
                    $now = Carbon::parse($request->get('date'));
                    $notices->whereDate('publishDate',$now);
                }
            }
            $notices = $notices->orderBy('idNoticeboard', 'desc')
                    ->skip($limit)
                    ->take($limit + 20)->get();
            return json_encode($notices);
        } else {
            return json_encode(array());
        }
    }

    //schoolmis-1c700
    public function viewEmployeeNoticeboards($limit) {
        $user = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
        if ($school->isActive == 'Y') {
            $idClass = $user->idEmployee;
            $notices = \App\EmployeeNoticeboard::select('noticeboard_employee.*','departments.departmentName','designations.designationName')->leftJoin('departments', 'noticeboard_employee.idDepartment', '=', 'departments.idDepartment')
                    ->leftJoin('designations', 'noticeboard_employee.idDesignation', '=', 'designations.idDesignation')
                    ->where('noticeboard_employee.idSchool', '=', $user->idSchool)
                    ->whereRaw('noticeboard_employee.idFinancialYear IS NOT NULL AND noticeboard_employee.idFinancialYear = ?', [$this->fys()])
                    ->whereNull('noticeboard_employee.idDepartment')
                    ->where('isPublished', 'Y')
                    ->orWhere(function($query) use ($idClass) {
                        $query->where('noticeboard_employee.idEmployee', $idClass)
                        ->whereNotNull('noticeboard_employee.idFinancialYear');
                    })
                    ->orderBy('idEmployeeNoticeboard', 'desc')
                    ->skip($limit)
                    ->take($limit + 20);
            $notices = $notices->get();
            return json_encode($notices);
        } else {
            return json_encode(array());
        }
    }

    public function viewNoticeboardsDocs($id) {
        $notice = \App\Noticeboard::findOrFail($id);
        $path = storage_path('app/public/schools/' . $notice->idSchool . '/noticeboard/' . $notice->noticeFile);
        return response()->file($path);
    }

    public function viewSalary() {
        $user = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
        return json_encode(array());
        if ($school->isActive == 'Y') {
            $slstr = \App\SalaryStructure::where('idEmployee', '=', $user->idEmployee)->first();
            $emppayments = \App\EmpPayment::selectRaw('(select months.monthName from months where months.idMonth=employee_payment.idMonth) as monthName,employee_payment.*')
                            ->where('employee_payment.idSchool', '=', $user->idSchool)->where('employee_payment.idEmployee', '=', $user->idEmployee)->orderBy('employee_payment.idEmpPayment', 'desc')->get();
            return json_encode(array(
                "salary" => $slstr,
                "transaction" => $emppayments
            ));
        } else {
            return json_encode(array());
        }
    }

    public function fetchAttendance(Request $request){
        $emp = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $emp->idSchool)->first();
        if ($school->isActive == 'Y') {
            $todaydate = Carbon::now();
            $month = \App\Month::where('idMonth', '=', $request->idMonth)->first();
            $noOfdays = $month->noOfDays;
            $m = $month->idMonth;
            $y = $request->year;
            $days = [];
            $excluded = 0;
            $result = [];
            $total_working = $noOfdays;
            for ($i = 1; $i <= $noOfdays; $i++) {
                $dt = $i . '-' . $m . '-' . $y;

                $tdate = \Carbon\Carbon::parse($dt);
                $hd = '';
                if($school->idCountry == 1){
                    if ($tdate->dayOfWeek == '0' && $school->idSchool != 144 ) {
                        $hd = 'SUNDAY';
                        $excluded++;
                    }
                }else{
                    if ($tdate->dayOfWeek == '5') {
                        $hd = 'FRIDAY';
                        $excluded++;
                    }
                }
                $days[] = array($dt, $hd);
            }
            $total_present = 0; 
            $total_absent = 0; 
            $total_holiday = 0; 
            $allowedLateMinutes = 0;
            $allowedEarlyMinutes = 0;
            $totalLateDays = 0;
            $totalEarlyDays = 0;
            $empDays = [];
            $idFinancialYear = $this->fys();
            $leaveMaster = fetchLeaveMaster($emp,$idFinancialYear);
            foreach($days as $key=>$var){
                $obj = [];
                $tdate = \Carbon\Carbon::parse($var[0]);
                $now = \Carbon\Carbon::now();
                $jdate = $tdate->format('Y-m-d');
                $obj['date'] = $jdate;
                $obj['remarks'] = "";
                $obj['data'] = "A";
                $cdate = intval($tdate->format('d'));
                $length = $tdate->diffInDays($now);
                //check for holiday 
                $holiday = getHoliday($emp,$jdate);
                $shifts = fetchShift($emp,$jdate);
                $dayNight = "AM";
                $nightDay = "AM";
                $isLeaveMaster = "N";
                $empDays[$cdate] = "A";
                $isPaidLeaveMaster = "N";
                if($shifts != null && $holiday == null){
                        $dayNight = strtoupper($shifts->shift_from);
                        $nightDay = strtoupper($shifts->shift_to);
                        $arrival = checkArrival($emp,$jdate,$shifts,$school,$dayNight,$idFinancialYear,$allowedLateMinutes,$totalLateDays);
                        $departure = checkDeparture($emp,$jdate,$shifts,$school,$nightDay,$idFinancialYear,$allowedEarlyMinutes,$totalEarlyDays);
                        $overtime = fetchOvertime($emp,$shifts,$dayNight,$nightDay,$school,$jdate,$idFinancialYear);
                        $totalEarlyDays = $departure['days'];
                        $totalLateDays = $arrival['days'];
                        $nonPaidLeave = DB::table('employee_leave')
                        ->whereDate('leave_from', '<=', $jdate)
                        ->whereDate('leave_to', '>=', $jdate)
                        ->where('idEmployee', $emp->idEmployee)
                        ->where('status' ,'!=', 'Approve with PL(Paid Leave)')
                        ->first();
                        if($nonPaidLeave != null){
                            $isPaidLeaveMaster = "K";
                        }else
                        if(fetchPaidLeave($jdate,$emp) == 1){
                            $isPaidLeaveMaster = "Y";
                        }else if($leaveMaster != null){
                            if($leaveMaster->leave_allocation == "A"){
                                $month = \App\Month::where('monthName', '=', $tdate->format('F'))->first();
                                if($cdate > 1 && $cdate < $month->noOfDays){
                                    if(isset($leaveMaster->exclude_month)){
                                        $month = \App\Month::where('monthName',$tdate->format('F'))->whereIn('idMonth',json_decode($leaveMaster->exclude_month,true))->get();
                                        if(count($month) == 0){
                                            //check for sandwich leave
                                            if($holiday != null){
                                                if(checkForSandwich($emp,$leaveMaster->sandwich,$empDays,$tdate,$cdate,$school) == 1){
                                                    $isLeaveMaster = "Y";
                                                }
                                            }

                                            if($shifts->weekOff  == "Y"){
                                                if(checkForSandwich($emp,$leaveMaster->sandwich,$empDays,$tdate,$cdate,$school) == 1){
                                                    $isLeaveMaster = "Y";
                                                }
                                            }
                                        }
                                    }else{
                                        //check for sandwich leave
                                    }
                                }
                            }
                        }

                }
                else {
                    $arrival = [];
                    $departure = [];
                }
                if($jdate <= $todaydate){
                    if($isPaidLeaveMaster == "Y" || $isPaidLeaveMaster == "K"){
                        if($isPaidLeaveMaster == "K"){
                            $empDays[$cdate] = "A";
                            $total_absent = $total_absent + 1;
                            $obj['data'] = "A";
                            $obj['late'] = "A (Leave)";
                        }else{
                            $total_present = $total_present + 1; 
                            $empDays[$cdate] = "H";
                            $obj['data'] = "P";
                            $obj['remarks'] = "P (Leave)";
                        }
                    }else{
                        if($isLeaveMaster == "Y" && $shifts != null){
                            $total_absent = $total_absent + 1; 
                            $empDays[$cdate] = "A";
                            $obj['data'] = "A";
                            $obj['late'] = "A (Leave)";
                        }else{
                            if($holiday != null){
                                $total_holiday = $total_holiday + 1; 
                                $empDays[$cdate] = "H";
                                $obj['data'] = "W";
                                $obj['remarks'] = $holiday->holidayName;
                            }else{
                                if($shifts != null){
                                    $obj['shift'] = \Carbon\Carbon::parse($shifts->fromTime.' '.$dayNight)->format('H:i').'-'.\Carbon\Carbon::parse($shifts->toTime.' '.$nightDay)->format('H:i');
                                    if($shifts->weekOff  == "Y"){
                                        $total_holiday = $total_holiday + 1; 
                                        $empDays[$cdate] = "H";
                                        $obj['data'] = "W";
                                        $obj['remarks'] = " Weekly-Off";
                                    }else{
                                        if(isset($shifts->fromTime) && isset($shifts->toTime)){
                                            $a_mat = \App\EmpAttendance::where('Enrollment_Number', '=', $emp->enrollmentNo)
                                            ->where('idSchool', '=', $school->idSchool)
                                            ->whereDate('date', '=', $jdate)
                                            ->where('status', '=', 'P')
                                            ->where('idType', '=', 'M')
                                            ->first();
                                            if($a_mat == null){
                                                $aintime = \App\EmpAttendance::where('Enrollment_Number', '=', $emp->enrollmentNo)
                                                ->where('Device_ID', '=', $school->Device_ID)
                                                ->whereDate('date', '=', $jdate)
                                                ->where('status', '=', 'IN')
                                                ->where('idType', '=', 'A')
                                                ->first();
                                                if($aintime)
                                                    $obj['remarks'] = "IN: ".explode(" ",$aintime->TimeStamp)[1];
                                                else
                                                    $obj['remarks'] = "IN: Incomplete Attendance";

                                                $aouttime = \App\EmpAttendance::where('Enrollment_Number', '=', $emp->enrollmentNo)
                                                    ->where('Device_ID', '=', $school->Device_ID)
                                                    ->whereDate('date', '=', $jdate)
                                                    ->where('status', '=', 'OUT')
                                                    ->where('idType', '=', 'A')
                                                    ->first();
                                                    
                                                if($aouttime)
                                                    $obj['remarks'] = $obj['remarks']." OUT: ".explode(" ",$aouttime->TimeStamp)[1];
                                                else
                                                    $obj['remarks'] = $obj['remarks']." OUT: Incomplete Attendance";
                                            
                                            }
                                            if($arrival['status'] == "I" && $departure['status'] == "I"){
                                                $total_absent = $total_absent + 1; 
                                                $empDays[$cdate] = "A";
                                                $obj['data'] = "A";
                                                $obj['remarks'] = "";
                                            }else{
                                                $empDays[$cdate] = "P";
                                                $obj['data'] = "A";
                                                
                                                if($arrival['status'] == "I"){
                                                    $obj['data'] = "A";
                                                }elseif($arrival['status'] == "HF"){
                                                    $obj['data'] = "H";
                                                    $obj['late'] = $arrival['normal_html'];
                                                }elseif($arrival['status'] == "LT"){
                                                    $obj['data'] = "P";
                                                    $obj['late'] = $arrival['normal_html'];
                                                }elseif($arrival['status'] == "P"){
                                                    $obj['data'] = "P";
                                                }

                                                if($arrival['status'] == "A"){
                                                    $total_absent = $total_absent + 1; 
                                                    $empDays[$cdate] = "AB";
                                                    $obj['data'] = "A";
                                                    $obj['remarks'] = $obj['remarks'].' '.$arrival['normal_html'];
                                                }elseif($departure['status'] == "A"){
                                                    $total_absent = $total_absent + 1; 
                                                    $empDays[$cdate] = "AB";
                                                    $obj['data'] = "A";
                                                    $obj['remarks'] = $obj['remarks'].' '.$arrival['normal_html'];
                                                }elseif($departure['status'] == "P" && $arrival['status'] == "P"){
                                                    $total_present = $total_present + 1;
                                                    $obj['data'] = "P";
                                                }elseif( ( $departure['status'] == "LT" || $departure['status'] == "P") && ( $arrival['status'] == "LT" || $arrival['status'] == "P")){
                                                    $total_present = $total_present + 1;
                                                    $obj['data'] = "P";
                                                }elseif($departure['status'] == "HF" || $arrival['status'] == "HF"){
                                                    $total_present = $total_present + 0.5;
                                                    $obj['data'] = "H";
                                                }

                                                if($departure['status'] == "I"){
                                                    if($obj['data'] != "H")
                                                    $obj['data'] = "A";
                                                }elseif($departure['status'] == "HF"){
                                                    //$obj['data'] = "H";
                                                    $obj['late'] = $arrival['normal_html'];
                                                }elseif($departure['status'] == "LT"){
                                                    $obj['data'] = "P";
                                                    $obj['late'] = $arrival['normal_html'];
                                                }elseif($departure['status'] == "P"){
                                                    $obj['data'] = "P";
                                                }

                                                if($overtime['status'] == "Y"){
                                                    
                                                }
                                            }

                                            
                                        }
                                    }
                                }
                            }
                        }
                    }
                }else{
                    $obj['data'] = "Date not came yet";
                    $obj['remarks'] = "IN : 00:00:00 Out : 00:00:00";
                }
                array_push($result,$obj);
            }
            return json_encode(array(
                'overview' => [
                    'present' => "Present - ".$total_present." days",
                    'absent' => "Absent - ".$total_absent." days",
                    'holiday' => "Holiday - ".$total_holiday." days",
                    'working' => "Working -".$total_working." days"
                ],
                'result' => $result
            ));
        
        }else {
            return json_encode(array());
        }
    }

    public function fetchSalarySlip($limit){
        $emp = Auth::guard('teacher-api')->user();
        $empsalaries = DB::table('employee_payment')
                    ->select('employee_payment.*','enrollmentNo','firstName','middleName','lastName','departmentName','designationName','monthName')
                    ->join('employees','employee_payment.idEmployee','=','employees.idEmployee')
                    ->join('departments','employees.idDepartment','=','departments.idDepartment')
                    ->join('designations','employees.idDesignation','=','designations.idDesignation')
                    ->join('months','employee_payment.idMonth','=','months.idMonth')
                    ->where('employee_payment.idFinancialYear', $this->fys())
                    ->where('employee_payment.idEmployee', '=', $emp->idEmployee)->get();
        return  json_encode($empsalaries);        
    }

    public function downloadSlip($id){
        $empsalary = \App\EmpPayment::where('idEmpPayment', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $empsalary->idSchool)->first();
        $month = \App\Month::where('idMonth', '=', $empsalary->idMonth)->first();
        $employee = \App\Employee::where('idEmployee', '=', $empsalary->idEmployee)->first();
        $now = \Carbon\Carbon::now();
        $pay_start = '01' . '-' . $month->idMonth . '-' . $now->year;
        $pay_end = $month->noOfDays . '-' . $month->idMonth . '-' . $now->year;
        $y = $now->year;
        $earnings = \App\SalaryStrAllowances::where('idSalaryStr', '=', $empsalary->idSalaryStr)->get();
        $deductions = \App\SalaryStrDeduction::where('idSalaryStr', '=', $empsalary->idSalaryStr)->get();
        $pdf = PDF::loadView('schools.hrms.print_salaryslip', ['margin_top' => 20], compact('pay_start','pay_end','school', 'empsalary', 'month', 'employee', 'earnings', 'deductions'));
        return $pdf->download('salaryslip.pdf');
    }

    public function viewCalender() {
        $user = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
        
        if ($school->isActive == 'Y') {
            $fy = $this->fys();
            $holidays = \App\HrmsHoliday::where('idSchool', '=', $user->idSchool)->where('idFinancialYear','=',$fy)
            ->whereRaw('idEmployee IS NULL AND department = ?', [$user->idDepartment])
            ->orWhere('idEmployee',$user->idEmployee)
            ->get();
            return json_encode($holidays);
        } else {
            return json_encode(array());
        }
    }

    public function viewGallery($limit,Request $request) {
        $user = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
        if ($school->isActive == 'Y') {
            $folders = \App\GalleryFolder::
                    select('gallery_folder.idFolder', 'gallery_folder.idSchool', 'gallery_folder.folderName')
                    ->selectRaw('(select image from gallery where gallery.idFolder=gallery_folder.idFolder LIMIT 1) as image')
                    ->where('gallery_folder.idSchool', '=', $user->idSchool);
            if($request->get('idClass') != "" || $request->get('date') != "" ){
                if($request->get('idClass') != "") 
                    $folders->where('gallery.idClass', '=', $request->get('idClass'));
                if($request->get('date') != ""){
                    $now = Carbon::parse($request->get('date'));
                    $folders->whereDate('gallery_folder.updated_at',$now->format('Y-m-d'));
                } 
            }
            $folders =$folders->orderBy('idFolder', 'desc')
                    ->skip($limit)
                    ->take(20)
                    ->get();
            return json_encode($folders);
        } else {
            return json_encode(array());
        }
    }

    public function viewGalleryFiles($folder_id, $limit) {
        $user = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
        if ($school->isActive == 'Y') {
            $photos = \App\Gallery::where('idFolder', '=', $folder_id)
                    ->where('idSchool', '=', $user->idSchool)
                    ->whereExists(function ($query) use ($user) {
                        $query->select('idClass')
                        ->from('teacher_classes')
                        ->where('teacher_classes.idEmployee', $user->idEmployee)
                        ->where('teacher_classes.idSchool', $user->idSchool);
                    })
                    ->orderBy('idGallery', 'desc')
                    ->skip($limit)
                    ->take($limit + 10)
                    ->get();
            return json_encode($photos);
        } else {
            return json_encode(array());
        }
    }

    public function downloadGallery($id) {
        $user = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
        if ($school->isActive == 'Y') {
            $photos = \App\Gallery::findOrFail($id);
            $folderName = \App\GalleryFolder::where('idFolder', '=', $photos->idFolder)->value('folderName');
            $path = storage_path('app/public/schools/' . $photos->idSchool . '/galleries/' . $folderName . '/' . $photos->image);
            return response()->file($path);
        } else {
            return json_encode(array());
        }
    }

    public function viewPracticeSet($limit,Request $request) {
        $user = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
        if ($school->isActive == 'Y') {
            $psets = \App\PracticeSet::select('practice_sets.*','classes.className','sections.sectionName')->leftJoin('classes', 'practice_sets.idClass', '=', 'classes.idClass')
                    ->leftJoin('sections', 'practice_sets.idSection', '=', 'sections.idSection')
                    ->where('practice_sets.idSchool', '=', $user->idSchool)
                    ->whereExists(function ($query) use ($user) {
                        $query->select('idClass')
                        ->from('teacher_classes')
                        ->where('teacher_classes.idEmployee', $user->idEmployee)
                        ->where('teacher_classes.idSchool', $user->idSchool);
                    })
                    ->whereExists(function ($query) use ($user) {
                        $query->select('idSection')
                        ->from('teacher_classes')
                        ->where('teacher_classes.idEmployee', $user->idEmployee)
                        ->where('teacher_classes.idSchool', $user->idSchool);
                    })
                    ->where('isPublished', 'Y')
                    ->where('idFinancialYear', $this->fys())
                    ->orWhereNull('practice_sets.idSection');

            if($request->get('search') != "" || $request->get('date') != ""){
                if($request->get('search') != "")
                    $psets->where('subject','LIKE','%'.$request->get('search').'%');
                if($request->get('date') != ""){
                    $now = Carbon::parse($request->get('date'));
                    $psets->whereDate('publishDate',$now);
                }
            }    
            $psets = $psets
                     ->orderBy('idSet', 'desc')->skip($limit)
                    ->take($limit + 20)
                    ->get();
            return json_encode($psets);
        } else {
            return json_encode(array());
        }
    }

    public function viewPracticeDocs($id) {
        $pset = \App\PracticeSet::findOrFail($id);
        $path = storage_path('app/public/schools/' . $pset->idSchool . '/practiceset/' . $pset->practiceFile);
        return response()->file($path);
    }

    public function newsletterSearch($filter, $limit) {
        $user = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
        if ($school->isActive == 'Y') {
            $idClass = DB::table('teacher_classes')->where('teacher_classes.idEmployee', $user->idEmployee)->get()->pluck('idClass')->toArray();
            $newsletters = array();
            if ($filter != "none") {
                if (substr($filter, 0, 1) == "0") {
                    $newsletters = \App\NewsLetter::leftJoin('classes', 'newsletter.idClass', '=', 'classes.idClass')
                            ->select('newsletter.*','classes.className')
                            ->where('newsletter.idSchool', '=', $user->idSchool)
                            ->where('title', 'LIKE', substr($filter, 1) . '%')
                            ->orderBy('idNewsletter', 'desc')
                            ->skip($limit)
                            ->take(20)
                            ->get();
                } else {
                    $newsletters = \App\NewsLetter::leftJoin('classes', 'newsletter.idClass', '=', 'classes.idClass')
                            ->select('newsletter.*','classes.className')
                            ->where('newsletter.idSchool', '=', $user->idSchool)
                            ->where('title', 'LIKE', $filter . '%')
                            ->orderBy('idNewsletter', 'desc')
                            ->skip($limit)
                            ->take(20)
                            ->get();
                }
            } else {
                $newsletters = \App\NewsLetter::leftJoin('classes', 'newsletter.idClass', '=', 'classes.idClass')
                        ->select('newsletter.*','classes.className')
                        ->where('newsletter.idSchool', '=', $user->idSchool)
                        ->whereNull('newsletter.idClass')
                        ->orWhereIn('newsletter.idClass', $idClass)
                        ->orderBy('idNewsletter', 'desc')
                        ->skip($limit)
                        ->take(20)
                        ->get();
            }

            if ($school->idSchool != 14) {
                for ($k = 0; $k < count($newsletters); $k++) {
                    $newsletters[$k]['videoKey'] = $newsletters[$k]['videoLink'];
                    $newsletters[$k]['videoLink'] = "https://www.youtube.com/embed/" . $newsletters[$k]['videoLink'];
                }
            }

            return json_encode($newsletters);
        } else {
            return json_encode(array());
        }
    }

    public function newsletter($limit) {
        $user = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
        if ($school->isActive == 'Y') {
            $idClass = DB::table('teacher_classes')->where('teacher_classes.idEmployee', $user->idEmployee)->get()->pluck('idClass')->toArray();

            $newsletters = \App\NewsLetter::leftJoin('classes', 'newsletter.idClass', '=', 'classes.idClass')
                    ->select('newsletter.*','classes.className')
                    ->where('newsletter.idSchool', '=', $user->idSchool)
                    ->whereNull('newsletter.idClass')
                    ->orWhereIn('newsletter.idClass', $idClass)
                    ->orderBy('idNewsletter', 'desc')
                    ->skip($limit)
                    ->take($limit + 20)
                    ->get();

            if ($school->idSchool != 14) {
                for ($k = 0; $k < count($newsletters); $k++) {
                    $newsletters[$k]['videoLink'] = "https://www.youtube.com/embed/" . $newsletters[$k]['videoLink'];
                    $newsletters[$k]['videoKey'] = $newsletters[$k]['videoLink'];
                }
            }

            return json_encode($newsletters);
        } else {
            return json_encode(array());
        }
    }

    public function positiveNews($limit) {
        $user = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
        if ($school->isActive == 'Y') {
            $idClass = DB::table('teacher_classes')->where('teacher_classes.idEmployee', $user->idEmployee)->get()->pluck('idClass')->toArray();
            $newsletters = \App\PositiveNews::where('idSchool', '=', $user->idSchool)
                    ->whereNull('idClass')
                    ->orWhereIn('idClass', $idClass)
                    ->orderBy('idNews', 'desc')
                    ->skip($limit)
                    ->take($limit + 20)
                    ->get();
            return json_encode($newsletters);
        } else {
            return json_encode(array());
        }
    }

    public function positiveNewsFull($id) {
        $news = \App\PositiveNews::where('idNews', '=', $id)->first();
        return json_encode($news);
    }

    public function viewThoughts($limit) {
        $user = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
        if ($school->isActive == 'Y') {
            $idClass = DB::table('teacher_classes')->where('teacher_classes.idEmployee', $user->idEmployee)->get()->pluck('idClass')->toArray();
            $thoughts = \App\WeekThought::where('idSchool', '=', $user->idSchool)->whereNull('idClass')
                    ->orWhereIn('idClass', $idClass)
                    ->orderBy('idThought', 'desc')
                    ->skip($limit)
                    ->take($limit + 20)
                    ->get();
            return json_encode($thoughts);
        } else {
            return json_encode(array());
        }
    }

    public function viewShortStories($limit) {
        $user = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
        if ($school->isActive == 'Y') {

            $idClass = DB::table('teacher_classes')->where('teacher_classes.idEmployee', $user->idEmployee)->get()->pluck('idClass')->toArray();
            $stories = \App\ShortStory::where('idSchool', '=', $user->idSchool)
                    ->whereNull('idClass')
                    ->orWhereIn('idClass', $idClass)
                    ->orderBy('idStory', 'desc')
                    ->skip($limit)
                    ->take($limit + 20)
                    ->get();
            return json_encode($stories);
        } else {
            return json_encode(array());
        }
    }

    public function viewShortStoriesLong($id) {
        $stories = \App\ShortStory::where('idStory', '=', $id)
                        ->get()->first();
        return json_encode($stories);
    }

    public function viewBirthdays() {
        $user = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
        if ($school->isActive == 'Y') {
            $birthday = DB::table('students')->join('classes', 'students.idClass', '=', 'classes.idClass')
                    ->join('sections', 'students.idSection', '=', 'sections.idSection')
                    ->select('students.firstName', 'students.middleName', 'students.lastName', 'students.studentDob', 'students.gender', 'students.idStudent', 'classes.className', 'sections.sectionName')
                    ->whereRaw("DATE_FORMAT((studentDob),'%m-%d') = DATE_FORMAT(NOW(),'%m-%d')")
                    ->where('students.idSchool', '=', $user->idSchool)
                    ->whereExists(function ($query) use ($user) {
                        $query->select('idClass')
                        ->from('teacher_classes')
                        ->where('teacher_classes.idEmployee', $user->idEmployee)
                        ->where('teacher_classes.idSchool', $user->idSchool);
                    })
                    ->whereExists(function ($query) use ($user) {
                        $query->select('idSection')
                        ->from('teacher_classes')
                        ->where('teacher_classes.idEmployee', $user->idEmployee)
                        ->where('teacher_classes.idSchool', $user->idSchool);
                    })
                    // ->orWhereNull('idSection')
                    ->get();
            return json_encode($birthday);
        } else {
            return json_encode(array());
        }
    }

    public function deleteHomework($id) {
        $user = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
        if ($school->isActive == 'Y') {
            $homework = \App\Homework::findOrFail($id);
            $homework->delete();
            return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
        } else {
            return response()->json(['success' => "FAILED"], 404, ['app-status' => 'success']);
        }
    }

    public function editHomework($id) {
        $user = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
        if ($school->isActive == 'Y') {

            $homework = \App\Homework::findOrFail($id);
            $student = \App\AdmEntry::where('idStudent', '=', $homework->idStudent)->get()->pluck('name')->toArray();
            if (sizeof($student) > 0)
                return response()->json(['homework' => $homework,
                            'student' => $student
                                ], 200, ['app-status' => 'success']);
            else
                return response()->json(['homework' => $homework], 200, ['app-status' => 'success']);
        }else {
            return response()->json(['success' => "FAILED"], 404, ['app-status' => 'success']);
        }
    }

    public function updateHomework($id, Request $request) {
        $rules = [
            'idClass' => 'required',
            'subject' => 'required|max:120',
            'homework' => 'required|max:500',
            'homeworkFile' => 'mimes:doc,jpg,png,jpeg,pdf,docx|max:25000'
        ];
        if (count($request->sections) == 0) {
            $rules += ['idSection' => 'required'];
        }
        $messages = [
            'idClass.required' => 'Class must be selected.',
            'idSection.required' => 'Section must be selected.'
        ];
        $this->Validate($request, $rules, $messages);
        $teacher = \App\Employee::where('idEmployee', '=', Auth::guard('teacher-api')->user()->idEmployee)->first();
        $school = \App\School::where('idSchool', '=', $teacher->idSchool)->first();
        if ($school->isActive == 'Y') {
            $homework = \App\Homework::findOrFail($id);
            $homework->fill($request->all());
            if ($request->hasFile('homeworkFile')) {
                $hw = 'homework_' . $homework->idHomework . '.' . $request->file('homeworkFile')->getClientOriginalExtension();
                $request->file('homeworkFile')->storeAs('public/schools/' . $teacher->idSchool . '/homeworks/', $hw);
                $homework->homeworkFile = $hw;
            }
            if ($homework->update())
                return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
            else
                return response()->json(['success' => "Failed"], 200, ['app-status' => 'success']);
        }else {
            return response()->json(['success' => "FAILED"], 404, ['app-status' => 'success']);
        }
    }

    public function deleteNoticeboards($id) {
        $user = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
        if ($school->isActive == 'Y') {

            $notice = \App\Noticeboard::findOrFail($id);
            $notice->delete();
            return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
        } else {
            return response()->json(['success' => "FAILED"], 404, ['app-status' => 'success']);
        }
    }

    public function getClass() {
        $teacher = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $teacher->idSchool)->first();
        if ($school->isActive == 'Y') {
            $classes = \App\ClassM::select('idClass', 'className')
                            ->where('idSchool', '=', $teacher->idSchool)
                            ->orderBy('idClass')->get();
            return json_encode($classes);
        } else {
            return json_encode(array());
        }
    }

    public function getSubjects() {
        $teacher = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $teacher->idSchool)->first();
        if ($school->isActive == 'Y') {
            $classes = \App\Subject::select('subjectName')
                            ->where('idSchool', '=', $teacher->idSchool)
                            ->where('idFinancialYear', $this->fys())
                            ->distinct()
                            ->orderBy('subjectName')->get();
            return json_encode($classes);
        } else {
            return json_encode(array());
        }
    }

    public function getSection($id) {
        $teacher = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $teacher->idSchool)->first();
        if ($school->isActive == 'Y') {
            $sections = \App\Section::select('idSection', 'sectionName')->where('idSchool', '=', $teacher->idSchool)->where('idClass', '=', $id)->get();
            return json_encode($sections);
        } else {
            return json_encode(array());
        }
    }

    public function addNotice(Request $request) {
        $rules = [
            'idClass' => 'required',
            'subject' => 'required|max:120',
            'notice' => 'required|max:500',
            'noticeFile' => 'mimes:doc,pdf,docx,jpg,png,jpeg|max:10000'
        ];
        $messages = [
            'idClass.required' => 'Class must be selected.',
            'idSection.required' => 'Section must be selected.'
        ];
        $this->Validate($request, $rules, $messages);
        $teacher = \App\Employee::where('idEmployee', '=', Auth::guard('teacher-api')->user()->idEmployee)->first();
        $school = \App\School::where('idSchool', '=', $teacher->idSchool)->first();
        if ($school->isActive == 'Y') {
            if ($request->idClass == 'All') {
                $notice = new \App\Noticeboard();
                $notice->fill($request->all());
                $notice->idClass = null;
                $notice->idSchool = $teacher->idSchool;
                $notice->publishDate = today_date();
                $notice->idFinancialYear = $this->fys();
                $notice->isPublished = 'Y';
                DB::beginTransaction();
                $notice->save();
                if ($request->hasFile('noticeFile')) {
                    $nw = 'notice_' . $notice->idNoticeboard . '.' . $request->file('noticeFile')->getClientOriginalExtension();
                    $request->file('noticeFile')->storeAs('public/schools/' . $teacher->idSchool . '/noticeboard/', $nw);
                    $notice->noticeFile = $nw;
                    $notice->update();
                }
                DB::commit();
                /* $reg_ids=DB::table('students')
                  ->join('parents', 'students.father_mobile', '=', 'parents.mobile')
                  ->select('parents.idFirebase')
                  ->where('students.idSchool', $teacher->idSchool)
                  ->where('students.idFinancialYear', $this->fys())
                  ->get()->pluck('idFirebase')->toArray();
                  SendNotificationApi::sendNotification( $reg_ids,"Circular : ".$request->notice);
                  $reg_ids=DB::table('students')
                  ->join('parents', 'students.mother_mobile', '=', 'parents.mobile')
                  ->select('parents.idFirebase')
                  ->where('students.idSchool', $teacher->idSchool)
                  ->where('students.idFinancialYear', $this->fys())
                  ->get()->pluck('idFirebase')->toArray();
                  SendNotificationApi::sendNotification( $reg_ids,"Circular : ".$request->notice); */
            } else if ($request->has('all')) {
                $notice = new \App\Noticeboard();
                $notice->fill($request->all());
                $notice->idSection = null;
                $notice->idSchool = $teacher->idSchool;
                $notice->publishDate = today_date();
                $notice->idFinancialYear = $this->fys();
                $notice->isPublished = 'Y';
                DB::beginTransaction();
                $notice->save();
                if ($request->hasFile('noticeFile')) {
                    $nw = 'notice_' . $notice->idNoticeboard . '.' . $request->file('noticeFile')->getClientOriginalExtension();
                    $request->file('noticeFile')->storeAs('public/schools/' . $teacher->idSchool . '/noticeboard/', $nw);
                    $notice->noticeFile = $nw;
                    $notice->update();
                }
                DB::commit();
                /* $reg_ids=DB::table('students')
                  ->join('parents', 'students.father_mobile', '=', 'parents.mobile')
                  ->select('parents.idFirebase')
                  ->where('students.idClass', $request->idClass)
                  ->where('students.idSchool', $teacher->idSchool)
                  ->where('students.idFinancialYear', $this->fys())
                  ->get()->pluck('idFirebase')->toArray();
                  SendNotificationApi::sendNotification( $reg_ids,"Circular : ".$request->notice);
                  $reg_ids=DB::table('students')
                  ->join('parents', 'students.mother_mobile', '=', 'parents.mobile')
                  ->select('parents.idFirebase')
                  ->where('students.idClass', $request->idClass)
                  ->where('students.idSchool', $teacher->idSchool)
                  ->where('students.idFinancialYear', $this->fys())
                  ->get()->pluck('idFirebase')->toArray();
                  SendNotificationApi::sendNotification( $reg_ids,"Circular : ".$request->notice); */
            } else {
                foreach ($request->sections as $key1 => $value1) {
                    $notice = new \App\Noticeboard();
                    $notice->fill($request->all());
                    $notice->idSection = $value1;
                    $notice->idFinancialYear = $this->fys();
                    $notice->idSchool = $teacher->idSchool;
                    $notice->publishDate = today_date();
                    $notice->isPublished = 'Y';
                    DB::beginTransaction();
                    $notice->save();
                    if ($request->hasFile('noticeFile')) {
                        $nw = 'notice_' . $notice->idNoticeboard . '.' . $request->file('noticeFile')->getClientOriginalExtension();
                        $request->file('noticeFile')->storeAs('public/schools/' . $teacher->idSchool . '/noticeboard/', $nw);
                        $notice->noticeFile = $nw;
                        $notice->update();
                    }
                    DB::commit();
                    /* $reg_ids=DB::table('students')
                      ->join('parents', 'students.father_mobile', '=', 'parents.mobile')
                      ->select('parents.idFirebase')
                      ->where('students.idSection', $value1)
                      ->where('students.idClass', $request->idClass)
                      ->where('students.idSchool', $teacher->idSchool)
                      ->where('students.idFinancialYear', $this->fys())
                      ->get()->pluck('idFirebase')->toArray();
                      SendNotificationApi::sendNotification( $reg_ids,"Circular : ".$request->notice);
                      $reg_ids=DB::table('students')
                      ->join('parents', 'students.mother_mobile', '=', 'parents.mobile')
                      ->select('parents.idFirebase')
                      ->where('students.idSection', $value1)
                      ->where('students.idClass', $request->idClass)
                      ->where('students.idSchool', $teacher->idSchool)
                      ->where('students.idFinancialYear', $this->fys())
                      ->get()->pluck('idFirebase')->toArray();
                      SendNotificationApi::sendNotification( $reg_ids,"Circular : ".$request->notice); */
                }
            }
            return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
        } else {
            return response()->json(['success' => "FAILED"], 404, ['app-status' => 'success']);
        }
    }

    public function editNotice($id) {
        $user = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
        if ($school->isActive == 'Y') {
            $notice = \App\Noticeboard::findOrFail($id);
            $classes = \App\ClassM::where('idClass', '=', $notice->idClass)->get()->pluck('className');
            $section = \App\Section::where('idSection', '=', $notice->idSection)->get()->pluck('sectionName');
            return response()->json(['notice' => $notice,
                        'class' => $classes,
                        'section' => $section
                            ], 200, ['app-status' => 'success']);
        } else {
            return response()->json(['success' => "FAILED"], 404, ['app-status' => 'success']);
        }
    }

    public function updateNotice($id, Request $request) {
        $rules = [
            'subject' => 'required|max:120',
            'notice' => 'required|max:500',
            'noticeFile' => 'mimes:pdf|max:10000'
        ];
        $messages = [];
        $this->Validate($request, $rules, $messages);
        $teacher = \App\Employee::where('idEmployee', '=', Auth::guard('teacher-api')->user()->idEmployee)->first();
        $school = \App\School::where('idSchool', '=', $teacher->idSchool)->first();
        if ($school->isActive == 'Y') {
            $notice = \App\Noticeboard::findOrFail($id);
            $notice->fill($request->all());
            if ($request->hasFile('noticeFile')) {
                $nw = 'notice_' . $notice->idNoticeboard . '.' . $request->file('noticeFile')->getClientOriginalExtension();
                $request->file('noticeFile')->storeAs('public/schools/' . $teacher->idSchool . '/noticeboard/', $nw);
                $notice->noticeFile = $nw;
            }
            if ($notice->update())
                return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
            else
                return response()->json(['success' => "Failed"], 200, ['app-status' => 'success']);
        }else {
            return response()->json(['success' => "FAILED"], 404, ['app-status' => 'success']);
        }
    }

    public function createFolder(Request $request) {
        $user = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
        if ($school->isActive == 'Y') {
            $rules = ['folderName' => 'required'];
            $this->validate($request, $rules);
            $folder = new \App\GalleryFolder();
            $folder->fill($request->all());
            $folder->idSchool = Auth::guard('teacher-api')->user()->idSchool;
            if ($folder->save())
                return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
            else
                return response()->json(['success' => "Failed"], 200, ['app-status' => 'success']);
        }else {
            return response()->json(['success' => "FAILED"], 404, ['app-status' => 'success']);
        }
    }

    public function editFolder($id) {
        $user = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
        if ($school->isActive == 'Y') {
            $folders = \App\GalleryFolder::where('idSchool', '=', Auth::guard('teacher-api')->user()->idSchool)->get();
            $folder = \App\GalleryFolder::where('idFolder', '=', $id)->first();
            return json_encode($folder);
        } else {
            return json_encode(array());
        }
    }

    public function updateFolder(Request $request, $id) {
        $user = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
        if ($school->isActive == 'Y') {
            $rules = ['folderName' => 'required'];
            $this->validate($request, $rules);
            $folder = \App\GalleryFolder::where('idFolder', '=', $id)->first();
            $folder->fill($request->all());
            if ($folder->update())
                return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
            else
                return response()->json(['success' => "Failed"], 200, ['app-status' => 'success']);
        }else {
            return response()->json(['success' => "FAILED"], 404, ['app-status' => 'success']);
        }
    }

    public function deleteFolder($id) {
        $user = Auth::guard('teacher-api')->user();
        $school = \App\School::where('idSchool', '=', $user->idSchool)->first();
        if ($school->isActive == 'Y') {
            $blog = DB::table('gallery')->where('idFolder', $id)->delete();
            $folder = \App\GalleryFolder::findOrFail($id);
            $folder->delete();
            return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
        } else {
            return response()->json(['success' => "FAILED"], 404, ['app-status' => 'success']);
        }
    }

    public function storeGallery(Request $request) {
        $rules = [
            'idFolder' => 'required',
            'imageTitle' => 'required',
            'image' => 'required'
        ];
        $this->validate($request, $rules);
        $folder = \App\GalleryFolder::where('idFolder', '=', $request->idFolder)->first();
        $f_name = $folder->folderName;
        $gallery = new \App\Gallery();
        $gallery->fill($request->all());
        $gallery->idSchool = Auth::guard('teacher-api')->user()->idSchool;
        $gallery->idFinancialYear = $this->fys();
        if ($request->idClass == 'All') {
            $gallery->idClass = null;
        }
        //check if directory exists and if exist rename the directory
        $basePath = storage_path('app');
        /*if(Auth::guard('teacher-api')->user()->idEmployee == 5682){
            $oldDirectoryPath = $basePath . '/public/schools/' . $gallery->idSchool. '/galleries/' . $f_name;
            $newDirectoryPath = $basePath . '/public/schools/' . $gallery->idSchool. '/galleries/' . $request->idFolder;
            
            if(File::exists($oldDirectoryPath) && File::isDirectory($oldDirectoryPath)){
                if (File::move($oldDirectoryPath, $newDirectoryPath)) {
                    $folder->isFolderId = "Y";
                    $folder->update();
                    DB::table('gallery')->where('idFolder',$request->idFolder)->update(['isFolderId' => 'Y']);
                }
            }else{
                $folder->isFolderId = "Y";
                $folder->update();
            }
        }*/
        //else store normally
        DB::beginTransaction();
        $gallery->save();
        if (str_contains($request->file('image')->getClientOriginalExtension(), 'jpg'))
        $image = 'photo_' . $gallery->idGallery . '.jpg';
        else if (str_contains($request->file('image')->getClientOriginalExtension(), 'jpeg'))
        $image = 'photo_' . $gallery->idGallery . '.jpeg';
        else if (str_contains($request->file('image')->getClientOriginalExtension(), 'png'))
        $image = 'photo_' . $gallery->idGallery . '.png';
        else $image = 'photo_' . $gallery->idGallery . '.'.$request->file('image')->getClientOriginalExtension();
        if( $folder->isFolderId == "Y")
        $request->file('image')->storeAs('public/schools/' . $gallery->idSchool . '/galleries/' . $request->idFolder . '/', $image);
        else
        $request->file('image')->storeAs('public/schools/' . $gallery->idSchool . '/galleries/' . $f_name . '/', $image);
        
        $gallery->image = $image;
        $gallery->update();
        DB::commit();
        /* if($request->idClass == 'All'){
          $reg_ids=DB::table('students')
          ->join('parents', 'students.father_mobile', '=', 'parents.mobile')
          ->select('parents.idFirebase')
          ->where('students.idSchool', Auth::guard('teacher-api')->user()->idSchool)
          ->where('students.idFinancialYear', $this->fys())
          ->get()->pluck('idFirebase')->toArray();
          SendNotificationApi::sendNotification( $reg_ids,"Gallery : ".$request->imageTitle);
          $reg_ids=DB::table('students')
          ->join('parents', 'students.mother_mobile', '=', 'parents.mobile')
          ->select('parents.idFirebase')
          ->where('students.idSchool', Auth::guard('teacher-api')->user()->idSchool)
          ->where('students.idFinancialYear', $this->fys())
          ->get()->pluck('idFirebase')->toArray();
          SendNotificationApi::sendNotification( $reg_ids,"Gallery : ".$request->imageTitle);
          }else{
          $reg_ids=DB::table('students')
          ->join('parents', 'students.father_mobile', '=', 'parents.mobile')
          ->select('parents.idFirebase')
          ->where('students.idClass', $request->idClass)
          ->where('students.idSchool', Auth::guard('teacher-api')->user()->idSchool)
          ->where('students.idFinancialYear', $this->fys())
          ->get()->pluck('idFirebase')->toArray();
          SendNotificationApi::sendNotification( $reg_ids,"Gallery : ".$request->imageTitle);
          $reg_ids=DB::table('students')
          ->join('parents', 'students.mother_mobile', '=', 'parents.mobile')
          ->select('parents.idFirebase')
          ->where('students.idClass', $request->idClass)
          ->where('students.idSchool', Auth::guard('teacher-api')->user()->idSchool)
          ->where('students.idFinancialYear', $this->fys())
          ->get()->pluck('idFirebase')->toArray();
          SendNotificationApi::sendNotification( $reg_ids,"Gallery : ".$request->imageTitle);
          } */
        return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
    }

    public function findFinancialYear() {
        $now = \Carbon\Carbon::now();
        if (Auth::guard('teacher-api')->check()) {
            $teacher = \App\Employee::where('idEmployee', '=', Auth::guard('teacher-api')->user()->idEmployee)->first();
            $finyear = \App\FinancialYear::where('idSchool', '=', $teacher->idSchool)->get();
        } else {
            $finyear = \App\FinancialYear::where('idSchool', '=', Auth::guard('school')->user()->idSchool)->get();
        }
        foreach ($finyear as $fy) {
            $start_date = \Carbon\Carbon::parse($fy->startDate);
            $end_date = \Carbon\Carbon::parse($fy->endDate);
            if ($now->between($start_date, $end_date) == true) {
                return $fy->idFinancialYear;
            }
        }
    }

    public function storeStories(Request $request) {
        $rules = [
            'title' => 'required',
            'source' => 'required',
            'story' => 'required',
            'image' => 'mimes:jpg,jpeg,png|max:2000'
        ];
        if (count($request->classes) == 0) {
            $rules += ['all' => 'required'];
        }
        $messages = [
            'all.required' => 'Class must be selected'
        ];
        $this->validate($request, $rules, $messages);
        if ($request->has('all')) {
            $story = new \App\ShortStory();
            $story->fill($request->all());
            $story->idSchool = Auth::guard('teacher-api')->user()->idSchool;
            $story->publishDate = today_date();
            $story->isPublished = 'Y';
            $story->idFinancialYear = $this->fys();
            DB::beginTransaction();
            $story->save();
            if ($request->has('image')) {
                $nw = 'story_' . $story->idStory . '.' . $request->file('image')->getClientOriginalExtension();
                $request->file('image')->storeAs('public/schools/' . Auth::guard('teacher-api')->user()->idSchool . '/stories/', $nw);
                $story->image = $nw;
                $story->update();
            }
            DB::commit();
            /* $reg_ids=DB::table('students')
              ->join('parents', 'students.father_mobile', '=', 'parents.mobile')
              ->select('parents.idFirebase')
              ->where('students.idSchool', Auth::guard('teacher-api')->user()->idSchool)
              ->where('students.idFinancialYear', $this->fys())
              ->get()->pluck('idFirebase')->toArray();
              SendNotificationApi::sendNotification( $reg_ids,"Short Stories : ".$request->title);
              $reg_ids=DB::table('students')
              ->join('parents', 'students.mother_mobile', '=', 'parents.mobile')
              ->select('parents.idFirebase')
              ->where('students.idSchool', Auth::guard('teacher-api')->user()->idSchool)
              ->where('students.idFinancialYear', $this->fys())
              ->get()->pluck('idFirebase')->toArray();
              SendNotificationApi::sendNotification( $reg_ids,"Short Stories : ".$request->title); */
        } else {
            foreach ($request->classes as $key => $value) {
                $story = new \App\ShortStory();
                $story->fill($request->all());
                $story->idSchool = Auth::guard('teacher-api')->user()->idSchool;
                $story->idClass = $value;
                $story->publishDate = today_date();
                $story->idFinancialYear = $this->fys();
                $story->isPublished = 'Y';
                DB::beginTransaction();
                $story->save();
                if ($request->has('image')) {
                    $nw = 'story_' . $story->idStory . '.' . $request->file('image')->getClientOriginalExtension();
                    $request->file('image')->storeAs('public/schools/' . Auth::guard('teacher-api')->user()->idSchool . '/stories/', $nw);
                    $story->image = $nw;
                    $story->update();
                }
                DB::commit();
                /* $reg_ids=DB::table('students')
                  ->join('parents', 'students.father_mobile', '=', 'parents.mobile')
                  ->select('parents.idFirebase')
                  ->where('students.idClass', $value)
                  ->where('students.idSchool', Auth::guard('teacher-api')->user()->idSchool)
                  ->where('students.idFinancialYear', $this->fys())
                  ->get()->pluck('idFirebase')->toArray();
                  SendNotificationApi::sendNotification( $reg_ids,"Short Stories : ".$request->title);
                  $reg_ids=DB::table('students')
                  ->join('parents', 'students.mother_mobile', '=', 'parents.mobile')
                  ->select('parents.idFirebase')
                  ->where('students.idClass', $value)
                  ->where('students.idSchool', Auth::guard('teacher-api')->user()->idSchool)
                  ->where('students.idFinancialYear', $this->fys())
                  ->get()->pluck('idFirebase')->toArray();
                  SendNotificationApi::sendNotification( $reg_ids,"Short Stories : ".$request->title); */
            }
        }
        return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
    }

    public function deleteStories($id) {
        $story = \App\ShortStory::findOrfail($id);
        $story->delete();
        return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
    }

    public function editStories($id) {
        $story = \App\ShortStory::findOrfail($id);
        return json_encode($story);
    }

    public function updateStories($id, Request $request) {
        $rules = [
            'title' => 'required',
            'source' => 'required',
            'story' => 'required',
            'image' => 'mimes:jpg,jpeg,png|max:2000'
        ];
        $this->validate($request, $rules);
        $story = \App\ShortStory::findOrfail($id);
        $story->fill($request->all());
        if ($request->has('image')) {
            $nw = 'story_' . $story->idStory . '.' . $request->file('image')->getClientOriginalExtension();
            $request->file('image')->storeAs('public/schools/' . Auth::guard('teacher-api')->user()->idSchool . '/stories/', $nw);
            $story->image = $nw;
        }
        if ($story->update())
            return response()->json(['success' => "SUCCESS", 'message' => $story->image], 200, ['app-status' => 'success']);
        else
            return response()->json(['success' => "Failed"], 200, ['app-status' => 'success']);
    }

    public function addThoughts(Request $request) {
        $rules = [
            'source' => 'required',
            'thought' => 'required',
            'image' => 'mimes:jpg,jpeg,png|max:5000',
        ];
        if ($request->has('idClass')) {
            $rules += ['idClass' => 'required'];
        }
        if ($request->has('schedule')) {
            $rules += ['publishDate' => 'required'];
        }
        $messages = [
            'idClass.required' => 'Class must be selected',
        ];
        $this->validate($request, $rules, $messages);
        if ($request->has('all')) {
            $thought = new \App\WeekThought();
            $thought->fill($request->all());
            $thought->idSchool = Auth::guard('teacher-api')->user()->idSchool;
            $thought->idFinancialYear = $this->fys();
            $thought->publishDate = today_date();
            $thought->isPublished = 'Y';

            DB::beginTransaction();
            $thought->save();
            if ($request->has('image')) {
                $nw = 'thought_' . $thought->idThought . '.' . $request->file('image')->getClientOriginalExtension();
                $request->file('image')->storeAs('public/schools/' . Auth::guard('teacher-api')->user()->idSchool . '/thoughts/', $nw);
                $thought->image = $nw;
                $thought->update();
            }
            DB::commit();

            /* $reg_ids=DB::table('students')
              ->join('parents', 'students.father_mobile', '=', 'parents.mobile')
              ->select('parents.idFirebase')
              ->where('students.idSchool', Auth::guard('teacher-api')->user()->idSchool)
              ->where('students.idFinancialYear', $this->fys())
              ->get()->pluck('idFirebase')->toArray();
              SendNotificationApi::sendNotification( $reg_ids,"Thoughts : ".$request->thought);

              $reg_ids=DB::table('students')
              ->join('parents', 'students.mother_mobile', '=', 'parents.mobile')
              ->select('parents.idFirebase')
              ->where('students.idSchool', Auth::guard('teacher-api')->user()->idSchool)
              ->where('students.idFinancialYear', $this->fys())
              ->get()->pluck('idFirebase')->toArray();
              SendNotificationApi::sendNotification( $reg_ids,"Thoughts : ".$request->thought); */
        } else {
            foreach ($request->classes as $key => $value) {
                $thought = new \App\WeekThought();
                $thought->fill($request->all());
                $thought->idSchool = Auth::guard('teacher-api')->user()->idSchool;
                $thought->idClass = $value;
                $thought->idFinancialYear = $this->fys();
                $thought->publishDate = today_date();
                $thought->isPublished = 'Y';

                DB::beginTransaction();
                $thought->save();
                if ($request->has('image')) {
                    $nw = 'thought_' . $thought->idThought . '.' . $request->file('image')->getClientOriginalExtension();
                    $request->file('image')->storeAs('public/schools/' . Auth::guard('teacher-api')->user()->idSchool . '/thoughts/', $nw);
                    $thought->image = $nw;
                    $thought->update();
                }
                DB::commit();
                /*  $reg_ids=DB::table('students')
                  ->join('parents', 'students.father_mobile', '=', 'parents.mobile')
                  ->select('parents.idFirebase')
                  ->where('students.idClass', $value)
                  ->where('students.idSchool', Auth::guard('teacher-api')->user()->idSchool)
                  ->where('students.idFinancialYear', $this->fys())
                  ->get()->pluck('idFirebase')->toArray();
                  SendNotificationApi::sendNotification( $reg_ids,"Thoughts : ".$request->thought); $reg_ids=DB::table('students')
                  ->join('parents', 'students.mother_mobile', '=', 'parents.mobile')
                  ->select('parents.idFirebase')
                  ->where('students.idClass', $value)
                  ->where('students.idSchool', Auth::guard('teacher-api')->user()->idSchool)
                  ->where('students.idFinancialYear', $this->fys())
                  ->get()->pluck('idFirebase')->toArray();
                  SendNotificationApi::sendNotification( $reg_ids,"Thoughts : ".$request->thought); */
            }
        }
        return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
    }

    public function deleteThoughts($id) {
        $thought = \App\WeekThought::findOrfail($id);
        $thought->delete();
        return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
    }

    public function editThoughts($id) {
        $thought = \App\WeekThought::findOrfail($id);
        return json_encode($thought);
    }

    public function updateThoughts($id, Request $request) {
        $rules = [
            'source' => 'required',
            'thought' => 'required',
            'image' => 'mimes:jpg,jpeg,png|max:5000',
        ];
        $messages = [
            'idClass.required' => 'Class must be selected',
        ];
        $this->validate($request, $rules, $messages);

        $thought = \App\WeekThought::findOrfail($id);
        $thought->fill($request->all());
        if ($request->has('image')) {
            $nw = 'thought_' . $thought->idThought . '.' . $request->file('image')->getClientOriginalExtension();
            $request->file('image')->storeAs('public/schools/' . Auth::guard('teacher-api')->user()->idSchool . '/thoughts/', $nw);
            $thought->image = $nw;
        }
        if ($thought->update())
            return response()->json(['success' => "SUCCESS", 'message' => $thought->image], 200, ['app-status' => 'success']);
        else
            return response()->json(['success' => "Failed"], 200, ['app-status' => 'success']);
    }

    public function addPNews(Request $request) {
        $rules = [
            'title' => 'required',
            'source' => 'required',
            'category' => 'required',
            'news' => 'required',
            'image' => 'mimes:jpg,jpeg,png|max:2000',
        ];
        if ($request->has('idClass')) {
            $rules += ['idClass' => 'required'];
        }
        $messages = [
            'idClass.required' => 'Class must be selected',
        ];
        $this->validate($request, $rules, $messages);
        if ($request->has('all')) {
            $pnews = new \App\PositiveNews();
            $pnews->fill($request->all());
            $pnews->idSchool = Auth::guard('teacher-api')->user()->idSchool;
            $pnews->idFinancialYear = $this->fys();
            $pnews->publishDate = today_date();
            $pnews->isPublished = 'Y';

            DB::beginTransaction();
            $pnews->save();
            if ($request->has('image')) {
                $nw = 'pnews_' . $pnews->idNews . '.' . $request->file('image')->getClientOriginalExtension();
                $request->file('image')->storeAs('public/schools/' . Auth::guard('teacher-api')->user()->idSchool . '/positivenews/', $nw);
                $pnews->image = $nw;
                $pnews->update();
            }
            DB::commit();
            /* $reg_ids=DB::table('students')
              ->join('parents', 'students.father_mobile', '=', 'parents.mobile')
              ->select('parents.idFirebase')
              ->where('students.idSchool', Auth::guard('teacher-api')->user()->idSchool)
              ->where('students.idFinancialYear', $this->fys())
              ->get()->pluck('idFirebase')->toArray();
              SendNotificationApi::sendNotification( $reg_ids,"News : ".$request->title); $reg_ids=DB::table('students')
              ->join('parents', 'students.mother_mobile', '=', 'parents.mobile')
              ->select('parents.idFirebase')
              ->where('students.idSchool', Auth::guard('teacher-api')->user()->idSchool)
              ->where('students.idFinancialYear', $this->fys())
              ->get()->pluck('idFirebase')->toArray();
              SendNotificationApi::sendNotification( $reg_ids,"News : ".$request->title); */
        } else {
            foreach ($request->classes as $key => $value) {
                $pnews = new \App\PositiveNews();
                $pnews->fill($request->all());
                $pnews->idSchool = Auth::guard('teacher-api')->user()->idSchool;
                $pnews->idClass = $value;
                $pnews->idFinancialYear = $this->fys();
                $pnews->publishDate = today_date();
                $pnews->isPublished = 'Y';

                DB::beginTransaction();
                $pnews->save();
                if ($request->has('image')) {
                    $nw = 'pnews_' . $pnews->idNews . '.' . $request->file('image')->getClientOriginalExtension();
                    $request->file('image')->storeAs('public/schools/' . Auth::guard('teacher-api')->user()->idSchool . '/positivenews/', $nw);
                    $pnews->image = $nw;
                    $pnews->update();
                }
                DB::commit();
                /* $reg_ids=DB::table('students')
                  ->join('parents', 'students.father_mobile', '=', 'parents.mobile')
                  ->select('parents.idFirebase')
                  ->where('students.idClass', $value)
                  ->where('students.idSchool', Auth::guard('teacher-api')->user()->idSchool)
                  ->where('students.idFinancialYear', $this->fys())
                  ->get()->pluck('idFirebase')->toArray();
                  SendNotificationApi::sendNotification( $reg_ids,"News : ".$request->title);$reg_ids=DB::table('students')
                  ->join('parents', 'students.mother_mobile', '=', 'parents.mobile')
                  ->select('parents.idFirebase')
                  ->where('students.idClass', $value)
                  ->where('students.idSchool', Auth::guard('teacher-api')->user()->idSchool)
                  ->where('students.idFinancialYear', $this->fys())
                  ->get()->pluck('idFirebase')->toArray();
                  SendNotificationApi::sendNotification( $reg_ids,"News : ".$request->title); */
            }
        }
        return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
    }

    public function deletePNews($id) {
        $pnews = \App\PositiveNews::findOrfail($id);
        $pnews->delete();
        return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
    }

    public function editPNews($id) {
        $pnews = \App\PositiveNews::findOrfail($id);
        return json_encode($pnews);
    }

    public function updatePNews($id, Request $request) {
        $rules = [
            'title' => 'required',
            'source' => 'required',
            'category' => 'required',
            'news' => 'required',
            'image' => 'mimes:jpg,jpeg,png|max:2000',
        ];
        $this->validate($request, $rules);
        $pnews = \App\PositiveNews::findOrfail($id);
        $pnews->fill($request->all());
        if ($request->has('image')) {
            $nw = 'pnews_' . $pnews->idNews . '.' . $request->file('image')->getClientOriginalExtension();
            $request->file('image')->storeAs('public/schools/' . Auth::guard('teacher-api')->user()->idSchool . '/positivenews/', $nw);
            $pnews->image = $nw;
        }
        if ($pnews->update())
            return response()->json(['success' => "SUCCESS", 'message' => $pnews->image], 200, ['app-status' => 'success']);
        else
            return response()->json(['success' => "Failed"], 200, ['app-status' => 'success']);
    }

    public function addPraticeSet(Request $request) {
        $rules = [
            'idClass' => 'required',
            'subject' => 'required|max:120',
            'message' => 'required|max:500',
            'practiceFile' => 'mimes:doc,jpg,png,jpeg,pdf,docx|max:25000'
        ];
        if ($request->has('schedule')) {
            $rules += ['publishDate' => 'required'];
        }
        if (count($request->sections) == 0) {
            $rules += ['idSection' => 'required'];
        }
        $messages = [
            'idClass.required' => 'Class must be selected.',
            'idSection.required' => 'Section must be selected.'
        ];
        $this->Validate($request, $rules, $messages);
        if (is_array($request->students)) {
            if(count($request->students) > 0){
                foreach ($request->students as $key => $value) {
                    $std = \App\AdmEntry::where('idStudent', '=', $value)->first();
                    $pset = new \App\PracticeSet();
                    $pset->fill($request->all());
                    $pset->idStudent = $value;
                    $pset->idSection = $std->idSection;
                    $pset->idFinancialYear = $this->fys();
                    $pset->idSchool = Auth::guard('teacher-api')->user()->idSchool;

                    $pset->publishDate = today_date();
                    $pset->isPublished = 'Y';

                    DB::beginTransaction();
                    $pset->save();
                    if ($request->hasFile('practiceFile')) {
                        $hw = 'practice_' . $pset->idSet . '.' . $request->file('practiceFile')->getClientOriginalExtension();
                        $request->file('practiceFile')->storeAs('public/schools/' . Auth::guard('teacher-api')->user()->idSchool . '/practiceset/', $hw);
                        $pset->practiceFile = $hw;
                        $pset->update();
                    }
                    $pset->total_student = 1;    
                    $pset->update();
                    DB::commit();
                    /* $reg_ids=DB::table('students')
                    ->join('parents', 'students.father_mobile', '=', 'parents.mobile')
                    ->select('parents.idFirebase')
                    ->where('students.idStudent',  $value)
                    ->where('students.idFinancialYear', $this->fys())
                    ->get()->pluck('idFirebase')->toArray();
                    SendNotificationApi::sendSingleNotification( $reg_ids,"Practice : ".$request->message); $reg_ids=DB::table('students')
                    ->join('parents', 'students.mother_mobile', '=', 'parents.mobile')
                    ->select('parents.idFirebase')
                    ->where('students.idStudent',  $value)
                    ->where('students.idFinancialYear', $this->fys())
                    ->get()->pluck('idFirebase')->toArray();
                    SendNotificationApi::sendSingleNotification( $reg_ids,"Practice : ".$request->message); */
                }
            }
        } else {
            foreach ($request->sections as $key1 => $value1) {
                $pset = new \App\PracticeSet();
                $pset->fill($request->all());
                $pset->idSection = $value1;
                $pset->idFinancialYear = $this->fys();
                $pset->idSchool = Auth::guard('teacher-api')->user()->idSchool;

                $pset->publishDate = today_date();
                $pset->isPublished = 'Y';

                DB::beginTransaction();
                $pset->save();
                if ($request->hasFile('practiceFile')) {
                    $hw = 'practice_' . $pset->idSet . '.' . $request->file('practiceFile')->getClientOriginalExtension();
                    $request->file('practiceFile')->storeAs('public/schools/' . Auth::guard('teacher-api')->user()->idSchool . '/practiceset/', $hw);
                    $pset->practiceFile = $hw;
                    $pset->update();
                }
                DB::commit();
                $totalStudents = DB::table('students')
                        ->where('students.idSection', $value1)
                        ->where('students.idClass', $request->idClass)
                        ->where('students.idFinancialYear',$this->fys())
                        ->count();    
                $pset->total_student = $totalStudents;     
                $pset->update();
                /* $reg_ids=DB::table('students')
                  ->join('parents', 'students.father_mobile', '=', 'parents.mobile')
                  ->select('parents.idFirebase')
                  ->where('students.idSection', $value1)
                  ->where('students.idClass', $request->idClass)
                  ->where('students.idSchool', Auth::guard('teacher-api')->user()->idSchool)
                  ->where('students.idFinancialYear', $this->fys())
                  ->get()->pluck('idFirebase')->toArray();
                  SendNotificationApi::sendNotification( $reg_ids,"Practice : ".$request->message); $reg_ids=DB::table('students')
                  ->join('parents', 'students.mother_mobile', '=', 'parents.mobile')
                  ->select('parents.idFirebase')
                  ->where('students.idSection', $value1)
                  ->where('students.idClass', $request->idClass)
                  ->where('students.idSchool', Auth::guard('teacher-api')->user()->idSchool)
                  ->where('students.idFinancialYear', $this->fys())
                  ->get()->pluck('idFirebase')->toArray();
                  SendNotificationApi::sendNotification( $reg_ids,"Practice : ".$request->message); */
            }
        }
        return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
    }

    public function editPracticeSet($id) {
        $pset = \App\PracticeSet::findOrFail($id);
        $student = \App\AdmEntry::where('idStudent', '=', $pset->idStudent)->get()->pluck('name')->toArray();
        if (sizeof($student) > 0)
            return response()->json(['practice' => $pset,
                        'student' => $student
                            ], 200, ['app-status' => 'success']);
        else
            return response()->json(['practice' => $pset], 200, ['app-status' => 'success']);
    }

    public function deletePracticeSet($id) {
        $pset = \App\PracticeSet::findOrFail($id);
        $pset->delete();
        return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
    }

    public function updatePracticeSet($id, Request $request) {
        $rules = [
            'idClass' => 'required',
            'subject' => 'required|max:120',
            'message' => 'required|max:500',
            'practiceFile' => 'mimes:doc,jpg,png,jpeg,pdf,docx|max:25000'
        ];
        if(is_array($request->sections)){
            if (count($request->sections) == 0) {
                $rules += ['idSection' => 'required'];
            }
        }
        $messages = [
            'idClass.required' => 'Class must be selected.',
            'idSection.required' => 'Section must be selected.'
        ];
        $this->Validate($request, $rules, $messages);
        $pset = \App\PracticeSet::findOrFail($id);
        $pset->fill($request->all());
        if ($request->hasFile('practiceFile')) {
            $hw = 'practice_' . $pset->idSet . '.' . $request->file('practiceFile')->getClientOriginalExtension();
            $request->file('practiceFile')->storeAs('public/schools/' . Auth::guard('teacher-api')->user()->idSchool . '/practiceset/', $hw);
            $pset->practiceFile = $hw;
        }
        if ($pset->update())
            return response()->json(['success' => "SUCCESS", 'message' => $pset->practiceFile], 200, ['app-status' => 'success']);
        else
            return response()->json(['success' => "Failed"], 200, ['app-status' => 'success']);
    }

    public function changePassword(Request $request) {
        if ($request->has('pwd')) {
            $user = Auth::guard('teacher-api')->user();
            $employee = \App\Employee::findOrFail($user->idEmployee);
            $password = $request->pwd;
            $employee->password = bcrypt($password);
            if ($employee->save)
                return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
            else
                return response()->json(['success' => "Failed"], 200, ['app-status' => 'success']);
        } else
            return response()->json(['success' => "Failed"], 200, ['app-status' => 'success']);
    }

    public function changeNumber(Request $request) {
        $user = Auth::guard('teacher-api')->user();
        if (DB::table('user_request')->insert([
                    [
                        'noteRequest' => 'Change Number',
                        'prevNumber' => $user->mobile,
                        'newNumber' => $request->mobile,
                        'created_at' => now()->timestamp,
                        'isResolved' => 0
                    ]
                ]))
            return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
        else
            return response()->json(['success' => "Failed"], 200, ['app-status' => 'success']);
    }

    public function storeNewsletter(Request $request) {

        $rules = [
            'title' => 'required',
            'description' => 'required'
        ];
        if ($request->has('schedule')) {
            $rules += ['publishDate' => 'required'];
        }
        $messages = [
            'idClass.required' => 'Class must be selected',
        ];
        $this->validate($request, $rules, $messages);
        if ($request->has('all')) {
            $newsletter = new \App\NewsLetter();
            $newsletter->fill($request->all());
            $newsletter->idSchool = Auth::guard('teacher-api')->user()->idSchool;
            $newsletter->idFinancialYear = $this->fys();
            if (isset($request->subject)) {
                $newsletter->subjectName = $request->subject;
            }

            if (($request->has('publishDate')) && ($request->publishDate > today_date())) {
                $newsletter->isPublished = 'N';
            } else {
                $newsletter->publishDate = today_date();
                $newsletter->isPublished = 'Y';
            }
            DB::beginTransaction();
            $newsletter->save();
            if ($request->has('image')) {
                $nw = 'newsletter_' . $newsletter->idNewsletter . '.' . $request->file('image')->getClientOriginalExtension();
                $request->file('image')->storeAs('public/schools/' . Auth::guard('teacher-api')->user()->idSchool . '/newsletters/', $nw);
                $newsletter->image = $nw;
                $newsletter->update();
            }
            DB::commit();

            if ($newsletter->isPublished == 'Y') {
                /* $reg_ids = DB::table('students')
                  ->join('parents', 'students.father_mobile', '=', 'parents.mobile')
                  ->select('parents.idFirebase')
                  ->where('students.idSchool', Auth::guard('teacher-api')->user()->idSchool)
                  ->get()->pluck('idFirebase')->toArray();
                  SendNotificationApi::sendNotification($reg_ids, "News : " . $request->title);
                  $reg_ids = DB::table('students')
                  ->join('parents', 'students.mother_mobile', '=', 'parents.mobile')
                  ->select('parents.idFirebase')
                  ->where('students.idSchool', Auth::guard('teacher-api')->user()->idSchool)
                  ->get()->pluck('idFirebase')->toArray();
                  SendNotificationApi::sendNotification($reg_ids, "Newsletter : " . $request->title); */
            }
        } else {
            foreach ($request->classes as $key => $value) {
                $newsletter = new \App\NewsLetter();
                $newsletter->fill($request->all());
                $newsletter->idSchool = Auth::guard('teacher-api')->user()->idSchool;
                $newsletter->idFinancialYear = $this->fys();
                $newsletter->idClass = $value;
                if (isset($request->subject)) {
                    $newsletter->subjectName = $request->subject;
                }
                if (($request->has('publishDate')) && ($request->publishDate > today_date())) {
                    $newsletter->publishDate = $request->publishDate;
                } else {
                    $newsletter->publishDate = today_date();
                    $newsletter->isPublished = 'Y';
                }
                DB::beginTransaction();
                $newsletter->save();
                if ($request->has('image')) {
                    $nw = 'newsletter_' . $newsletter->idNewsletter . '.' . $request->file('image')->getClientOriginalExtension();
                    $request->file('image')->storeAs('public/schools/' . Auth::guard('teacher-api')->user()->idSchool . '/newsletters/', $nw);
                    $newsletter->image = $nw;
                    $newsletter->update();
                }
                DB::commit();
                if ($newsletter->isPublished == 'Y') {
                    /* $reg_ids = DB::table('students')
                      ->join('parents', 'students.father_mobile', '=', 'parents.mobile')
                      ->select('parents.idFirebase')
                      ->where('students.idClass', $value)
                      ->where('students.idSchool', Auth::guard('teacher-api')->user()->idSchool)
                      ->get()->pluck('idFirebase')->toArray();
                      SendNotificationApi::sendNotification($reg_ids, "News : " . $request->title);
                      $reg_ids = DB::table('students')
                      ->join('parents', 'students.mother_mobile', '=', 'parents.mobile')
                      ->select('parents.idFirebase')
                      ->where('students.idClass', $value)
                      ->where('students.idSchool', Auth::guard('teacher-api')->user()->idSchool)
                      ->get()->pluck('idFirebase')->toArray();
                      SendNotificationApi::sendNotification($reg_ids, "Newsletter : " . $request->title); */
                }
            }
        }
        return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
    }

    public function deleteNewsletter($id) {
        $thought = \App\NewsLetter::findOrfail($id);
        $thought->delete();
        return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
    }

    public function editNewsletter($id) {
        $thought = \App\NewsLetter::findOrfail($id);
        return json_encode($thought);
    }

    public function updateNewsletter(Request $request, $id) {
        $rules = [
            'title' => 'required',
            'description' => 'required'
        ];
        $messages = [
            'idClass.required' => 'Class must be selected',
        ];
        $this->validate($request, $rules, $messages);
        $newsletter = \App\NewsLetter::findOrfail($id);
        $newsletter->fill($request->all());
        if (isset($request->subject)) {
            $newsletter->subjectName = $request->subject;
        }
        if ($request->has('image') && $request->image != null) {

            $nw = 'newsletter_' . $newsletter->idNewsletter . '.' . $request->file('image')->getClientOriginalExtension();
            $request->file('image')->storeAs('public/schools/' . Auth::guard('teacher-api')->user()->idSchool . '/newsletters/', $nw);
            $newsletter->image = $nw;
        }
        if ($newsletter->update())
            return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
        else
            return response()->json(['success' => "Failed"], 200, ['app-status' => 'success']);
    }

    function fys() {
        $now = \Carbon\Carbon::now();
        $finyear = \App\FinancialYear::where('idSchool', '=', Auth::guard('teacher-api')->user()->idSchool)->get();
        foreach ($finyear as $fy) {
            $start_date = \Carbon\Carbon::parse($fy->startDate);
            $end_date = \Carbon\Carbon::parse($fy->endDate);
            if ($now->between($start_date, $end_date) == true || $end_date->diffInDays($now) == 0) {
                return $fy->idFinancialYear;
            }
        }
    }

    function fysDate() {
        $now = \Carbon\Carbon::now();
        $finyear = \App\FinancialYear::where('idSchool', '=', Auth::guard('teacher-api')->user()->idSchool)->get();
        foreach ($finyear as $fy) {
            $start_date = \Carbon\Carbon::parse($fy->startDate);
            $end_date = \Carbon\Carbon::parse($fy->endDate);
            if ($now->between($start_date, $end_date) == true || $end_date->diffInDays($now) == 0) {
                return [$fy->startDate . " 00:00:00", $fy->endDate . " 23:59:59"];
            }
        }
    }

    public function getBooks($limit) {
        $school = \App\School::where('idSchool', '=', Auth::guard('teacher-api')->user()->idSchool)->first();
        if ($school->isActive == 'Y') {
            $ebook = \App\ELibrary::where('idSchool', '=', Auth::guard('teacher-api')->user()->idSchool)->skip($limit)
                    ->take($limit + 20)
                    ->get();
            return json_encode($ebook);
        } else {
            return json_encode(array());
        }
    }

    public function viewExamResults($id, $sid, $limit) {
        $school = \App\School::where('idSchool', '=', Auth::guard('teacher-api')->user()->idSchool)->first();
        if ($school->isActive == 'Y') {
            return json_encode(array());
        } else {
            return json_encode(array());
        }
    }

    public function getExams($limit) {
        $school = \App\School::where('idSchool', '=', Auth::guard('teacher-api')->user()->idSchool)->first();
        if ($school->isActive == 'Y') {
            $exams = \App\ExamMcq::where('idFinancialYear', '=', $this->fys())
                    ->where('idSchool', '=', $school->idSchool)
                    ->orderBy('examDate', 'desc')
                    ->skip($limit)
                    ->take(20)
                    ->get();
            return json_encode($exams);
        } else {
            return json_encode(array());
        }
    }

    public function getExamsV2() {
        $school = \App\School::where('idSchool', '=', Auth::guard('teacher-api')->user()->idSchool)->first();
        if ($school->isActive == 'Y') {
            $exams = \App\ExamMcq::where('idFinancialYear', '=', $this->fys())
                    ->where('idSchool', '=', $school->idSchool)
                    ->orderBy('examDate', 'desc')
                    ->paginate();
            return json_encode($exams);
        } else {
            return json_encode(array());
        }
    }

    public function getResponse($idExam, $limit) {
        $school = \App\School::where('idSchool', '=', Auth::guard('teacher-api')->user()->idSchool)->first();
        if ($school->isActive == 'Y') {
            $students = DB::table('exam_mcq_response')
                            ->join('students', 'students.idStudent', 'exam_mcq_response.idStudent')
                            ->join('classes', 'classes.idClass', 'students.idClass')
                            ->join('sections', 'sections.idSection', 'students.idSection')
                            ->select('exam_mcq_response.idStudent', 'exam_mcq_response.idExam', 'exam_mcq_response.isPublished', 'students.ecNo', 'students.firstName', 'classes.className', 'sections.sectionName')
                            ->where('idExam', $idExam)
                            ->groupBy('idStudent')->skip($limit)
                            ->take(20)->get();
            return json_encode($students);
        } else {
            return json_encode(array());
        }
    }

    public function getResponseResult($idExam, $idStudent) {
        $school = \App\School::where('idSchool', '=', Auth::guard('teacher-api')->user()->idSchool)->first();
        if ($school->isActive == 'Y') {
            $response = DB::table('exam_mcq_response')
                            ->join('exam_mcq_questions', 'exam_mcq_response.idQuestion', 'exam_mcq_questions.idQuestions')
                            ->select('exam_mcq_response.*', 'exam_mcq_questions.idQuestions', 'exam_mcq_questions.question', 'exam_mcq_questions.questionType', 'exam_mcq_questions.answerA', 'exam_mcq_questions.answerB', 'exam_mcq_questions.answerC', 'exam_mcq_questions.answerD', 'exam_mcq_questions.answerCorrect', 'exam_mcq_questions.marks as totalMarks')
                            ->where('idStudent', $idStudent)->where('exam_mcq_response.idExam', $idExam)->get();
            return json_encode($response);
        } else {
            return json_encode(array());
        }
    }

    public function saveResponse(Request $request) {
        $school = \App\School::where('idSchool', '=', Auth::guard('teacher-api')->user()->idSchool)->first();
        if ($school->isActive == 'Y') {
            $marksObtained = 0;
            $update = json_decode($request->getContent(), true);
            $idMcq = "";
            $idStudent = "";
            foreach ($update as $key => $value) {

                $marksObtained = $marksObtained + $value['marks'];
                $ques = \App\ExamQuestions::where('idQuestions', $value['idQuestion'])->first();

                if ($ques->marks < $value['marks']) {
                    if ($request->ajax()) {
                        return response()->json(['errors' => "You cannot give more marks than assigned mark."], 422, ['app-status' => 'failed']);
                    }
                }

                $result = DB::table('exam_mcq_response')
                        ->where('idStudent', $value['idStudent'])
                        ->where('idQuestion', $value['idQuestion'])
                        ->update(['marks' => $value['marks'], 'isPublished' => 'Y']);

                $idMcq = $value['idExam'];
                $idStudent = $value['idStudent'];
            }

            $exam = \App\ExamMcq::where('idMcq', '=', $idMcq)->first();
            $mcq = \App\McqResult::where('idStudent', $idStudent)->where('idExam', $idMcq)->first();
            if (isset($mcq->idSchool)) {
                $mcq->marks = $marksObtained;
                $mcq->update();
            } else {
                $student = \App\AdmEntry::where('idStudent', '=', $idStudent)->first();
                $mcq = new \App\McqResult();
                $mcq->idStudent = $student->idStudent;
                $mcq->idFinancialYear = $student->idFinancialYear;
                $mcq->idSchool = $student->idSchool;
                $mcq->idClass = $student->idClass;
                $mcq->idSection = $student->idSection;
                $mcq->idSchool = $student->idSchool;
                $mcq->idExam = $exam->idMcq;
                $mcq->idSubject = $exam->idSubject;
                $mcq->marks = $marksObtained;
                $mcq->save();
            }

            return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
        } else {
            return response()->json(['failed' => "Failed"], 404, ['app-status' => 'success']);
        }
    }

    public function sendNotification(Request $request, $subject) {
        $teacher = \App\Employee::where('idEmployee', '=', Auth::guard('teacher-api')->user()->idEmployee)->first();
        $school = \App\School::where('idSchool', '=', $teacher->idSchool)->first();
        if ($school->isActive == 'Y') {


            if ($request->has('all') || $request->idClass == "All") {
                $reg_ids = DB::table('students')
                                ->join('parents', 'students.father_mobile', '=', 'parents.mobile')
                                ->select('parents.idFirebase')
                                ->where('students.idSchool', Auth::guard('teacher-api')->user()->idSchool)
                                ->where('students.idFinancialYear', $this->fys())
                                ->get()->pluck('idFirebase')->toArray();
                SendNotificationApi::sendNotification($reg_ids, $subject . " : " . $request->title);
                $reg_ids = DB::table('students')
                                ->join('parents', 'students.mother_mobile', '=', 'parents.mobile')
                                ->select('parents.idFirebase')
                                ->where('students.idSchool', Auth::guard('teacher-api')->user()->idSchool)
                                ->where('students.idFinancialYear', $this->fys())
                                ->get()->pluck('idFirebase')->toArray();
                SendNotificationApi::sendNotification($reg_ids, $subject . " : " . $request->title);
            } else if (is_array($request->classes) > 0) {
                foreach ($request->classes as $key => $value) {
                    $reg_ids = DB::table('students')
                                    ->join('parents', 'students.father_mobile', '=', 'parents.mobile')
                                    ->select('parents.idFirebase')
                                    ->where('students.idClass', $value)
                                    ->where('students.idSchool', Auth::guard('teacher-api')->user()->idSchool)
                                    ->where('students.idFinancialYear', $this->fys())
                                    ->get()->pluck('idFirebase')->toArray();
                    SendNotificationApi::sendSingleNotification($reg_ids, $subject . " : " . $request->title);
                    $reg_ids = DB::table('students')
                                    ->join('parents', 'students.mother_mobile', '=', 'parents.mobile')
                                    ->select('parents.idFirebase')
                                    ->where('students.idClass', $value)
                                    ->where('students.idSchool', Auth::guard('teacher-api')->user()->idSchool)
                                    ->where('students.idFinancialYear', $this->fys())
                                    ->get()->pluck('idFirebase')->toArray();
                    SendNotificationApi::sendSingleNotification($reg_ids, $subject . " : " . $request->title);
                }
            } else if(is_array($request->sections)){
                    if (count($request->sections) > 0) {
                    foreach ($request->sections as $key1 => $value1) {
                        $reg_ids = DB::table('students')
                                        ->join('parents', 'students.father_mobile', '=', 'parents.mobile')
                                        ->select('parents.idFirebase')
                                        ->where('students.idSection', $value1)
                                        ->where('students.idClass', $request->idClass)
                                        ->where('students.idFinancialYear', $this->fys())
                                        ->where('students.idSchool', $teacher->idSchool)
                                        ->get()->pluck('idFirebase')->toArray();
                        SendNotificationApi::sendNotification($reg_ids, $subject . " : " . $request->title);
                        $reg_ids = DB::table('students')
                                        ->join('parents', 'students.mother_mobile', '=', 'parents.mobile')
                                        ->select('parents.idFirebase')
                                        ->where('students.idSection', $value1)
                                        ->where('students.idClass', $request->idClass)
                                        ->where('students.idSchool', $teacher->idSchool)
                                        ->where('students.idFinancialYear', $this->fys())
                                        ->get()->pluck('idFirebase')->toArray();
                        SendNotificationApi::sendNotification($reg_ids, $subject . " : " . $request->title);
                    }
                }
            }

            if(is_array($request->students)){
                if (count($request->students) > 0) {
                    foreach ($request->students as $key => $value) {
                        $reg_ids = DB::table('students')
                                        ->join('parents', 'students.father_mobile', '=', 'parents.mobile')
                                        ->select('parents.idFirebase')
                                        ->where('students.idStudent', $value)
                                        ->get()->pluck('idFirebase')->toArray();
                        SendNotificationApi::sendSingleNotification($reg_ids, $subject . " : " . $request->title);
                        $reg_ids = DB::table('students')
                                        ->join('parents', 'students.mother_mobile', '=', 'parents.mobile')
                                        ->select('parents.idFirebase')
                                        ->where('students.idStudent', $value)
                                        ->get()->pluck('idFirebase')->toArray();
                        SendNotificationApi::sendSingleNotification($reg_ids, $subject . " : " . $request->title);
                    }
                }
            }
        
            return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
        } else {
            return response()->json(['success' => "FAILED"], 404, ['app-status' => 'success']);
        }
    }

    public function visitorOverview(Request $request){
        $from_date = Carbon::now();
        $to_date = Carbon::now();
        $isFilterRequired = 1;

        $designation = DB::table('designations')->where('idDesignation',Auth::guard('teacher-api')->user()->idDesignation)->first();
        if($designation == null){
            $data = [
                'inward' => 0,
                'outward' => 0,
                'total' => 0,
                'visitors' => []
            ];
            return json_encode($data); 
        }

        if ($request->get('filter') != "") {
            $from_date = Carbon::createFromFormat('d-m-Y', $request->filter);
            $to_date = Carbon::createFromFormat('d-m-Y', $request->filter);
            $isFilterRequired = 1;
        }else{
            if($designation->designationName == "Guard" || $designation->designationName == "GUARD"){
                $isFilterRequired = 1;
            }
        }

        $total_visitors = \App\Visitor::where('visitors.idSchool', '=', Auth::guard('teacher-api')->user()->idSchool);
                    
                    if ( $isFilterRequired > 0)
                    $total_visitors = $total_visitors->whereBetween('visitors.created_at', [$from_date->format('Y-m-d') . " 00:00:00", $to_date->format('Y-m-d') . " 23:59:59"]);
                    
                    if($designation->designationName == "Guard" || $designation->designationName == "GUARD"){
                        $total_visitors = $total_visitors->count();
                    }else{
                        $total_visitors = $total_visitors->where('idEmployee',Auth::guard('teacher-api')->user()->idEmployee)->count();
                    }
                    

        $in_visitors = \App\Visitor::where('visitors.idSchool', '=', Auth::guard('teacher-api')->user()->idSchool)->whereNull('outTime');
                    if ( $isFilterRequired > 0)
                    $in_visitors = $in_visitors->whereBetween('visitors.created_at', [$from_date->format('Y-m-d') . " 00:00:00", $to_date->format('Y-m-d') . " 23:59:59"]);
                    
                    if($designation->designationName == "Guard" || $designation->designationName == "GUARD"){
                        $in_visitors = $in_visitors->count();
                    }else{
                        $in_visitors = $in_visitors->where('idEmployee',Auth::guard('teacher-api')->user()->idEmployee)->count();
                    }

        $out_visitors = \App\Visitor::where('visitors.idSchool', '=', Auth::guard('teacher-api')->user()->idSchool) ->whereNotNull('outTime');
                    if ( $isFilterRequired > 0)
                    $out_visitors = $out_visitors->whereBetween('visitors.created_at', [$from_date->format('Y-m-d') . " 00:00:00", $to_date->format('Y-m-d') . " 23:59:59"]);
                   
                    if($designation->designationName == "Guard" || $designation->designationName == "GUARD"){
                        $out_visitors = $out_visitors->count();
                    }else{
                        $out_visitors = $out_visitors->where('idEmployee',Auth::guard('teacher-api')->user()->idEmployee)->count();
                    }
    
        $visitors = \App\Visitor::leftJoin('employees', 'visitors.idEmployee', '=', 'employees.idEmployee')
                    ->select('visitors.*','employees.firstName as visitName','employees.middleName as visitMiddleName','employees.lastName as visitLastName')
                    ->where('visitors.idSchool', '=', Auth::guard('teacher-api')->user()->idSchool);
                    if ( $isFilterRequired > 0)
                    $visitors = $visitors->whereBetween('visitors.created_at', [$from_date->format('Y-m-d') . " 00:00:00", $to_date->format('Y-m-d') . " 23:59:59"]);
                    if($designation->designationName == "Guard" || $designation->designationName == "GUARD"){
                        $visitors = $visitors->orderBy('idVisitor','DESC')->paginate();         
                    }else{
                        $visitors = $visitors->where('visitors.idEmployee',Auth::guard('teacher-api')->user()->idEmployee)->orderBy('idVisitor','DESC')->paginate();
                    }       
    
        $data = [
            'inward' => $in_visitors,
            'outward' => $out_visitors,
            'total' => $total_visitors,
            'visitors' => $visitors->items()
        ];

        return json_encode($data);          
    }

    public function getVisitEmployees(Request $request){
        $employee = \App\Employee::select('designationName','departmentName','employees.firstName','employees.middleName','employees.lastName','employees.idEmployee','employees.enrollmentNo')
                    ->leftJoin('departments', 'employees.idDepartment', '=', 'departments.idDepartment')    
                    ->leftJoin('designations', 'employees.idDesignation', '=', 'designations.idDesignation')           
                    ->where('employees.idSchool', '=', Auth::guard('teacher-api')->user()->idSchool)
                    ->where('designationName', '!=', 'Guard')
                    ->where('employees.isActive', '=', 'Y')
                    ->orderBy('employees.idEmployee', 'desc')->get();
        $data = [
            'employees' => $employee
        ];
        return json_encode($data);      
    }

    public function visitorAction(Request $request){
        $rules = [
            'visitor' => 'required',
            'action' => 'required'
        ];
        $this->validate($request, $rules);
        $visitor = \App\Visitor::where('idVisitor', '=', $request->visitor)->first();

        $employee = \App\Employee::where('idEmployee',$visitor->created_by)->first();
        $regId = [];
        if($employee != null)
        array_push($regId,$employee->firebase);
        
        if($request->action == "Verify"){
            $visitor->verified = 'Y';
            $visitor->update();
        }else if($request->action == "reject"){
            $visitor->is_approved = 'N';
            $visitor->remarks = $request->remarks;
            $visitor->outTime = Carbon::now();
            $visitor->update();
            SendNotificationApi::sendSingleNotification($regId,"Visitors - Employee has rejected the visitation of ".$visitor->firstName." with remarks ".$request->remarks);
        }else if($request->action == "approve"){
            $visitor->is_approved = 'Y';
            $visitor->remarks = $request->remarks;
            $visitor->update();
            SendNotificationApi::sendSingleNotification($regId,"Visitors - Employee has approved the visitation of  ".$visitor->firstName." with remarks ".$request->remarks);
        }else{
            if($visitor->is_approved == "P"){
                $visitor->is_approved = 'N';
                $visitor->remarks = "NA";
            }            
            $school = \App\School::where('idSchool', '=', Auth::guard('teacher-api')->user()->idSchool)->first();
            $visitor->outTime = Carbon::now();
            $message = 'Thank you for visiting '.$school->schoolName.' Regards '.$school->sms_regard_text.'.';
            $phone_number = $visitor->mobile;
            $template = \App\SchoolSmsTemplate::where('idSchool', '=', $school->idSchool)->where('template_name', '=', 'visitor')->first();
            if (!empty($template)) {
                $tempid = $template->template_id;
                \App\Http\SendSmsApi::getUserNumber($phone_number, $message, $school, $tempid);
            }
            $visitor->update();
        }

        

        return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
    }

    public function storeVisitor(Request $request){
        $rules = [
            'employee' => 'required',
            'name' => 'required',
            'mobile' => 'required',
            'purpose' => 'required',
            'address' => 'required'
        ];
        $this->validate($request, $rules);
        $school = \App\School::where('idSchool', '=', Auth::guard('teacher-api')->user()->idSchool)->first();
        $otp = mt_rand(100000, 999999);
        $visitor = new \App\Visitor();
        $visitor->idEmployee = $request->employee;
        $visitor->fill($request->all());
        $visitor->otp = $otp;
        $visitor->firstName = $request->name;
        $no = \App\NoGenerator::firstOrCreate(['idSchool' => Auth::guard('teacher-api')->user()->idSchool, 'type' => 'vno']);
        $no->increment('no', 1);
        $v_no = 'V000'. $no->no;
        $visitor->idSchool = Auth::guard('teacher-api')->user()->idSchool;
        $visitor->visitorNo = $v_no;
        $visitor->created_by = Auth::guard('teacher-api')->user()->idEmployee;
        $visitor->save();
        if ($request->hasFile('photo')) {
            $hw = 'visitor_' . $visitor->idVisitor . '.' . $request->file('photo')->getClientOriginalExtension();
            $request->file('photo')->storeAs('public/schools/' . $school->idSchool . '/visitors/', $hw);
            $path = '/home/spdtg/public_html/schoolmis/storage/app/public/schools/' . $school->idSchool . '/visitors/'.$hw;
            $type = pathinfo($path, PATHINFO_EXTENSION);
            $data = file_get_contents($path);
            $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
            $visitor->visitorImage = $base64;
            $visitor->update();
        }        
        $message = 'Your OTP for verifying mobile no is ' . $otp . ' Kindly Share with Receptionist. Regards ' .$school->sms_regard_text .'.';
        $phone_number = $request->mobile;
        $template = \App\SchoolSmsTemplate::where('idSchool', '=', $school->idSchool)->where('template_name', '=', 'mobile_verify_otp')->first();
        if (!empty($template)) {
            $tempid = $template->template_id;
            \App\Http\SendSmsApi::getUserNumber($phone_number, $message, $school, $tempid);
        }

        $employee = \App\Employee::where('idEmployee',$request->employee)->first();
        $regId = [];
        if($employee != null)
        array_push($regId,$employee->firebase);
        SendNotificationApi::sendSingleNotification($regId,"Visitors - ".$visitor->firstName." came to visit you for the purpose of ".$request->purpose);

        return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
    }

}

Copyright © 2021 - 2025 IMMREX7