<?php

namespace app\Http\Requests;

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

class ContactRequest extends FormRequest
{
    public function authorize()
    {
        return true; // 確保這裡返回 true
    }

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        return [
            'source' => ['required','regex:/^(official|commercial|mall)$/'],
            'name' => 'required',
            'company' => 'required',
            'phone' => 'required',
            'email' => 'required|email',
            'description' => 'required|max:1000',
        ];
    }

    /**
     * Get custom messages for validator errors.
     */
    public function messages(): array
    {
        return [
            'email.required' => 'E-Mail必填',
            'name.required' => '名稱必填',
            'company.required' => '公司必填',
            'phone.required' => '電話必填',
            'description.required' => '詢問內容必填',
            'email.email' => 'E-Mail格式錯誤',
            'source.regex' => '來源內容不符',
        ];
    }

    /**
     * 處理驗證失敗的情況
     */
    protected function failedValidation(Validator $validator)
    {
        throw new HttpResponseException(response()->json([
            'result' => "failed",
            'message' => $validator->errors(),
        ], 400));
    }
}
