<?php namespace ProcessWire;

/**
 * ProcessWire Checkbox Fieldtype
 *
 * This Fieldtype stores an ON/OFF toggle via a single checkbox. The ON value is 1 and OFF value is 0.
 *
 * For documentation about the fields used in this class, please see:  
 * /wire/core/Fieldtype.php
 * 
 * ProcessWire 3.x (development), Copyright 2015 by Ryan Cramer
 * https://processwire.com
 *
 */

class FieldtypeCheckbox extends Fieldtype {

	public static function getModuleInfo() {
		return array(
			'title' => 'Checkbox',
			'version' => 101,
			'summary' => 'This Fieldtype stores an ON/OFF toggle via a single checkbox. The ON value is 1 and OFF value is 0.',
			'permanent' => true, 
			);
	}

	public function getBlankValue(Page $page, Field $field) {
		return 0; 
	}

	public function sanitizeValue(Page $page, Field $field, $value) {
		return $value ? 1 : 0; 
	}

	public function ___markupValue(Page $page, Field $field, $value = null, $property = '') {
		if(is_null($value)) $value = $page->get($field->name); 
		$checked = $value ? " checked='checked'" : "";
		return "<input type='checkbox'$checked disabled='disabled' />";
	}

	public function getInputfield(Page $page, Field $field) {
		$inputfield = $this->modules->get('InputfieldCheckbox'); 
		$inputfield->set('checkedValue', 1); 
		$inputfield->set('uncheckedValue', 0); 
		$value = $page->get($field->name); 
		if($value) $inputfield->attr('checked', 'checked'); 
		$inputfield->class = $this->className();
		return $inputfield; 
	}

	public function getDatabaseSchema(Field $field) {
		$schema = parent::getDatabaseSchema($field); 
		$schema['data'] = "tinyint NOT NULL";
		$schema['keys']['data'] = 'KEY data (data)'; 
		return $schema;
	}

	public function getMatchQuery($query, $table, $subfield, $operator, $value) {
		if(!empty($value) && ($operator == '!=' || $operator == '<>')) {
			// allow for matching test_checkbox!=1 since non-checked rows don't appear in database
			static $n = 0;
			$_table = $table . '_ckbx' . (++$n);
			$query->leftjoin("$table AS $_table ON $_table.pages_id=pages.id");
			$query->where("$_table.pages_id IS NULL"); 
		} else {
			$query = parent::getMatchQuery($query, $table, $subfield, $operator, $value);
		}
		return $query;
	}

	/**
	 * Return array with information about what properties and operators can be used with this field
	 * 
	 * @param Field $field
	 * @param array $data
	 * @return array
	 *
	 */
	public function ___getSelectorInfo(Field $field, array $data = array()) {
		$info = parent::___getSelectorInfo($field, $data); 
		$info['input'] = 'checkbox';
		return $info; 
	}

}

