<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

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

    /**
     * Validation Rules
     */
    public function rules(): array
    {
        $userId = $this->route('user')
            ? $this->route('user')->id
            : null;

        $rules = [

            'name' => [
                'required',
                'string',
                'max:255',
            ],

            'email' => [
                'required',
                'email',
                'max:255',
                Rule::unique('users', 'email')->ignore($userId),
            ],

            'phone' => [
                'required',
                'string',
                'max:20',
                Rule::unique('users', 'phone')->ignore($userId),
            ],

            'type' => [
                'required',
                Rule::in(['admin', 'staff']),
            ],

            'status' => [
                'required',
                Rule::in([0, 1]),
            ],

        ];

        if ($this->isMethod('POST')) {

            $rules['password'] = [
                'required',
                'string',
                'min:6',
                'confirmed',
            ];

        } else {

            $rules['password'] = [
                'nullable',
                'string',
                'min:6',
                'confirmed',
            ];

        }

        return $rules;
    }

    /**
     * Validation Messages
     */
    public function messages(): array
    {
        return [

            'name.required' => 'Name is required.',

            'email.required' => 'Email is required.',
            'email.email' => 'Enter a valid email address.',
            'email.unique' => 'Email already exists.',

            'phone.required' => 'Mobile number is required.',
            'phone.unique' => 'Mobile number already exists.',

            'password.required' => 'Password is required.',
            'password.min' => 'Password must be at least 6 characters.',
            'password.confirmed' => 'Passwords do not match.',

            'type.required' => 'User type is required.',

            'status.required' => 'Status is required.',

        ];
    }
}