<?php

namespace Booktics\Validation\Rules;

/**
 * Class Unique_Rule
 */
class Unique_Rule implements Rule {

    /**
     * Store table name
     *
     * @var string
     */
    private $table;

    /**
     * Store column name
     *
     * @var string
     */
    private $column;

    /**
     * Store except id
     *
     * @var mixed|null
     */
    private $except_id;

    public function __construct( string $table, string $column, $except_id = null ) {
        $this->table    = $table;
        $this->column   = $column;
        $this->except_id = $except_id;
    }

    /**
     * Check the rule passed or not
     *
     * @param any $field
     * @param any $value
     *
     * @return bool
     */
    public function passes( $field, $value ): bool {
        if ( $this->table === 'wp_users' ) {
            $existing_user = get_user_by( $field, $value );

            if ( ! $existing_user ) {
                return true;
            }

            if ( intval( $existing_user->ID ) === intval( $this->except_id ) ) {
                return true;
            }

            return false;
        }
        return true;
    }

    /**
     * Set validation message
     *
     * @param any $field
     *
     * @return string
     */
    public function message( $field ) {
        return $field . ' is not unique';
    }
}
