<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Illuminate\Contracts\Encryption\DecryptException;

use EF;

class AccountVerificationRule implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    private $validation_list;
  
    public function __construct($array)
    {
        $this->validation_list = $array;
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */

    public function passes($attribute, $value)
    {

        try 
        {
            $validation_list = $this->getValidationList();  

           
            $compund_list = EF::getVoucherType();


            $debit_subhead  = 0;
            $credit_subhead = 0;

            $match = 0;
            $index = 0;

            foreach ($validation_list['amount'] as $rows) 
            {
                // FOR MULTIPLE DEBIT
                if($compund_list[1] == $validation_list['compound_type'])
                {
                    $credit_subhead =  $validation_list['credit_subhead'][0];
                    $debit_subhead  = $validation_list['debit_subhead'][$index];

                }  
                // FOR MULTIPLE CREDIT
                else if($compund_list[2] == $validation_list['compound_type'])
                {
                    $debit_subhead = $validation_list['debit_subhead'][0];
                    $credit_subhead = $validation_list['credit_subhead'][$index];

                }
                else
                {
                     $credit_subhead = $validation_list['credit_subhead'][$index];
                     $debit_subhead  = $validation_list['debit_subhead'][$index];
                }


                if(decrypt($debit_subhead) == decrypt($credit_subhead))
                {
                    $match++;
                }

                $index++;


            } 


            if($match == 0)
            {
                return true;
            }


            $this->setMessage('Debit and credit subhead are same.');

        } 
        catch (DecryptException $e) 
        {
            //
        }

        return false;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    
    // SET ERROR MESSAGE
    public function setMessage($msg)
    {
        $this->message = $msg;
    }

    public function message()
    {
        return $this->message;
    }

    public function getValidationList()
    {
        return $this->validation_list;
    }

}
