<?php

namespace App\Http\Controllers\Attendance;

use PDF;
use App\Constants\Status;

use App\Constants\Settings;
use Illuminate\Http\Request;
use App\Models\Academic\Group;
use App\Models\Academic\Shift;
use App\Models\Academic\Section;
use App\Models\Student\StudentInfo;
use App\Http\Controllers\Controller;
use Maatwebsite\Excel\Facades\Excel;
use App\Models\Academic\AcademicYear;
use App\Models\Academic\ClassSection;
use App\Models\Academic\StudentClass;
use App\Exports\StudentAttendanceExport;
use App\Models\Attendance\StudentAttendance;

class StudentAttendanceController extends Controller
{
    public function index()
    {
        return view('pages.student_attendance.index');
    }

    public function create()
    {
        $data['student_class_id'] = '';
        $data['section_id'] = '';
        $data['group_id'] = '';
        $data['shift_id'] = '';
        // if(auth()->user()->user_type == 'teacher'){
        //     $teacherClass = ClassSection::where('class_teacher_id',auth()->user()->id)->first();
        //     $data['teacherClass'] = $teacherClass;
        //     $data['studentClasses'] = StudentClass::where('id',$teacherClass->student_class_id)->pluck('class_name','id');
        //     $data['section_id'] = $teacherClass->section_id;
        //     $data['student_class_id'] = $teacherClass->student_class_id;
        // }else{
        //     $data['studentClasses'] = StudentClass::pluck('class_name','id');
        // }
        $data['studentClasses'] = StudentClass::pluck('class_name','id');
        $data['sections'] = Section::pluck('section_name','id');
        $data['groups'] = Group::pluck('group_name','id');
        $data['shifts'] = Shift::pluck('shift_name','id');
        return view('pages.student_attendance.create', $data);
    }

    public function myStudent()
    {
        $teacherClass = ClassSection::where('class_teacher_id', auth()->user()->id)->first();
        $data['teacherClass'] = $teacherClass;
        $data['studentClasses'] = StudentClass::where('id',$teacherClass?->student_class_id)->pluck('class_name','id');
        $data['section_id'] = $teacherClass?->section_id;
        $data['student_class_id'] = $teacherClass?->student_class_id;
        $data['student_class_name'] = $teacherClass?->studentClass->class_name;
        $data['section_name'] = $teacherClass?->section?->section_name;
        
        if(!empty($teacherClass)) {
            $students = StudentInfo::query();

            if (!empty($data['student_class_id'])) {
                $students->where('student_class_id', $data['student_class_id']);
            }

            if (!empty($data['section_id'])) {
                $students->where('section_id', $data['section_id']);
            }

            if (!empty($data['group_id'])) {
                $students->where('group_id', $data['group_id']);
            }

            if (!empty($data['shift_id'])) {
                $students->where('shift_id', $data['shift_id']);
            }

            $students->where('status', '!=', Status::GRADUATED);

            $data['attendance_date'] = date('Y-m-d');

            // Retrieve the attendance records for the specified date
            if (!empty($data['attendance_date'])) {
                $date = date_convertion($data['attendance_date'],'Y-m-d');
                $students->with(['attendance' => function ($query) use ($date) {
                    $query->whereDate('punch_date', $date);
                }]);
            }

            // Retrieve all students
            $data['students'] = $students->orderBy('class_roll', 'ASC')->get();
        }else{
            $data['students'] = [];
        };
        return view('pages.student_attendance.my-student', $data);
    }

