<?php

/**
 * Class SupsysticTablesPro_Tables_Model_Conditions
 */
class SupsysticTablesPro_Tables_Model_Conditions extends SupsysticTables_Core_BaseModel {

	/**
	 * Returns all table conditions
	 * @param int $id Table id
	 * @return array
	 */
	public function getConditions($id)
	{
		$query = $this->getQueryBuilder()
			->select($this->getField(null, 'data'))
			->from($this->getTable())
			->where('table_id', '=', (int)$id)
			->orderBy($this->getField(null, 'id'));

		$conditions = $this->db->get_results($query->build());

		if ($this->db->last_error) {
			throw new RuntimeException($this->db->last_error);
		}

		if (count($conditions) > 0) {
			foreach ($conditions as $i => $c) {
				$conditions[$i] = @unserialize($c->data);
			}
		}

		return $conditions;
	}

	/**
	 * @param $id
	 * @param $conditions
	 * @param bool $remove
	 */
	public function setConditions($id, $conditions, $remove = true)
	{
		try {
			if($remove) {
				$this->removeConditions($id);
			}
			foreach ($conditions as $c) {
				$this->addCondition($id, $c);
			}
		} catch (Exception $e) {
			throw new RuntimeException(
				sprintf('Failed to set conditions: %s', $e->getMessage())
			);
		}
	}

	/**
	 * Adds a condition to the table.
	 * @param int $id Table id
	 * @param array $data An array of the condition data
	 * @return int
	 */
	public function addCondition($id, array $data)
	{
		$query = $this->getQueryBuilder()
			->insertInto($this->getTable())
			->fields(
				$this->getField(null, 'table_id'),
				$this->getField(null, 'data')
			)
			->values((int)$id, serialize($data));

		$this->db->query($query->build());

		if ($this->db->last_error) {
			throw new RuntimeException($this->db->last_error);
		}

		return $this->db->insert_id;
	}

	/**
	 * Removes all table conditions.
	 * @param int $id Table id
	 */
	public function removeConditions($id)
	{
		$query = $this->getQueryBuilder()
			->deleteFrom($this->getTable())
			->where($this->getField(null, 'table_id'), '=', (int)$id);


		$this->db->query($query->build());

		if ($this->db->last_error) {
			throw new RuntimeException($this->db->last_error);
		}
	}
}