<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use DB;
use Illuminate\Contracts\Encryption\DecryptException;
use App\AssignAllowance;

class AllowanceVerificationRule implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
     private $parms;
     

     private $message;
    public function __construct($parms)
    {
        $this->parms = $parms;
       
        $this->message = 'Required Validation.';
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        
        try 
        {

            $scale_id             = decrypt($this->parms['scale']);

            $allowance_id         = decrypt($this->parms['allowance']);

            $designation_id       = decrypt($this->parms['designation']);

           

            $condition = ['scale_id' => $scale_id, 'designation_id' => $designation_id, 'allowance_id' => $allowance_id, 'is_recycle' => '0' ];

            
            // THIS SECTION WORK ONLY FOR THE UPDATE ASSIGN ALLOWANCE CASE
            if(isset($this->parms['id']))
            {
                $current_id           = decrypt($this->parms['id']);

                $current_assign = $this->getAssignAllowanceById($current_id);

                if(isset($current_assign->id))
                {
                    if($current_assign->scale_id == $scale_id && $current_assign->allowance_id == $allowance_id && $current_assign->designation_id == $designation_id)
                    {
                        return true;
                    }
                }
            }

            


            if($scale_id == 0 && $designation_id == 0)
            {
                $this->setMessage("Select Scale or Designation to assign Allowance");
                return false;
            }
            if($this->allowanceVerification($condition) > 0)
            {
                        $this->setMessage('Allowance already assigned');

                        return false;
            }


        } 
        catch (DecryptException $e) 
        {
            //
        }

        return true;
    }

       
    /**
     * Get the validation error message.
     *
     * @return string
     */


    // SET ERROR MESSAGE
    public function setMessage($msg)
    {
        $this->message = $msg;
    }

    // RETURN CUSTOM ERROR MESSAGE
    public function message()
    {
        return $this->message;
    }
    public function allowanceVerification($condition)
    {
            return DB::table('assign_allowances')->where($condition)->count();
    }

    public function getAssignAllowanceById($id)
    {
            $assign_allowances = new AssignAllowance;

            return $assign_allowances->getAssignAllowanceById($id);
    }
}
