<?php

namespace App\Http\Requests\Eol;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Validation\ValidationException;

class IndividualCertificateRequest extends FormRequest
{

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'file' => 'array|max:5',
            'file.*' => 'file|mimes:pdf|max:5120',
        ];
    }

    /**
     * Get the custom error messages for validation rules.
     *
     * @return array
     */
    public function messages()
    {
        return [
            'file.*.file' => 'Each uploaded document must be a file.',
            'file.*.mimes' => 'Each document must be a PDF.',
            'file.*.max' => 'Each document must not be greater than 5MB.',
            'file.max' => 'You can upload a maximum of 5 files.',
        ];
    }

    /**
     * Handle a failed validation attempt.
     *
     * @param  \Illuminate\Contracts\Validation\Validator  $validator
     * @return void
     *
     * This method will handle the failed validation and return a structured JSON response
     * to be used directly by Dropzone.
     */
    protected function failedValidation(Validator $validator)
    {
        // Format the error messages
        $errors = $validator->errors()->all();

        // Create a custom error response
        $response = [
            'success_message' => '',
            'error_message'   => implode('<br>', $errors), // Join all error messages with a line break
        ];

        // Send the response with a 400 status code
        throw new ValidationException($validator, response()->json($response, 200));
    }
}
