<?php

namespace App\Http\Requests\Admin;

use Illuminate\Foundation\Http\FormRequest;

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

    protected function prepareForValidation(): void
    {
        // Only set default flag_send to 0 if the route is for user update and flag_send is not present
        if (($this->isMethod('put') || $this->isMethod('patch')) && !$this->has('flag_send')) {
            $this->merge([
                'flag_send' => config('constants.FLAG_SEND_DISABLED'),
            ]);
        }
    }

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        $msnv = $this->route('msnv');

        return [
            'card'        => 'nullable|integer|min:0',
            'num_card'    => 'nullable|integer|min:1',
            'role'        => 'nullable|in:' . config('constants.ROLE_MEMBER') . ',' . config('constants.ROLE_ADMIN'),
            'status'      => 'nullable|in:' . config('constants.STATUS_INACTIVE') . ',' . config('constants.STATUS_ACTIVE'),
            'flag_send'   => 'nullable|in:0,1',
            'first_login' => 'nullable|in:' . config('constants.FIRST_LOGIN_FALSE') . ',' . config('constants.FIRST_LOGIN_TRUE'),
            
            // Editable basic info
            'name'        => 'sometimes|required|string|max:255',
            'mail'        => 'sometimes|required|email|unique:user,mail,' . $msnv . ',msnv',
            'departments' => 'sometimes|required|string|in:' . implode(',', config('constants.DEPARTMENTS')),
            'avatar'      => 'nullable|image|max:2048',
        ];
    }
}
