<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Barryvdh\DomPDF\Facade\Pdf;
use App\Models\Certificate;
use Illuminate\Support\Facades\Validator;


class CertificateController extends Controller
{
    public function generate(Request $request)
    {
        // Define custom error messages
        $messages = [
            'name.required' => 'Name field is required.',
            'name.string' => 'Name must be a string.',
            'name.max' => 'Name may not be greater than 255 characters.',
            'email.required' => 'Email field is required.',
            'email.email' => 'Emailmust be a valid email address.',
            'email.max' => 'Emaill may not be greater than 255 characters.',
            'email.unique' => 'Email has already downloaded the file .',
            'phone.required' => 'Phone number field is required.',
            'phone.string' => 'Phone number must be a string.',
            'phone.max' => 'Phone number may not be greater than 15 characters.',
            'department.required' => 'Department field is required.',
            'department.string' => 'Department must be a string.',
            'department.max' => 'Department may not be greater than 255 characters.',
            'college_name.required' => 'College name field is required.',
            'college_name.string' => 'College name must be a string.',
            'college_name.max' => 'College name may not be greater than 255 characters.',
        ];

        // Validate the request
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255|unique:certificates,email',
            'phone' => 'required|string|max:15',
            'department' => 'required|string|max:255',
            'college_name' => 'required|string|max:255',
        ], $messages);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        // Store data in the database
        $certificate = new Certificate();
        $certificate->name = $request->input('name');
        $certificate->email = $request->input('email');
        $certificate->phone = $request->input('phone');
        $certificate->dob = $request->input('dob') ?? null;
        $certificate->department = $request->input('department');
        $certificate->college_name = $request->input('college_name');
        $certificate->address = $request->input('address') ?? null;
        $certificate->save();

        // Generate PDF
        $pdf = Pdf::loadView('certificates.certificate', [
            'name' => $request->input('name'),
            'course' => $request->input('course'),
            'date' => $request->input('date'),
        ])
            ->setPaper([0, 0, 800, 600]); // Width: 800px, Height: 600px

        // Return PDF file as a response
        return $pdf->download('certificate.pdf');
    }
}
