<?php

namespace Velis\Mvc\Validators\Rules;

use Exception;
use Velis\App;
use Velis\Mvc\Validators\Rules\RuleInterface;

/**
 * Check if the record with the provided value exists in the DB table
 */
class Exists implements RuleInterface
{
    private string $table;

    public function __construct(string $table)
    {
        $this->table = $table;
    }

    public function validate(array $data, string $fieldName): bool
    {
        $sql = "SELECT COUNT(1) FROM {$this->table} WHERE {$fieldName} = :value LIMIT 1";

        try {
            return App::$di['db']->getOne($sql, ['value' => $data[$fieldName]]) == 1;
        } catch (Exception) {
            return false;
        }
    }

    public function getErrorMessage($fieldName): string
    {
        return "{$fieldName} with the value provided doesn't exist";
    }
}
