<?php
/**
 *
 * @package fabrikar
 * @author Rob Clayburn
 * @copyright (C) Rob Clayburn
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
 */


/**
 *
 *
 */

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();

//require the abstract plugin class
require_once(COM_FABRIK_FRONTEND.DS.'models'.DS.'plugin.php');
require_once(COM_FABRIK_FRONTEND.DS.'models'.DS.'validation_rule.php');

class FabrikModelIsuniquevalue extends FabrikModelValidationRule {

	var $_pluginName = 'isuniquevalue';

	/** @param string classname used for formatting error messages generated by plugin */
	var $_className = 'notempty isuniquevalue';

	/**
	 * validate the elements data against the rule
	 * @param string data to check
	 * @param object element Model
	 * @param int plugin sequence ref
	 * @return bol true if validation passes, false if fails
	 */

	function validate( $data, &$elementModel, $c )
	{
		//could be a dropdown with multivalues
		if (is_array($data)) {
			$data = implode('', $data);
		}
		$params =& $this->getParams();
		$element 			=& $elementModel->getElement();
		$tableModel 	=& $elementModel->getTableModel();
		$table 				=& $tableModel->getTable();
		$db 					=& $tableModel->getDb();
		$lookuptable 	= $db->nameQuote($table->db_table_name);
		$data 				= $db->Quote($data);
		if ($params->get('isuniquevalue-caseinsensitive') == 1) {
			$sql = "SELECT COUNT(*) FROM $lookuptable WHERE $element->name LIKE $data";
		} else {
			$sql = "SELECT COUNT(*) FROM $lookuptable WHERE $element->name = $data";
		}

		// $$$ hugh - need to check to see if we're editing a record, otherwise
		// will fail 'cos it finds the original record (assuming this element hasn't changed)
		// @TODO - is there a better way getting the rowid?  What if this is form a joined table?
		// $rowid = JRequest::getVar('rowid');
		// Have to do it by grabbing PK from request, 'cos rowid isn't set on AJAX validation
		$pk = FabrikString::safeColNameToArrayKey($table->db_primary_key);
		$rowid = JRequest::getVar($pk, '');
		if (!empty($rowid)) {
			//if main key is in repeat group!
			if (is_array($rowid)) {
				foreach($rowid as &$i) {
					$i = $db->Quote($i);
				}
				$s = implode(',', $rowid);
				if ($s !== "''") {
					$sql .= " AND $table->db_primary_key NOT IN (" . $s . ")";
				}
			} else {
				$sql .= " AND $table->db_primary_key != " . $db->Quote($rowid);
			}
		}
		$db->setQuery($sql);
		$c = $db->loadResult();
		return ($c == 0) ? true : false;
	}
}
?>