<?php

namespace App\Http\Controllers\StudentPortal;

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

class DashboardController extends Controller
{
    use ResolvesStudent;

    public function index(): View
    {
        $student = $this->student()->load(['schoolClass', 'section', 'family']);

        $att = StudentAttendance::where('student_id', $student->id)
            ->whereBetween('date', [Carbon::today()->startOfMonth(), Carbon::today()->endOfMonth()])->get();
        $attendancePct = $att->count() ? round($att->whereIn('status', ['present', 'late', 'half_day'])->count() / $att->count() * 100) : null;

        $outstanding = FeeChallan::where('family_id', $student->family_id)
            ->whereIn('status', ['unpaid', 'partial'])->get()->sum(fn ($c) => $c->balance);

        $homeworkCount = $student->class_id
            ? LearningMaterial::published()->where('class_id', $student->class_id)->where('type', 'homework')->count()
            : 0;

        $notices = Notice::where('branch_id', $student->branch_id)
            ->published()->forAudience('students')->latest('published_at')->latest('id')->limit(5)->get();

        return view('student.dashboard', compact('student', 'attendancePct', 'outstanding', 'homeworkCount', 'notices'));
    }
}
