<?php

namespace App\Http\Requests\User;

use Illuminate\Foundation\Http\FormRequest;
use Hash;

class UserUpdateRequest 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()
    {
        $userId = $this->route()->parameter('user');

        $rules = [
            'first_name' => 'nullable|string|max:255',
            'last_name' => 'nullable|string|max:255',
            'email' => 'required|string|email|max:255|unique:users,email,' . $userId,

            'roles' => 'nullable|exists:roles,id',
            'phone_number' => 'nullable|regex:/^(\+?\d{1,4}[\s\-]?)?(\(?\d{3}\)?[\s\-]?)?\d{3}[\s\-]?\d{4}$/',
            'company_name' => 'nullable|string|max:255',
            'billing_address' => 'nullable|string|max:255',
            'billing_city' => 'nullable|string|max:255',
            'billing_zip' => 'nullable|string|max:10',
            'billing_country' => 'nullable|exists:countries,id',
            'billing_state' => 'nullable|exists:states,id',
        ];

        if ($this->input('password')) {
            $rules['password'] = 'required|string|min:6';
            $this->request->set('password', Hash::make($this->input('password')));
        } else {
            $this->request->remove('password');
        }

        return $rules;
    }
}
