<?php
namespace App\Http\Controllers;
use App\Models\Certificate;
use App\Models\Enrollment;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;
class CertificateController extends Controller {
    public function index(): View {
        $certificates = Certificate::with(['enrollment.student','enrollment.trainingClass.course'])->latest()->get();
        return view('certificates.index', compact('certificates'));
    }
    public function create(): View {
        $enrollments = Enrollment::with(['student','trainingClass.course'])->latest()->get();
        return view('certificates.create', compact('enrollments'));
    }
    public function store(Request $request): RedirectResponse {
        $request->validate([
            'enrollment_id'=>'required|exists:enrollments,id|unique:certificates,enrollment_id',
            'certificate_no'=>'required|max:100|unique:certificates,certificate_no',
            'issued_date'=>'nullable|date',
            'status'=>'required|max:100',
        ]);
        Certificate::create($request->only(['enrollment_id','certificate_no','issued_date','status','note']));
        return redirect()->route('certificates.index')->with('success','Đã cấp giấy chứng nhận thành công.');
    }
    public function show(Certificate $certificate): View {
        $certificate->load(['enrollment.student','enrollment.trainingClass.course']);
        return view('certificates.show', compact('certificate'));
    }
    public function edit(Certificate $certificate): View {
        $enrollments = Enrollment::with(['student','trainingClass.course'])->latest()->get();
        return view('certificates.edit', compact('certificate','enrollments'));
    }
    public function update(Request $request, Certificate $certificate): RedirectResponse {
        $request->validate([
            'enrollment_id'=>'required|exists:enrollments,id|unique:certificates,enrollment_id,'.$certificate->id,
            'certificate_no'=>'required|max:100|unique:certificates,certificate_no,'.$certificate->id,
            'issued_date'=>'nullable|date',
            'status'=>'required|max:100',
        ]);
        $certificate->update($request->only(['enrollment_id','certificate_no','issued_date','status','note']));
        return redirect()->route('certificates.index')->with('success','Đã cập nhật giấy chứng nhận thành công.');
    }
    public function destroy(Certificate $certificate): RedirectResponse {
        $certificate->delete();
        return redirect()->route('certificates.index')->with('success','Đã xóa giấy chứng nhận thành công.');
    }
}
