<?php

namespace App\Http\Controllers\StudentPortal;

use App\Http\Controllers\Controller;
use App\Http\Controllers\StudentPortal\Concerns\ResolvesStudent;
use App\Models\StudentAttendance;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\View\View;

class AttendanceController extends Controller
{
    use ResolvesStudent;

    public function index(Request $request): View
    {
        $student = $this->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 = StudentAttendance::where('student_id', $student->id)
            ->whereBetween('date', [$start, $end])->orderBy('date')->get();

        $summary = ['present' => 0, 'absent' => 0, 'leave' => 0, 'late' => 0, 'half_day' => 0];
        foreach ($records as $r) {
            $summary[$r->status] = ($summary[$r->status] ?? 0) + 1;
        }

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