    public function search(Request $request){
        $data['student_class_id'] = $request->student_class_id;
        $data['section_id'] = $request->section_id;
        $data['group_id'] = $request->group_id;
        $data['shift_id'] = $request->shift_id;

        $students = StudentInfo::query();

        if ($request->has('student_class_id')) {
            $students->where('student_class_id', $request->input('student_class_id'));
        }

        if (!empty($data['section_id'])) {
            $students->where('section_id', $request->input('section_id'));
        }

        if (!empty($data['group_id'])) {
            $students->where('group_id', $request->input('group_id'));
        }

        if (!empty($data['shift_id'])) {
            $students->where('shift_id', $request->input('shift_id'));
        }

        $data['attendance_date'] = $request->input('attendance_date');

        // Retrieve the attendance records for the specified date
        if ($request->has('attendance_date')) {
            $date = date_convertion($request->input('attendance_date'),'Y-m-d');
            $students->with(['attendance' => function ($query) use ($date) {
                $query->whereDate('punch_date', $date);
            }]);
        }

        // Retrieve all students
        $data['students'] = $students->orderBy('class_roll', 'ASC')->get();
        $data['studentClasses'] = StudentClass::pluck('class_name','id');
        $data['sections'] = Section::pluck('section_name','id');
        $data['groups'] = Group::pluck('group_name','id');
        $data['shifts'] = Shift::pluck('shift_name','id');

        $data['teacherClass'] = ClassSection::where('class_teacher_id',auth()->user()->id)->first();

        return view('pages.student_attendance.create', $data);
    }

    public function store(Request $request)
    {

        if(empty($request->student_id)) {
            return redirect()->back()->with('error', 'Please select at least one student.');
        }

        foreach ($request->student_id as $key => $req_student_id) {
            $student_info = StudentInfo::where('id',$req_student_id)->first();
            $branch_id = $student_info->branch_id;
            $shift_id = $student_info->shift_id;
            $student_class_id = $student_info->student_class_id;
            $section_id = $student_info->group_id;
            $attendance_status = $request->attendance_status[$req_student_id];
            $note = $request->note[$req_student_id] ?? '';

            $attendance_data = [
                'student_id' => $req_student_id,
                'student_class_id' => $student_class_id,
                'branch_id' => $branch_id,
                'shift_id' => $shift_id,
                'section_id' => $section_id,
                'punch_date' => date('Y-m-d'),
                'day_status' => $attendance_status,
                'note' => $note,
                'created_by' => auth()->user()->id,
            ];

            if($attendance_status=="P"){
                $attendance_data['is_present'] = 1;
                $attendance_data['is_absent'] = 0;
                $attendance_data['is_late'] = 0;
            }elseif($attendance_status=="A"){
                $attendance_data['is_present'] = 0;
                $attendance_data['is_absent'] = 1;
                $attendance_data['is_late'] = 0;
            }elseif($attendance_status=="L"){
                $attendance_data['is_present'] = 0;
                $attendance_data['is_absent'] = 0;
                $attendance_data['is_late'] = 1;
            }

            // $date = "2024-11-10";
            // $checkAttendance = StudentAttendance::where('student_id',$req_student_id)->where('punch_date', $date)->first();
            // if(!empty($checkAttendance)){
            //     StudentAttendance::where('student_id',$req_student_id)->where('punch_date', $date)->update($attendance_data);
            //     $data = StudentAttendance::where('student_id',$req_student_id)->where('punch_date', $date)->first();
            // }else{
            //     $data = StudentAttendance::create($attendance_data);
            // }

            $checkAttendance = StudentAttendance::where('student_id',$req_student_id)->where('punch_date', date('Y-m-d'))->first();
            if(!empty($checkAttendance)){
                StudentAttendance::where('student_id',$req_student_id)->where('punch_date', date('Y-m-d'))->update($attendance_data);
                $data = StudentAttendance::where('student_id',$req_student_id)->where('punch_date', date('Y-m-d'))->first();
            }else{
                $data = StudentAttendance::create($attendance_data);
                $in_time_sms = get_setting_value(Settings::IN_TIME_SMS) ? get_setting_value(Settings::IN_TIME_SMS) : '0';
                if($in_time_sms == '1'){
                    // send in time student attendance sms
                }
            }
        }
        return redirect()->route('student_attendance.create')->with('success','Attendance Successfully Saved');
    }


