<?php
 
namespace Filter; 
 
class Condition
{
	private $table;
	private $field;
	private $op;
	private $value;
	
	public function Get() {
		$tblString = !is_null($this->table) ? $this->table."." : "";
    switch ($this->op) {
      case "=":
        return is_null($this->value) ? $tblString."`".$this->field."` IS NULL " : $tblString."`".$this->field."` = '".$this->value."'";
      case "<>":
        return is_null($this->value) ? $tblString."`".$this->field."` IS NOT NULL " : $tblString."`".$this->field."` <> '".$this->value."'";
      case "<":
        return $tblString."`".$this->field."` < '".$this->value."'";
      case ">":
        return $tblString."`".$this->field."` > '".$this->value."'";
      case "<=":
        return $tblString."`".$this->field."` <= '".$this->value."'";
      case ">=":
        return $tblString."`".$this->field."` >= '".$this->value."'";
      case "like":
        return $tblString."`".$this->field."` LIKE '%".$this->value."%'";
      case "not like":
        return $tblString."`".$this->field."` NOT LIKE '%".$this->value."%'";
      case "in":
        return "'".$this->value."' IN ".$tblString.$this->field."'";
      case "not in":
        return "'".$this->value."' NOT IN ".$tblString.$this->field."'";
    }
    return "1 ";
	}
	
	public function __construct($field, $op, $value, $table = null) {
		$this->field = $field;
		$this->op = $op;
		$this->value = $value;
		$this->table = $table;
	}
}

class ConditionList
{
	private $mode = "or";
	private $list = [];
	
	public function Get() {
		if (count($this->list)==0) {
			return "1";
		}
		
		$strings = [];
		foreach ($this->list as $entry) {
			$strings[] = $entry->Get();
		}
		$strings = array_unique($strings);
		$string = join(" ".$this->mode." ", $strings);
  	return count($strings)>1 ? "(".$string.")" : $string;
	}
	
	public function __construct($mode) {
		$this->mode = $mode;
	}
	
	public function Add($condition) {
		$this->list[] = $condition;
		return $this;
	}
}
 
class Filter
{
	private static $fields = [];
	private static $requested = null;
	private static $restricted = null;
	
	public static function Where() {
  	if (is_null(self::$requested) && is_null(self::$restricted)) {
  		return "";
  	}
  	$ret = " WHERE ";
  	if (!is_null(self::$requested)) {
  		$ret.= self::$requested->Get();
  	}
  	if (!is_null(self::$restricted)) {
  		$ret.= (is_null(self::$requested) ? "" : "AND ").self::$restricted->Get();
  	}
  	return $ret;
  }
  
  public static function Selected($field) {
  	return empty(self::$fields) || in_array($field, self::$fields);
  }
  
  public static function Limit($fields) {
  	self::$fields = $fields;
  }
  
  public static function Request($condition) {
  	self::$requested = $condition;
  }
  
  public static function Restrict($condition) {
  	self::$restricted = $condition;
  }
}
