<?php

namespace App\Http\Controllers;

use App\Models\CertificateTemplate;
use App\Models\Student;
use App\Support\BranchContext;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;
use Illuminate\Validation\Rule;
use Illuminate\View\View;

class CertificateController extends Controller implements HasMiddleware
{
    public static function middleware(): array
    {
        return [
            new Middleware('can:certificates.view', only: ['index', 'generate']),
            new Middleware('can:certificates.generate', only: ['create', 'store', 'edit', 'update', 'destroy', 'print']),
        ];
    }

    public function index(): View
    {
        $templates = CertificateTemplate::orderBy('name')->get();

        return view('certificates.index', compact('templates'));
    }

    public function create(): View
    {
        return view('certificates.create', ['template' => new CertificateTemplate()]);
    }

    public function store(Request $request, BranchContext $context): RedirectResponse
    {
        $data = $this->validateData($request);
        $data['branch_id'] = $context->currentId() ?? auth()->user()->branch_id ?? \App\Models\Branch::min('id');
        CertificateTemplate::create($data);

        return redirect()->route('certificates.index')->with('success', 'Template created.');
    }

    public function edit(CertificateTemplate $certificate): View
    {
        return view('certificates.edit', ['template' => $certificate]);
    }

    public function update(Request $request, CertificateTemplate $certificate): RedirectResponse
    {
        $certificate->update($this->validateData($request));

        return redirect()->route('certificates.index')->with('success', 'Template updated.');
    }

    public function destroy(CertificateTemplate $certificate): RedirectResponse
    {
        $certificate->delete();

        return redirect()->route('certificates.index')->with('success', 'Template deleted.');
    }

    /** Generation form (template + student); on submit produce the PDF. */
    public function generate(Request $request)
    {
        $templates = CertificateTemplate::active()->orderBy('name')->get();
        $students = Student::active()->orderBy('name')->get();

        return view('certificates.generate', [
            'templates' => $templates,
            'students' => $students,
            'selectedStudent' => $request->integer('student_id') ?: null,
        ]);
    }

    public function print(Request $request)
    {
        $data = $request->validate([
            'template_id' => ['required', 'exists:certificate_templates,id'],
            'student_id' => ['required', 'exists:students,id'],
        ]);

        $template = CertificateTemplate::findOrFail($data['template_id']);
        $student = Student::with(['family', 'schoolClass', 'section', 'academicSession', 'branch'])->findOrFail($data['student_id']);

        $html = $template->render($student);

        $pdf = Pdf::loadView('certificates.pdf', [
            'school' => $student->branch?->name ?? config('app.name'),
            'title' => CertificateTemplate::TYPES[$template->type] ?? $template->name,
            'body' => $html,
        ])->setPaper('a4');

        return $pdf->stream('certificate-'.$student->admission_number.'.pdf');
    }

    private function validateData(Request $request): array
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:150'],
            'type' => ['required', Rule::in(array_keys(CertificateTemplate::TYPES))],
            'body' => ['required', 'string'],
            'is_active' => ['nullable', 'boolean'],
        ]);
        $data['is_active'] = (bool) ($data['is_active'] ?? false);

        return $data;
    }
}
