<?php

namespace App\Http\Controllers;
use Barryvdh\DomPDF\Facade\Pdf;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\AttendanceExport;
use Illuminate\Http\Request;
use App\Models\Classe;
use App\Models\Section;
use App\Models\Student;
use App\Models\Attendance;
use App\Models\Staff_attendance;
use App\Models\Staff_member;
use Carbon\Carbon;


class AttendanceController extends Controller
{
        public function index(Request $request)
        {
            $request->validate([
                'class_id' => 'nullable|exists:classes,id',
                'section_id' => 'nullable|exists:sections,id',
                'search' => 'nullable|string|max:255',
            ]);

            $query = Student::query()
                ->with(['classes', 'sections', 'latestAdmission', 'documents'])
                ->where('status', 'active'); // Add this condition
            if ($request->filled('search')) {
                $query->where('student_name', 'like', '%' . $request->search . '%');
            }

            if ($request->filled('class_id')) {
                $query->whereHas('latestAdmission', function ($q) use ($request) {
                    $q->where('class_id', $request->class_id);
                });
            }

            if ($request->filled('section_id')) {
                $query->whereHas('latestAdmission', function ($q) use ($request) {
                    $q->where('section_id', $request->section_id);
                });
            }

            $students = $query->get(); // Get all the students

            // Get attendance for today
            $today = now()->toDateString();
            $attendances = Attendance::where('date', $today)->get()->keyBy('student_id'); // Key by student_id for easy lookup
          //  dd($attendances);
            if ($request->ajax()) {
                return response()->json([
                    'students' => $students,
                ]);
            }

            $totalActiveStudents = Student::where('status', 'active')->count();
            $classes = Classe::all();
            $sections = Section::all();
            $presentCount = $attendances->where('status', 'present')->count();
            $absentCount = $attendances->where('status', 'absent')->count();
            $onLeaveCount = $attendances->where('status', 'leave')->count();
            $halfDayLeaveCount = $attendances->where('status', 'half_day')->count();

            return view('stdAttendance.allStdAttend', compact('students', 'classes', 'sections', 'totalActiveStudents', 'presentCount', 'absentCount', 'onLeaveCount', 'attendances','halfDayLeaveCount'));
        }


            public function store(Request $request)
        {
           
            $request->validate([
                'attendance' => 'required|array',
                'class_id' => 'required|array',
                'section_id' => 'required|array',
                'status.*' => 'in:Present,Absent,Leave,Half Day',
            ]);

            $today = now()->toDateString(); // Get today's date
             
            foreach ($request->attendance as $studentId => $status) {
                $status = strtolower(str_replace(' ', '_', $status)); // Replace space with underscore and convert to lowercase
                // Ensure it matches enum values: present, absent, leave, half_day

                // Check if attendance already exists for the student on today's date
                $attendance = Attendance::where('student_id', $studentId)
                                        ->where('date', $today)
                                        ->first();

                if ($attendance) {
                    // Update the existing record
                    $attendance->update([
                        'status' => $status,
                        'class_id' => $request->class_id[$studentId],
                        'section_id' => $request->section_id[$studentId],
                        'remarks' => $request->remarks[$studentId],
                    ]);
                } else {
                        try {
                            $attendance = Attendance::create([
                                'student_id' => $studentId,
                                'date' => $today,
                                'status' => $status,
                                'class_id' => $request->class_id[$studentId],
                                'section_id' => $request->section_id[$studentId],
                                'remarks' => $request->remarks[$studentId],
                            ]);

                            if ($attendance) {
                                \Log::info("Attendance inserted for student ID: $studentId on $today");
                            } else {
                                \Log::warning("Attendance insert returned null for student ID: $studentId on $today");
                            }
                        } catch (\Exception $e) {
                            \Log::error("Error inserting attendance: " . $e->getMessage());
                        }
                    }

            }

            return redirect()->back()->with('success', 'Attendance submitted successfully.');
        }

