<?php

namespace App\Http\Controllers\ParentPortal;

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

class DashboardController extends Controller
{
    use ResolvesFamily;

    public function index(): View
    {
        $family = $this->family();
        $children = $family->students()->with(['schoolClass', 'section'])->get();

        $monthStart = Carbon::today()->startOfMonth();
        $monthEnd = Carbon::today()->endOfMonth();

        $childCards = $children->map(function ($student) use ($monthStart, $monthEnd) {
            $att = StudentAttendance::where('student_id', $student->id)
                ->whereBetween('date', [$monthStart, $monthEnd])->get();
            $present = $att->whereIn('status', ['present', 'late', 'half_day'])->count();
            $total = $att->count();

            return [
                'student' => $student,
                'attendance_pct' => $total ? round($present / $total * 100) : null,
            ];
        });

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

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

        return view('parent.dashboard', compact('family', 'childCards', 'challans', 'outstanding', 'notices'));
    }
}
