<?php

namespace App\Http\Controllers\ParentPortal;

use App\Http\Controllers\Controller;
use App\Http\Controllers\ParentPortal\Concerns\ResolvesFamily;
use App\Models\Student;
use App\Models\StudentAttendance;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\View\View;

class AttendanceController extends Controller
{
    use ResolvesFamily;

    public function index(Request $request): View
    {
        $family = $this->family();
        $children = $family->students;

        $studentId = $request->integer('student_id') ?: $children->first()?->id;
        $student = $studentId ? Student::find($studentId) : null;
        if ($student) {
            $this->authorizeChild($student);
        }

        $month = $request->input('month', Carbon::today()->format('Y-m'));
        [$y, $m] = array_pad(explode('-', $month), 2, null);
        $start = Carbon::createFromDate((int) $y, (int) $m, 1)->startOfMonth();
        $end = (clone $start)->endOfMonth();

        $records = collect();
        $summary = ['present' => 0, 'absent' => 0, 'leave' => 0, 'late' => 0, 'half_day' => 0];

        if ($student) {
            $records = StudentAttendance::where('student_id', $student->id)
                ->whereBetween('date', [$start, $end])->orderBy('date')->get();
            foreach ($records as $r) {
                $summary[$r->status] = ($summary[$r->status] ?? 0) + 1;
            }
        }

        return view('parent.attendance', compact('children', 'student', 'records', 'summary', 'month'));
    }
}