        public function show(Request $request, $id)
        {
            // Get student info
            $student = Student::with('latestAdmission', 'documents')->findOrFail($id);

            // Start attendance query
            $attendanceQuery = Attendance::where('student_id', $id);

            // Filter by year and month if provided
            if ($request->filled('year') && $request->filled('month')) {
                $year = $request->year;
                $month = $request->month;

                $attendanceQuery->whereYear('date', $year)
                                ->whereMonth('date', $month);
            }

            // Fetch records
            $attendanceRecords = $attendanceQuery->orderBy('date', 'desc')->get();

            // Count types
            $total = $attendanceRecords->count();
            $presentCount = $attendanceRecords->where('status', 'present')->count();
            $absentCount = $attendanceRecords->where('status', 'absent')->count();
            $leaveCount = $attendanceRecords->where('status', 'leave')->count();
            $halfDayCount = $attendanceRecords->where('status', 'half_day')->count();

            // Percentages
            $presentPercent = $total > 0 ? round(($presentCount / $total) * 100, 1) : 0;
            $absentPercent = $total > 0 ? round(($absentCount / $total) * 100, 1) : 0;
            $leavePercent = $total > 0 ? round(($leaveCount / $total) * 100, 1) : 0;
            $halfDayPercent = $total > 0 ? round(($halfDayCount / $total) * 100, 1) : 0;

            return view('stdAttendance.stdHistory', compact(
                'student',
                'attendanceRecords',
                'presentCount',
                'absentCount',
                'leaveCount',
                'halfDayCount',
                'total',
                'presentPercent',
                'absentPercent',
                'leavePercent',
                'halfDayPercent'
            ));
        }


        public function report(Request $request)
        {
            $classes = Classe::all();
            $sections = Section::all();
        
            $studentsQuery = Student::with('latestAdmission', 'documents');
        
            // Filter by class
            if ($request->filled('class_id')) {
                $studentsQuery->whereHas('latestAdmission', function ($q) use ($request) {
                    $q->where('class_id', $request->class_id);
                });
            }
        
            // Filter by section
            if ($request->filled('section_id')) {
                $studentsQuery->whereHas('latestAdmission', function ($q) use ($request) {
                    $q->where('section_id', $request->section_id);
                });
            }
        
            // Determine the year and month to filter
            if ($request->filled('year') && $request->filled('month')) {
                $filterYear = $request->year;
                $filterMonth = $request->month;
            } else {
                // Default to previous month
                $previousMonth = now()->subMonth();
                $filterYear = $previousMonth->year;
                $filterMonth = $previousMonth->month;
            }

              // Determine filter month and year
            if ($request->filled('year') && $request->filled('month')) {
                $filterYear = $request->year;
                $filterMonth = $request->month;
            } else {
                $previousMonth = now();
                $filterYear = $previousMonth->year;
                $filterMonth = $previousMonth->month;
            }

        
            // Filter attendances by year and month
            $studentsQuery->withCount([
                'attendances as present_count' => function ($query) use ($filterYear, $filterMonth) {
                    $query->whereRaw('YEAR(date) = ?', [$filterYear])
                          ->whereRaw('MONTH(date) = ?', [$filterMonth])
                          ->where('status', 'present');
                },
                'attendances as absent_count' => function ($query) use ($filterYear, $filterMonth) {
                    $query->whereRaw('YEAR(date) = ?', [$filterYear])
                          ->whereRaw('MONTH(date) = ?', [$filterMonth])
                          ->where('status', 'absent');
                },
                'attendances as leave_count' => function ($query) use ($filterYear, $filterMonth) {
                    $query->whereRaw('YEAR(date) = ?', [$filterYear])
                          ->whereRaw('MONTH(date) = ?', [$filterMonth])
                          ->where('status', 'leave');
                },
                'attendances as half_day_count' => function ($query) use ($filterYear, $filterMonth) {
                    $query->whereRaw('YEAR(date) = ?', [$filterYear])
                          ->whereRaw('MONTH(date) = ?', [$filterMonth])
                          ->where('status', 'half_day');
                },
                
                
            ]);
            
            $studentsQuery->withCount([
                // ... other counts
                'attendances as total_attendance_count' => function ($query) use ($filterYear, $filterMonth) {
                    $query->whereRaw('YEAR(date) = ?', [$filterYear])
                          ->whereRaw('MONTH(date) = ?', [$filterMonth]);
                },
            ]);
        
            $students = $studentsQuery->paginate(40);
            // $students = $students->paginate(10);
             
            // ✅ Excel Export
            if ($request->get('export') === 'excel') {
                return Excel::download(new AttendanceExport($students), 'attendance_report.xlsx');
            }

            // ✅ PDF Export
            if ($request->get('export') === 'pdf') {
                $pdf = Pdf::loadView('stdAttendance.attendPdf', compact('students'));
                return $pdf->download('attendance_report.pdf');
            }


        
            return view('stdAttendance.stdAttendReport', compact(
                'classes', 'sections', 'students'
            ));
        }
        
