<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Illuminate\Contracts\Encryption\DecryptException;

use Schema;
use DB;

class UpdateUniqueRule implements Rule
{
    
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    private $field_name;
    private $table_name;
    private $message;
    private $id;




    public function __construct($table,$field,$row_id)
    {
        try 
        {
            $row_id = decrypt($row_id);

            $this->table_name = $table;
            $this->field_name = $field;
            $this->id         = $row_id;

            $this->message    = 'Required Validation.';

            

        } 
        catch (DecryptException $e) 
        {
            //
        }
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        
       
        if($this->verification())
        {
            if($this->getQuery($value))
            {
                return true;
            }
            else
            {
                $this->setMessage('The '.$attribute.' already found.');
            }
        }
       
        return false;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    
    // SET ERROR MESSAGE
    public function setMessage($msg)
    {
        $this->message = $msg;
    }

    // RETURN CUSTOM ERROR MESSAGE
    public function message()
    {
        return $this->message;
    }

    // RETURN FIELD NAME
    public function getFieldName()
    {
        return $this->field_name;
    }

    // RETURN TABLE NAME
    public function getTableName()
    {
        return $this->table_name;
    }

    // RETURN ID
    public function getRowId()
    {
        return $this->id;
    }


    public function getQuery($value)
    {
            $current = DB::table($this->getTableName())->where(['id' => $this->getRowId(),'is_recycle' => 0])->first();

            $flag = DB::table($this->getTableName())->where([$this->getFieldName() => $value,'is_recycle' => 0])->count();

            $current = json_decode(json_encode($current), true);

            if(isset($current['id']) && $current[$this->getFieldName()] == trim($value))
            {
                return true;
            }
            else if(($flag) == 0)
            {
                return true;
            }

        return false;
    }

    public function verification()
    {
        if(Schema::hasTable($this->getTableName()) && Schema::hasColumn($this->getTableName(),$this->getFieldName()))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}
