<?php

namespace App\Http\Controllers\Admin\School;

use App\Http\Controllers\Admin\PageController;
use App\Models\ReportCard;
use App\Models\SchoolClass;
use App\Models\Term;
use App\Services\School\ReportCardService;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\View\View;

class ReportCardController extends PageController
{
    public function __construct(
        private readonly ReportCardService $reportCardService,
    ) {}

    public function index(Request $request): View
    {
        $classId = $request->integer('class_id') ?: null;
        $termId = $request->integer('term_id') ?: Term::query()->where('is_current', true)->value('id');

        $reportCards = ReportCard::query()
            ->with(['student', 'schoolClass', 'term'])
            ->when($classId, fn ($q) => $q->where('class_id', $classId))
            ->when($termId, fn ($q) => $q->where('term_id', $termId))
            ->orderBy('overall_position')
            ->paginate(30)
            ->withQueryString();

        return $this->page('admin.report-cards.index', [
            'crumbTitle' => 'Report Cards',
            'crumbSub' => 'Generate & publish',
            'classes' => SchoolClass::query()->orderBy('name')->get(),
            'terms' => Term::query()->with('academicYear')->orderByDesc('starts_on')->get(),
            'classId' => $classId,
            'termId' => $termId,
            'reportCards' => $reportCards,
        ]);
    }

    public function generate(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'class_id' => ['required', 'exists:classes,id'],
            'term_id' => ['required', 'exists:terms,id'],
        ]);

        $cards = $this->reportCardService->generateForClass(
            $validated['class_id'],
            $validated['term_id'],
        );

        return redirect()
            ->route('school.report-cards.index', $validated)
            ->with('success', "Generated {$cards->count()} report card(s).");
    }

    public function pdf(ReportCard $reportCard): Response
    {
        $data = $this->reportCardService->buildPdfData($reportCard);
        $filename = 'report-card-'.$reportCard->student?->admission_number.'-term-'.$reportCard->term_id.'.pdf';

        return Pdf::loadView('exports.report-card', $data)->download($filename);
    }

    public function publish(ReportCard $reportCard): RedirectResponse
    {
        $this->reportCardService->publish($reportCard);

        return back()->with('success', 'Report card published for parent viewing.');
    }

    public function updateRemarks(Request $request, ReportCard $reportCard): RedirectResponse
    {
        $validated = $request->validate([
            'class_teacher_remarks' => ['nullable', 'string'],
            'head_teacher_remarks' => ['nullable', 'string'],
        ]);

        $reportCard->update($validated);

        return back()->with('success', 'Report card remarks updated.');
    }
}