        public function staffAttend(Request $request)
        {
            $today = now()->toDateString();
            
            // Get all staff members with today's attendance (if exists)
            $query = Staff_member::with([
                'attendances' => function ($q) use ($today) {
                    $q->where('date', $today)
                    ->where('status', 'active');
                }
            ])
            ->where('status', 'active') // Filters Staff_member table itself
            ->latest();


            if ($request->filled('search')) {
                $search = $request->search;
                $query->where(function ($q) use ($search) {
                    $q->where('full_name', 'like', "%{$search}%")
                    ->orWhere('registration_no', 'like', "%{$search}%")
                    ->orWhere('cnic', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%");
                });
            }

            $staffMembers = $query->get();

            
             // Count types
             $total = Staff_member::where('status','active')->count();

             $presentCount = $staffMembers->where('status', 'present')->count();
             $absentCount = $staffMembers->where('status', 'absent')->count();
             $leaveCount = $staffMembers->where('status', 'leave')->count();
             $halfDayCount = $staffMembers->where('status', 'half_day')->count();
 
             // Percentages
             $presentPercent = $total > 0 ? round(($presentCount / $total) * 100, 1) : 0;
             $absentPercent = $total > 0 ? round(($absentCount / $total) * 100, 1) : 0;
             $leavePercent = $total > 0 ? round(($leaveCount / $total) * 100, 1) : 0;
             $halfDayPercent = $total > 0 ? round(($halfDayCount / $total) * 100, 1) : 0;

            // Count today's check-ins
            $checkInCount =staff_attendance::whereDate('date', $today)
            ->whereNotNull('check_in')
            ->count();

            // Count today's check-outs
            $checkOutCount = staff_attendance::whereDate('date', $today)
            ->whereNotNull('check_out')
            ->count();

            
            // Prepare data for the view
            $formData = [
                'check_in' => [],
                'check_out' => [],
                'attendance' => []
            ];

            foreach ($staffMembers as $staff) {
                $attendance = $staff->attendances->first(); // Get today's attendance if exists
                
                $staffId = $staff->id;
                
                    // Convert to 24-hour format for time inputs
                $formData['check_in'][$staffId] = $attendance && $attendance->check_in 
                ? Carbon::parse($attendance->check_in)->format('H:i') // Changed to 24-hour format
                : null;

                $formData['check_out'][$staffId] = $attendance && $attendance->check_out 
                ? Carbon::parse($attendance->check_out)->format('H:i') // Changed to 24-hour format
                : null;

                
                $formData['attendance'][$staffId] = $attendance ? $attendance->status : 'Present'; // Default status
            }
 

            return view('staffAttendance.staffAttend', [
                'staffAttend'     => $staffMembers,
                'formData'        => $formData,
                'presentCount'    => $presentCount,
                'absentCount'     => $absentCount,
                'leaveCount'      => $leaveCount,
                'halfDayCount'    => $halfDayCount,
                'presentPercent'  => $presentPercent,
                'absentPercent'   => $absentPercent,
                'leavePercent'    => $leavePercent,
                'halfDayPercent'  => $halfDayPercent,
                'checkInCount'     => $checkInCount,
                'checkOutCount'    => $checkOutCount,
                'total'           => $total,
            ]);
            
        }
        public function staffAttendStore(Request $request)
        {

            $today = now()->toDateString();
            $statuses = $request->attendance ?? [];
            $checkIns = $request->check_in ?? [];
            $checkOuts = $request->check_out ?? [];
        
            foreach ($statuses as $staffId => $status) {
                  // Process check-in time
                $checkIn = null;
                if (!empty($checkIns[$staffId])) {
                    $checkIn = $today . ' ' . $checkIns[$staffId] . ':00'; // Combine date with time
                    $checkIn = Carbon::parse($checkIn); // Convert to Carbon datetime object
                }

                // Process check-out time
                $checkOut = null;
                if (!empty($checkOuts[$staffId])) {
                    $checkOut = $today . ' ' . $checkOuts[$staffId] . ':00'; // Combine date with time
                    $checkOut = Carbon::parse($checkOut); // Convert to Carbon datetime object
                }
                
                staff_attendance::updateOrCreate(
                    [
                        'staff_id' => $staffId,
                        'date' => $today,
                    ],
                    [
                        'check_in' => $checkIn,
                        'check_out' => $checkOut,
                        'status' => $status,
                    ]
                );
            }
        
            return redirect()->back()->with('success', 'Attendance updated successfully.');
        }

        

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

             // Get student info
             $staff = Staff_member::with('attendances')->findOrFail($id);

             // Start attendance query
             $attendanceQuery = staff_attendance::where('staff_id', $id);
 
             // Filter by year and month if provided
             if ($request->filled('year') && $request->filled('month')) {
                 $year = $request->year;
                 $month = $request->month;
 
                 $attendanceQuery->whereYear('date', $year)
                                 ->whereMonth('date', $month);
             }
 
             // Fetch records
             $attendanceRecords = $attendanceQuery->orderBy('date', 'desc')->get();
 
             // Count types
             $total = $attendanceRecords->count();
             $presentCount = $attendanceRecords->where('status', 'present')->count();
             $absentCount = $attendanceRecords->where('status', 'absent')->count();
             $leaveCount = $attendanceRecords->where('status', 'leave')->count();
             $halfDayCount = $attendanceRecords->where('status', 'half_day')->count();
 
             // Percentages
             $presentPercent = $total > 0 ? round(($presentCount / $total) * 100, 1) : 0;
             $absentPercent = $total > 0 ? round(($absentCount / $total) * 100, 1) : 0;
             $leavePercent = $total > 0 ? round(($leaveCount / $total) * 100, 1) : 0;
             $halfDayPercent = $total > 0 ? round(($halfDayCount / $total) * 100, 1) : 0;
 

             return view('staffAttendance.staffHistory', compact(
                 'staff',
                 'attendanceRecords',
                 'presentCount',
                 'absentCount',
                 'leaveCount',
                 'halfDayCount',
                 'total',
                 'presentPercent',
                 'absentPercent',
                 'leavePercent',
                 'halfDayPercent'
             ));


             
            // return view('staffAttendance.staffAttendanceReport', compact('staffAttend'));
    
        }

