<?php

namespace App\Http\Controllers;

use App\Models\Attendance;
use App\Models\AttendanceSession;
use App\Models\Enrollment;
use App\Models\TrainingClass;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class AttendanceSessionController extends Controller
{
    public function index(): View
    {
        $sessions = AttendanceSession::with('trainingClass.course')->latest()->get();
        return view('attendance_sessions.index', compact('sessions'));
    }

    public function create(): View
    {
        $classes = TrainingClass::with('course')->latest()->get();
        return view('attendance_sessions.create', compact('classes'));
    }

    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'training_class_id' => 'required|exists:training_classes,id',
            'title' => 'required|max:255',
            'session_date' => 'nullable|date',
        ]);

        AttendanceSession::create($request->only([
            'training_class_id',
            'title',
            'session_date',
            'session_time',
            'note',
        ]));

        return redirect()->route('attendance-sessions.index')
            ->with('success', 'Đã tạo buổi điểm danh thành công.');
    }

    public function show(AttendanceSession $attendanceSession): View
    {
        $attendanceSession->load('trainingClass.course');

        $enrollments = Enrollment::with('student')
            ->where('training_class_id', $attendanceSession->training_class_id)
            ->get();

        $attendances = Attendance::where('attendance_session_id', $attendanceSession->id)
            ->get()
            ->keyBy('enrollment_id');

        return view('attendance_sessions.show', compact(
            'attendanceSession',
            'enrollments',
            'attendances'
        ));
    }

    public function saveAttendance(Request $request, AttendanceSession $attendanceSession): RedirectResponse
    {
        $statuses = $request->input('status', []);
        $notes = $request->input('note', []);

        foreach ($statuses as $enrollmentId => $status) {
            Attendance::updateOrCreate(
                [
                    'attendance_session_id' => $attendanceSession->id,
                    'enrollment_id' => $enrollmentId,
                ],
                [
                    'status' => $status,
                    'note' => $notes[$enrollmentId] ?? null,
                ]
            );
        }

        return redirect()
            ->route('attendance-sessions.show', $attendanceSession->id)
            ->with('success', 'Đã lưu điểm danh thành công.');
    }

    public function edit(AttendanceSession $attendanceSession): View
    {
        $classes = TrainingClass::with('course')->latest()->get();
        return view('attendance_sessions.edit', compact('attendanceSession', 'classes'));
    }

    public function update(Request $request, AttendanceSession $attendanceSession): RedirectResponse
    {
        $request->validate([
            'training_class_id' => 'required|exists:training_classes,id',
            'title' => 'required|max:255',
            'session_date' => 'nullable|date',
        ]);

        $attendanceSession->update($request->only([
            'training_class_id',
            'title',
            'session_date',
            'session_time',
            'note',
        ]));

        return redirect()->route('attendance-sessions.index')
            ->with('success', 'Đã cập nhật buổi điểm danh thành công.');
    }

    public function destroy(AttendanceSession $attendanceSession): RedirectResponse
    {
        $attendanceSession->delete();

        return redirect()->route('attendance-sessions.index')
            ->with('success', 'Đã xóa buổi điểm danh thành công.');
    }
}
