<?php

namespace App\Http\Rules\User;

use Auth;
use App\Models\ContractObligation;
use App\Models\EntitySignature;

use App\Http\Helpers\Hasher;

use Illuminate\Contracts\Validation\Rule;

class ContractObligationEntitySignatureCheck implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */

    private $contract_obligation_id;

    public function __construct($contract_obligation_id = '')
    {
        $this->contract_obligation_id = $contract_obligation_id;
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $this->attribute = $attribute;
        $value = is_array($value) ? $value : [$value];

        $entity_signature_id = Hasher::decode('entity_signatures', $value[0]);
        $entity_signature = EntitySignature::find($entity_signature_id);

        if ($entity_signature) {
            if ($entity_signature->type == config('constants.entity.signature.master_key')) {
                return true;
            }
        }

        $contract_obligation_id = Hasher::decode('contract_obligations', $this->contract_obligation_id);
        $contract_obligation = ContractObligation::find($contract_obligation_id);

        if ($contract_obligation->contract_entity_list[0]->entity_signature_hash_id == $value[0]) {
            return true;
        }

        return false;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return config('error_code.obligation_signature_error');
    }
}