        public function staff_report(Request $request)
        {
            $classes = Classe::all();
            $sections = Section::all();
        
            $studentsQuery = Student::with('latestAdmission', 'documents');
        
            // Filter by class
            if ($request->filled('class_id')) {
                $studentsQuery->whereHas('latestAdmission', function ($q) use ($request) {
                    $q->where('class_id', $request->class_id);
                });
            }
        
            // Filter by section
            if ($request->filled('section_id')) {
                $studentsQuery->whereHas('latestAdmission', function ($q) use ($request) {
                    $q->where('section_id', $request->section_id);
                });
            }
        
            // Determine the year and month to filter
            if ($request->filled('year') && $request->filled('month')) {
                $filterYear = $request->year;
                $filterMonth = $request->month;
            } else {
                // Default to previous month
                $previousMonth = now()->subMonth();
                $filterYear = $previousMonth->year;
                $filterMonth = $previousMonth->month;
            }

              // Determine filter month and year
            if ($request->filled('year') && $request->filled('month')) {
                $filterYear = $request->year;
                $filterMonth = $request->month;
            } else {
                $previousMonth = now();
                $filterYear = $previousMonth->year;
                $filterMonth = $previousMonth->month;
            }

        
            // Filter attendances by year and month
            $studentsQuery->withCount([
                'attendances as present_count' => function ($query) use ($filterYear, $filterMonth) {
                    $query->whereRaw('YEAR(date) = ?', [$filterYear])
                          ->whereRaw('MONTH(date) = ?', [$filterMonth])
                          ->where('status', 'present');
                },
                'attendances as absent_count' => function ($query) use ($filterYear, $filterMonth) {
                    $query->whereRaw('YEAR(date) = ?', [$filterYear])
                          ->whereRaw('MONTH(date) = ?', [$filterMonth])
                          ->where('status', 'absent');
                },
                'attendances as leave_count' => function ($query) use ($filterYear, $filterMonth) {
                    $query->whereRaw('YEAR(date) = ?', [$filterYear])
                          ->whereRaw('MONTH(date) = ?', [$filterMonth])
                          ->where('status', 'leave');
                },
                'attendances as half_day_count' => function ($query) use ($filterYear, $filterMonth) {
                    $query->whereRaw('YEAR(date) = ?', [$filterYear])
                          ->whereRaw('MONTH(date) = ?', [$filterMonth])
                          ->where('status', 'half_day');
                },
                
                
            ]);
            
            $studentsQuery->withCount([
                // ... other counts
                'attendances as total_attendance_count' => function ($query) use ($filterYear, $filterMonth) {
                    $query->whereRaw('YEAR(date) = ?', [$filterYear])
                          ->whereRaw('MONTH(date) = ?', [$filterMonth]);
                },
            ]);
        
            $students = $studentsQuery->paginate(40);
            // $students = $students->paginate(10);
             
            // ✅ Excel Export
            if ($request->get('export') === 'excel') {
                return Excel::download(new AttendanceExport($students), 'attendance_report.xlsx');
            }

            // ✅ PDF Export
            if ($request->get('export') === 'pdf') {
                $pdf = Pdf::loadView('stdAttendance.attendPdf', compact('students'));
                return $pdf->download('attendance_report.pdf');
            }


        
            return view('stdAttendance.stdAttendReport', compact(
                'classes', 'sections', 'students'
            ));
        }
        
        


     
    
}
