<?php

namespace App\Http\Requests;

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

class ProductRequest 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()
    {
        $method = strtolower($this->method());
        switch ($method) {
            case 'post':
                $rules = [
                    'title'                       => 'required',
                    'price'                       => 'required|numeric',
                    'category_id'                 => 'required',
                    'subcategory_id'              => 'required',
                    'storetype_id'                => 'required',
                    'description'                 => 'required',

                ];
                break;
            case 'patch':
                $rules = [
                    'title'                       => 'required',
                    'price'                       => 'required|numeric',
                    'category_id'                 => 'required',
                    'subcategory_id'              => 'required',
                    'storetype_id'                => 'required',
                    'description'                 => 'required',
                ];
                break;
        }

        return $rules;
    }

    public function messages()
    {
        return [
            'category_id.required'                   => 'You must select at least one Category.',
            'subcategory_id.required'                => 'You must select at least one SubCategory.',
            'title.required'                         => 'The Title field is required.',
            'price.required'                         => 'The Price field is required.',
            'storetype_id.required'                  => 'You must select at least one Store Type.',
            'description.required'                   => 'The Description required',

        ];
    }
    /**
     * @param Validator $validator
     */
    protected function failedValidation(Validator $validator)
    {
        $data = [
            'status' => 422,
            'message' => $validator->errors()->first(),
        ];

        if ( request()->is('api*')){
           throw new HttpResponseException( response()->json($data,422) );
        }

        if ($this->ajax()) {
            throw new HttpResponseException(response()->json($data,422));
        } else {
            throw new HttpResponseException(redirect()->back()->withInput()->with('errors', $validator->errors()));
        }
    }
}
