<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use App\Rules\ExistRule;
use App\Allowance;
use EF;

class AllowanceRequest 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()
    {
        EF::errorMessage('Required form validation.');
        
        $current_path = url()->current();

        if($current_path === url('allowancecommit'))
        {
           return $this->storeAllowance();
        }

        elseif($current_path === url('allowanceupdate'))
        {
            return $this->updateAllowance();
        }
    }


     public function storeAllowance()
    {

        $this->type = ucfirst($this->input('type'));

        $allowance = new Allowance;

        $types = $allowance->getDistinctAllowance('type',['type']);

        $types = array_map('current', $types->toArray());

        $types = implode(',',$types);



        $common_validation = [

             'allowance_type'                =>  'required|In:'.$types,
             'title'                         =>  'required|min:1|max:50',
             'percentage'                    =>  'gte:0|lte:100',
             'amount'                        =>  'nullable|integer|gt:0',
             
        ];

        if($this->input('allowance_type') === "Other")
        {
            $common_validation['allowance_type']          = 'nullable';
            $common_validation                           += ['type' => 'required|NotIn:'.$types];
        }

        return $common_validation;
    }


     public function updateAllowance()
    {
      
        return [

             'allowance'                     =>  ['required', new ExistRule('allowances','id')],
             'type'                          =>  'required|min:3|max:50',
             'title'                         =>  'required|min:1|max:50',
             'amount'                        =>  'nullable|integer|gt:0',
             'percentage'                    =>  'gte:0|lte:100',
            
            
             
             
          
        ];
    }
}
