<?php

namespace App\Http\Controllers\Student;

use App\Http\Controllers\Controller;
use App\Models\Mark;
use App\Models\Exam;
use App\Models\Attendance;
use App\Models\Assignment;
use App\Models\FeeInvoice;

class StudentController extends Controller
{
    public function dashboard()
    {
        $student = auth()->user()->student;
        $currentInvoice = $student->currentInvoice;
        $recentMarks = Mark::where('student_id', $student->id)
            ->with(['exam', 'subject'])->latest()->limit(5)->get();
        $upcomingAssignments = Assignment::where('stream_id', $student->stream_id)
            ->where('due_date', '>=', today())->with('subject')->orderBy('due_date')->limit(5)->get();

        return view('student.dashboard', compact('student', 'currentInvoice', 'recentMarks', 'upcomingAssignments'));
    }

    public function results()
    {
        $student = auth()->user()->student;
        $exams = Exam::where('school_id', auth()->user()->school_id)
            ->where('is_published', true)
            ->whereHas('marks', fn($q) => $q->where('student_id', $student->id))
            ->with(['marks' => fn($q) => $q->where('student_id', $student->id)->with('subject')])
            ->latest()->get();

        return view('student.results', compact('student', 'exams'));
    }

    public function fees()
    {
        $student = auth()->user()->student;
        $invoices = FeeInvoice::where('student_id', $student->id)
            ->with(['term', 'payments'])->latest()->get();
        return view('student.fees', compact('student', 'invoices'));
    }

    public function attendance()
    {
        $student = auth()->user()->student;
        $records = Attendance::where('student_id', $student->id)
            ->orderByDesc('date')->paginate(30);
        $summary = Attendance::where('student_id', $student->id)
            ->selectRaw('status, COUNT(*) as count')->groupBy('status')->pluck('count', 'status');
        return view('student.attendance', compact('student', 'records', 'summary'));
    }

    public function assignments()
    {
        $student = auth()->user()->student;
        $assignments = Assignment::where('stream_id', $student->stream_id)
            ->with(['subject', 'teacher.user'])->orderByDesc('due_date')->paginate(15);
        return view('student.assignments', compact('assignments'));
    }
}