    public function store_old(Request $request)
    {
        $student_info = StudentInfo::where('id',$request->student_id)->first();

        $attendance_status = $request->attendance_status;

        $attendance_data = [
            'student_id' => $request->student_id,
            'branch_id' => 1,
            'shift_id' => $request->shift_id,
            'punch_date' => date('Y-m-d'),
            'day_status' => $attendance_status,
            'created_by' => auth()->user()->id,
        ];

        if($attendance_status=="P"){
            $attendance_data['is_present'] = 1;
            $attendance_data['is_absent'] = 0;
        }elseif($attendance_status=="A"){
            $attendance_data['is_present'] = 0;
            $attendance_data['is_absent'] = 1;
        }

        $checkAttendance = StudentAttendance::where('student_id',$request->student_id)->where('punch_date', date('Y-m-d'))->first();

        if(!empty($checkAttendance)){
            StudentAttendance::where('student_id',$request->student_id)->where('punch_date', date('Y-m-d'))->update($attendance_data);
            $data = StudentAttendance::where('student_id',$request->student_id)->where('punch_date', date('Y-m-d'))->first();
        }else{
            $data = StudentAttendance::create($attendance_data);
        }
        return response()->json(['success' => true, 'data' => $data, 'message' => $student_info->first_name.'\'s Attendance Success']);
    }

    public function attendanceReport(){
        $data['student_class_id'] = '';
        $data['section_id'] = '';
        $data['group_id'] = '';
        $data['shift_id'] = '';
        $data['month'] = date('m');
        $data['year'] = date("Y");

        if(auth()->user()->user_type == 'teacher'){
            $teacherClass = ClassSection::where('class_teacher_id',auth()->user()->id)->first();
            $data['teacherClass'] = $teacherClass;
            $data['studentClasses'] = $teacherClass ? StudentClass::where('id',$teacherClass?->student_class_id)->pluck('class_name','id') : [] ;
        }else{
            $data['studentClasses'] = StudentClass::pluck('class_name','id');
        }

        $data['sections'] = Section::pluck('section_name','id');
        $data['groups'] = Group::pluck('group_name','id');
        $data['shifts'] = Shift::pluck('shift_name','id');
        $data['academicYears'] = AcademicYear::orderBy('year','desc')->get();
        
        return view('pages.student_attendance.report', $data);
    }

    public function searchAttendance(Request $request)
    {

        $student_class_id = $request->student_class_id;
        $section_id = $request->section_id;
        $group_id = $request->group_id;
        $shift_id = $request->shift_id;
        $month = $request->month;
        $year = $request->year;
        $totalDays = cal_days_in_month(CAL_GREGORIAN, $month, $year);
        $from_date = "$year-$month-01";
        $to_date = "$year-$month-$totalDays";

        $students = StudentInfo::query();

        if ($request->has('student_class_id')) {
            $students->where('student_class_id', $request->input('student_class_id'));
        }

        if (!empty($section_id)) {
            $students->where('section_id', $request->input('section_id'));
        }

        if (!empty($group_id)) {
            $students->where('group_id', $request->input('group_id'));
        }

        if (!empty($shift_id)) {
            $students->where('shift_id', $request->input('shift_id'));
        }

        $students->where('status', '!=', Status::GRADUATED);

        $students->with(['attendances' => function ($query) use ($from_date, $to_date) {
            $query->whereBetween('punch_date', [$from_date, $to_date]);
        }]);

        $students = $students->get();

        if(auth()->user()->user_type == 'teacher'){
            $teacherClass = ClassSection::where('class_teacher_id',auth()->user()->id)->first();
            $studentClasses = $teacherClass ? StudentClass::where('id',$teacherClass?->student_class_id)->pluck('class_name','id') : [] ;
        }else{
            $studentClasses = StudentClass::pluck('class_name','id');
        }

        $sections = Section::pluck('section_name','id');
        $groups = Group::pluck('group_name','id');
        $shifts = Shift::pluck('shift_name','id');
        $academicYears = AcademicYear::orderBy('year','desc')->get();
        

        return view('pages.student_attendance.report', compact('studentClasses', 'sections', 'groups', 'shifts', 'academicYears', 'students', 'student_class_id', 'section_id', 'group_id', 'shift_id', 'month', 'year', 'totalDays', 'from_date', 'to_date'));
    }

