<?php

namespace App\Rules;

use Closure;
use Illuminate\Support\Facades\DB;
use Illuminate\Contracts\Validation\ValidationRule;

class UniqueEntityDetailField implements ValidationRule
{

    private string $column, $entityCode, $failedMessage;

    public function __construct(array $params)
    {
        $this->column = data_get($params, "column");
        $this->entityCode = data_get($params, "entityCode");
        $this->failedMessage = DB::connection("sys_base")->table("validations")
                ->where("code", "V0003")->first()->failed_message;
    }
    /**
     * Run the validation rule.
     *
     * @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        $records = DB::table("tbl_entity_details")->where([
            ["entity_code", "!=", $this->entityCode],
            ["type", "=", $this->column],
            ["value", "=", $value]
        ])->get();

        if ($records->count() > 0) {
            $fail($this->failedMessage, $attribute);
        }
    }
}
