<?php

namespace App\Http\Controllers\Teacher;

use App\Http\Controllers\Admin\PageController;
use App\Http\Controllers\Concerns\AuthorizesTeacherClass;
use App\Models\Attendance;
use App\Models\AttendanceRecord;
use App\Models\SchoolClass;
use App\Models\Term;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Illuminate\View\View;

class AttendanceController extends PageController
{
    use AuthorizesTeacherClass;

    public function index(): View
    {
        $staffId = auth()->user()?->staff_id;

        $sessions = Attendance::query()
            ->with(['schoolClass', 'recordedBy'])
            ->when($staffId, fn ($q) => $q->whereHas('schoolClass', fn ($c) => $c->where('class_teacher_id', $staffId)))
            ->latest('date')
            ->paginate(20);

        return $this->page('teacher.attendance.index', [
            'crumbTitle' => 'Attendance',
            'crumbSub' => 'Daily register',
            'sessions' => $sessions,
        ]);
    }

    public function mark(Request $request): View
    {
        $staffId = auth()->user()?->staff_id;
        $classId = $request->integer('class_id');
        $date = $request->input('date', today()->toDateString());

        $classesQuery = $this->assignedClassesQuery();
        $schoolClass = $classId ? $this->assignedClassesQuery()->with('students')->find($classId) : null;
        $existing = null;

        if ($schoolClass) {
            $existing = Attendance::query()
                ->with('records')
                ->where('class_id', $schoolClass->id)
                ->whereDate('date', $date)
                ->first();
        }

        return $this->page('teacher.attendance.mark', [
            'crumbTitle' => 'Attendance',
            'crumbSub' => 'Mark daily attendance',
            'classes' => $classesQuery->get(),
            'schoolClass' => $schoolClass,
            'date' => $date,
            'existing' => $existing,
            'statuses' => ['present', 'absent', 'late', 'excused'],
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'class_id' => ['required', 'exists:classes,id'],
            'date' => ['required', 'date'],
            'notes' => ['nullable', 'string'],
            'records' => ['required', 'array', 'min:1'],
            'records.*.student_id' => ['required', 'exists:students,id'],
            'records.*.status' => ['required', Rule::in(['present', 'absent', 'late', 'excused'])],
            'records.*.remarks' => ['nullable', 'string', 'max:255'],
        ]);

        $schoolClass = $this->authorizeClassAccess((int) $validated['class_id']);
        $term = Term::query()->where('is_current', true)->first();

        DB::transaction(function () use ($validated, $schoolClass, $term) {
            $attendance = Attendance::query()->updateOrCreate(
                ['class_id' => $schoolClass->id, 'date' => $validated['date']],
                [
                    'recorded_by' => auth()->user()?->staff_id,
                    'term_id' => $term?->id,
                    'status' => 'closed',
                    'notes' => $validated['notes'] ?? null,
                ],
            );

            foreach ($validated['records'] as $row) {
                AttendanceRecord::query()->updateOrCreate(
                    ['attendance_id' => $attendance->id, 'student_id' => $row['student_id']],
                    ['status' => $row['status'], 'remarks' => $row['remarks'] ?? null],
                );
            }
        });

        return $this->redirectWithSuccess('teacher.attendance.index', 'Attendance saved for '.$schoolClass->name.'.');
    }
}
