<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\{
    User,
    Attendance
};
use Illuminate\Support\Facades\Auth;


class AttendanceController extends Controller
{
    //

    public function __construct()
    {
        $this->middleware('auth');
    }

    public function showForm()
    {
        return view('attendance.mark');
    }



    // Show the attendance form (for supervisor or student)
    public function showAttendanceForm(Request $request)
{
    $attendances = collect();  // Default to an empty collection to avoid null errors
    $students = null;

    // If the user is a supervisor
    if (auth()->user()->role == 'supervisor') {
        // Get all students assigned to the supervisor
        $students = auth()->user()->students;


        // If a student is selected by the supervisor, fetch their attendance
        if ($request->has('student_id')) {
            $attendances = Attendance::where('student_id', $request->student_id)
                                     ->orderBy('created_at', 'desc')
                                     ->take(3)->get();
        }
    }

    // If the user is a student, fetch their attendance automatically
    if (auth()->user()->role == 'student') {
        $attendances = Attendance::where('student_id', auth()->user()->id)
                                 ->orderBy('created_at', 'desc')
                                 ->take(3)->get();
    }

    return view('attendance.mark', compact('students', 'attendances'));
}


    // Mark attendance for the selected student
    public function markAttendance(Request $request)
    {
        $student = User::find($request->student_id);

        // Prevent marking attendance if no supervisor is assigned
        if (!$student || !$student->supervisor_id) {
            return redirect()->back()
                ->with('error', 'Student cannot mark attendance without an assigned supervisor.');
        }

        $attendance = new Attendance();
        $attendance->student_id = $student->id;
        $attendance->supervisor_id = $student->supervisor_id;
        $attendance->date = now();
        $attendance->lesson_learned = $request->lesson_learned;
        $attendance->diagram_path = $request->diagram_path;
        $attendance->save();

        return redirect()->route('attendance.mark')->with('success', 'Attendance marked successfully');
    }





    public function store(Request $request)
    {
        $request->validate([
            'date' => 'required|date',
            'lesson_learned' => 'required|string|max:1000',
            'diagram' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048'
        ]);

        if (Auth::user()->role == 'supervisor') {
            // Supervisor submits for a selected student
            $data = [
                'student_id' => $request->student_id, // Get student_id from form
                'supervisor_id' => Auth::id(),
                'date' => $request->date,
                'lesson_learned' => $request->lesson_learned,
            ];
        } else {
            // Student submits for themselves
            $data = [
                'student_id' => Auth::id(),
                'supervisor_id' => Auth::user()->supervisor_id, // Their supervisor's ID
                'date' => $request->date,
                'lesson_learned' => $request->lesson_learned,
            ];
        }

        if ($request->hasFile('diagram')) {
            $path = $request->file('diagram')->store('diagrams', 'public');
            $data['diagram_path'] = $path;
        }

        Attendance::create($data);

        return redirect()->back()->with('success', 'Attendance marked successfully!');
    }


    public function records(Request $request)
{
    $students = User::where('role', 'student')->get();
    $selectedStudent = null;
    $calendar = [];
    $presentDays = [];

    if ($request->has('student_id')) {
        $selectedStudent = User::find($request->student_id);

        $calendar = $this->generateCalendar(now()->year, now()->month);

        $presentDays = Attendance::where('student_id', $selectedStudent->id)
            ->whereMonth('date', now()->month)
            ->pluck('date')
            ->map(fn($d) => \Carbon\Carbon::parse($d)->toDateString())
            ->toArray();
    }

    return view('supervisors.attendance.calendar', compact('students', 'selectedStudent', 'calendar', 'presentDays'));
}

public function update(Request $request, $studentId)
{
    Attendance::where('student_id', $studentId)
        ->whereMonth('date', now()->month)
        ->delete();

    if ($request->has('attendance_dates')) {
        foreach ($request->attendance_dates as $date) {
            Attendance::create([
                'student_id' => $studentId,
                'supervisor_id' => auth()->id(),
                'date' => $date,
                'lesson_learned' => 'Marked from calendar view'
            ]);
        }
    }

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

private function generateCalendar($year, $month)
{
    $cal = new \DateTimeImmutable("$year-$month-01");
    $weeks = [];
    $start = $cal->modify('last monday of previous month');
    for ($i = 0; $i < 6; $i++) {
        $week = [];
        for ($d = 0; $d < 7; $d++) {
            $day = $start->modify("+".($i * 7 + $d)." days");
            $week[] = [
                'date' => $day,
                'in_month' => $day->format('n') == $month
            ];
        }
        $weeks[] = $week;
    }
    return $weeks;
}

}
