<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Ujian;
use App\Services\LaporanService;
use Illuminate\Http\Request;

class LaporanController extends Controller
{
    public function __construct(protected LaporanService $laporanService) {}

    public function exportNilaiExcel(Request $request)
    {
        $request->validate(['ujian_id' => 'required|exists:ujian,id']);
        $ujian = Ujian::findOrFail($request->ujian_id);
        return $this->laporanService->exportNilaiExcel($ujian);
    }

    public function exportNilaiPdf(Request $request)
    {
        $request->validate(['ujian_id' => 'required|exists:ujian,id']);
        $ujian = Ujian::findOrFail($request->ujian_id);
        return $this->laporanService->exportNilaiPdf($ujian);
    }

    public function rekapUjian(Request $request)
    {
        $request->validate(['tahun_ajaran_id' => 'required|exists:tahun_ajaran,id']);

        $data = Ujian::where('tahun_ajaran_id', $request->tahun_ajaran_id)
            ->with(['mataPelajaran', 'kelas', 'guruMengajar.guru'])
            ->withCount(['pengerjaanUjian', 'nilaiUjian'])
            ->when($request->jenis, fn($q) => $q->where('jenis', $request->jenis))
            ->orderBy('tanggal_mulai')
            ->get();

        return response()->json(['success' => true, 'data' => $data]);
    }
}
