<?php

namespace App\Http\Requests\Eol;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;

class ConsolidatedCertificateRequest 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 [
            'certificate' => 'required|file|mimes:pdf|max:5120',
            'file' => [
                'required',
                'file',
                'mimes:csv,xls,xlsx,txt',
                'max:5000',
            ],
        ];
    }

    /**
     * Get the custom error messages for validation rules.
     *
     * @return array
     */
    public function messages()
    {
        return [
            'certificate.required' => 'A certificate file is required.',
            'certificate.file' => 'The uploaded certificate must be a valid file.',
            'certificate.mimes' => 'The certificate must be a PDF file.',
            'certificate.max' => 'The certificate must not be larger than 5MB.',
            'file.required' => 'Please upload an assets file.',
            'file.mimes' => 'Only CSV, Excel (.xls, .xlsx) files are allowed for assets.',
            'file.max' => 'The file size must not exceed 5MB for assets.',
        ];
    }

    /**
     * Handle additional validations for content-type and file MIME type.
     *
     * @return \Illuminate\Http\Response|null
     */
    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            $file = $this->file('file');
            $mimeType = $file->getMimeType();

            // Define allowed MIME types for CSV and Excel files.
            $allowedMimeTypes = [
                'text/csv', // MIME type for CSV files.
                'text/plain', // MIME type for .csv files.
                'application/vnd.ms-excel', // MIME type for .xls files.
                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // MIME type for .xlsx files.
            ];

            // Check if the MIME type matches the allowed types.
            if (!in_array($mimeType, $allowedMimeTypes)) {
                $validator->errors()->add('file', 'Invalid Content-Type. Only CSV and Excel files are allowed for assets.');
            }

            // Define allowed file extensions.
            $allowedExtensions = ['csv', 'xls', 'xlsx'];

            // Check the file extension.
            $extension = strtolower($file->getClientOriginalExtension());
            if (!in_array($extension, $allowedExtensions)) {
                $validator->errors()->add('file', 'Invalid file extension. Only .csv, .xls and .xlsx files are allowed for assets.');
            }
        });
    }

    /**
     * Format the validation error response before returning it.
     *
     * @param  \Illuminate\Contracts\Validation\Validator  $validator
     * @return void
     */
    protected function failedValidation(Validator $validator)
    {
        // Get the validation errors.
        $errors = $validator->errors()->getMessages();

        // Render the error view and pass the errors to it.
        $view['errors'] = view('assets.partials.upload-validation-errors', compact('errors'))->render();

        // Throw a custom exception with the formatted error response.
        throw new HttpResponseException(
            response()->json($view, 200)
        );
    }
}
