<?php

namespace App\Http\Rules\User;

use Auth;
use App\Models\ContractTemplateObligation;

use App\Http\Helpers\Hasher;

use Illuminate\Contracts\Validation\Rule;

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

    private $depend_template_contract_obligation_id;

    public function __construct($depend_template_contract_obligation_id = '')
    {
        $this->depend_template_contract_obligation_id = $depend_template_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];

        if ($value[0] != $this->depend_template_contract_obligation_id[0]) {
            $contract_template_obligation_id = Hasher::decode('contract_template_obligations', $value[0]);
            $contract_template_obligation = ContractTemplateObligation::find($contract_template_obligation_id);
            $depend_contract_template_obligation_id = Hasher::decode('contract_template_obligations', $this->depend_template_contract_obligation_id[0]);
            $depend_contract_template_obligation = ContractTemplateObligation::find($depend_contract_template_obligation_id);

            $contract_template_obligation_dependency_structure = $contract_template_obligation->getContractTemplateObligationDependencyStructure([$contract_template_obligation->hash_id]);

            if (in_array($depend_contract_template_obligation->hash_id, $contract_template_obligation_dependency_structure)) {
                // return false;
            }

            return true;
        }

        return false;
    }

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