<?php

namespace App\Http\Requests;

use App\Http\Controllers\Auth\RegisterController;
use Illuminate\Foundation\Http\FormRequest;

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

    protected function getValidatorInstance()
    {
        $v = parent::getValidatorInstance();

        if ($this->method() == 'PUT')
        {
            $requirements = RegisterController::passwordRequirements();
            $v->sometimes('password', $requirements['password'], function($input) {
                return (strlen($input->password) > 0 || strlen($input->password_confirmation) > 0);
            });
        }

        return $v;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        switch ($this->method())
        {
            case 'POST':
                return RegisterController::passwordRequirements();

            case 'PUT':
                $userId = intval($this->segment(3));

                $requirements = RegisterController::passwordRequirements();
                $requirements['email'] = 'required|email|max:255|unique:users,email,' . $userId;
                unset($requirements['password']);

                return $requirements;
        }

        return [];
    }
}