<?php

/*
*

 ______   _______  __   __  _______  _______  ___   _______ 
|      | |       ||  |_|  ||       ||       ||   | |       |
|  _    ||    ___||       ||   _   ||_     _||   | |       |
| | |   ||   |___ |       ||  | |  |  |   |  |   | |       |
| |_|   ||    ___||       ||  |_|  |  |   |  |   | |      _|
|       ||   |___ | ||_|| ||       |  |   |  |   | |     |_ 
|______| |_______||_|   |_||_______|  |___|  |___| |_______|
 _______  __   __  _______                                  
|       ||  |_|  ||       |                                 
|       ||       ||  _____|                                 
|       ||       || |_____                                  
|      _||       ||_____  |                                 
|     |_ | ||_|| | _____| |                                 
|_______||_|   |_||_______|                                                   
                                              
                                           
*
*
*/

/**
 * Demotic CMS is a fork of ImpressPages.
 * AUTHOR: Demotic
 * @package Demotic
 */

namespace Demotic\Form\Validator;


class Unique extends \Demotic\Form\Validator
{

    /**
     * Constructor
     *
     * @param array $data
     * @param string $errorMessage
     * @throws \Demotic\Exception
     */
    public function __construct($data, $errorMessage = null)
    {
        if (empty($data['table'])) {
            throw new \Demotic\Exception('Unique validator expect table name');
        }
        parent::__construct($data, $errorMessage);
    }

    /**
     * Get error
     *
     * @param array $values
     * @param int $valueKey
     * @param $environment
     * @return string|bool
     */
    public function getError($values, $valueKey, $environment)
    {
        if (!array_key_exists($valueKey, $values)) {
            return false;
        }

        if ($values[$valueKey] == '' && empty($this->data['allowEmpty'])) {
            return false;
        }

        $table = $this->data['table'];

        $idField = empty($this->data['idField']) ? 'id' : $this->data['idField'];

        $row = ipDb()->selectRow($table, '*', array($valueKey => $values[$valueKey]));

        if (!$row) {
            return false;
        }

        if (isset($values[$idField]) && $values[$idField] == $row[$idField]) {
            return false;
        }

        if ($this->errorMessage !== null) {
            return $this->errorMessage;
        }

        if ($environment == \Demotic\Form::ENVIRONMENT_ADMIN) {
            $errorText = __('The value should be unique', 'Demotic-admin');
        } else {
            $errorText = __('The value should be unique', 'Demotic');
        }

        return $errorText;
    }

}