    public function attendanceReportDateToDate(){
        $dates = null;
        $student_class_id = '';
        $section_id = '';
        $group_id = '';
        $shift_id = '';
        $studentClasses = StudentClass::pluck('class_name','id');
        $sections = Section::pluck('section_name','id');
        $groups = Group::pluck('group_name','id');
        $shifts = Shift::pluck('shift_name','id');
        return view('pages.student_attendance.dateToDateReport',compact('dates', 'studentClasses', 'sections', 'groups', 'shifts', 'student_class_id', 'section_id', 'group_id', 'shift_id'));
    }

    public function attendanceReportDateToDateSearch(Request $request){
        $extra_col = null;
        if(!empty($request->extra_col)){
            $extra_col = implode(',',$request->extra_col);
        }

        $student_class_id = $request->student_class_id;
        $shift_id = $request->shift_id;
        $daterange = $request->date;
        $query = $request->date;
        $from = substr($daterange, 0,-13);
        $from = strtotime($from);
        $from = date("Y-m-d", $from);

        $to = substr($daterange, -10);
        $to = strtotime($to);
        $to = date("Y-m-d", $to);
        $className = StudentClass::findOrFail($student_class_id)->class_name;
        $shiftName = Shift::findOrFail($shift_id)->shift_name;
        $student_id = null;
        $studentAttendance = StudentAttendance::query();
        if($request->has('student_class_id')) {
            $studentAttendance->where('student_class_id', $request->input('student_class_id'));
        }
        if(!empty($shift_id)) {
            $studentAttendance->where('shift_id', $request->input('shift_id'));
        }
        if(!empty($from) && !empty($to)) {
            $studentAttendance->whereBetween('punch_date', [$from, $to]);
        }
        if(!empty($student_id)){
            $studentAttendance->with(['studentInfo' => function ($query) use ($student_id){
                $query->where('student_id_no', $student_id);
            }]);
        }else{
            $studentAttendance->with(['studentInfo' ]);
        }
        $attendances = $studentAttendance
        ->select('student_id') // Select the unique column ->orderBy('class_roll','asc')
        ->selectRaw('SUM(student_attendances.is_present = 1) as totoal_present')
        ->selectRaw('SUM(student_attendances.is_absent = 1) as totoal_absent')
        ->selectRaw('SUM(student_attendances.is_late = 1) as totoal_late')
        ->selectRaw('COUNT(*) as punch_date')
        ->groupBy('student_id') // Group by the unique column
        ->get();
        $studentClasses = StudentClass::pluck('class_name','id');
        $shifts = Shift::pluck('shift_name','id');

        if($request->export == 'export'){
            $extra_col = ['Student ID','Roll','Name','Total Present','Total Absent','Total Late','Total Holiday','Total Half Day','Total Days'];
            return Excel::download(new StudentAttendanceExport($attendances, $className, $shiftName, $extra_col), 'attendance.xlsx');
            // return Excel::download(new StudentAttendanceExport($attendances, $extra_col), 'attendance.xlsx');
        }elseif($request->pdf === 'pdf'){
            // $data['attendances'] = $attendances;
            // $data['shiftName'] = $shiftName;
            // $date['className'] = $className;
            // dd($date);
            $customPaper = array(0,0,595,842);
            $pdf = PDF::loadView('pages.student_attendance.pdf.attendance_pdf', compact('attendances','className','shiftName','from','to','extra_col'))->setPaper($customPaper);
            // return $pdf->download('student_attendance.pdf');
            return $pdf->stream();
        }
        return view('pages.student_attendance.dateToDateReport',compact('studentClasses','daterange','shifts','from','to','attendances','student_class_id','shift_id'));
    }

    

    public function attendanceExport() {
        $attendances = StudentAttendance::all();
        return Excel::download(new StudentAttendanceExport($attendances), 'attendance.xlsx');
    }
}
