<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

/*
 * Predstavlja negaciju laravelovog pravila 'exists'
 */
class ExistsNot implements Rule
{
    private $tablename;
    private $tableColumn;
    private $ignorePairs;

    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct($tablename, $tableColumn, Array $ignorePairs = [])
    {
        $this->tablename = $tablename;
        $this->tableColumn = $tableColumn;
        $this->ignorePairs = $ignorePairs;

        $this->validateIgnorePairs($ignorePairs);
    }

    /**
     * Validiraj '$ignorePairs'
     * 
     * @param 
     * @throws \Exception
     * @return void
     * 
     */
    private function validateIgnorePairs($ignorePairs) 
    {
        if(count($ignorePairs) == 0) {
            return;
        }

        foreach($ignorePairs as $pair) {

            if( ! is_array($pair) || count($pair) < 2 || count($pair) > 3 ) {
                throw new \Exception(__CLASS__ . ': Programerska greska: Treci '
                . 'parametar "$ignorePairs" mora sadrzati clanove koji su nizovi '
                . ' gde svaki podniz ima dva ili tri clana');
            }

            if( ! is_string($pair[0]) ||  ! is_string($pair[1]) ) {
                throw new \Exception(__CLASS__ . ': Programerska greska: Clanovi '
                . 'podnizova parametra $ignorePairs moraju biti tipa String');
            }

        }
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $query =  \DB::table($this->tablename)
                     ->where($this->tableColumn, trim($value));

        foreach($this->ignorePairs as $ignorePair) {
            $operator = $ignorePair[2] ?? '<>';
            $colName = $ignorePair[0];
            $colVal = $ignorePair[1];
            $query->where($colName, $operator, $colVal);
        }

        return $query->doesntExist();
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return __('U tabeli ":attribute" već postoji unos sa datom vrednošću.');
    }
}
