<?php

/*
 *	Class Crud (Create,Read,Update,Delete)
 *	@Author: Rok Kelvišar, RoKreativa
 *	@AuthorWeb: http://www.rokreativa.si
 *	
 *	© Rok Kelvišar 2011 - 2012 
 */

	class Crud extends Db {
		public $model = array('c','r','u','d','l');
		public $field_separator = 'f_';
		
		function __construct ($table_name,$model=array()) {
			$this->model = $model;
			$this->table_name = $table_name;
			$this->table='';
			$sql = "DESCRIBE {$table_name}";
			$this->tbl_structure = $this->select($sql);
			
			foreach ($this->tbl_structure as $field) {
				if (($field['Key'] == 'PRI') && ($field['Extra'] == 'auto_increment')) $this->primary_key = $field['Field'];
			}
			//dump($this);
			$this->prepareForm();
		}
		
		function renderTableHeader() {
			$thead_pre 	= "<thead>\n\t<tr>";
			$thead_app 	= "\n\t</tr></thead>\n";
			$thead 		= '';
			foreach ($this->tbl_structure as $field) {
				if     ((!isset($this->model['r'][$field['Field']]) || $this->model['r'][$field['Field']] === true)
					&& (!isset($this->model['l'][$field['Field']]) || $this->model['l'][$field['Field']] === true)) {
					//dump($field['Field'].": ".$this->model['l'][$field['Field']]);
					$thead .= "<th
									data-name = '{$field['Field']}' 
									data-type = '{$field['Type']}' 
									data-null = '{$field['Null']}'
									data-key = '{$field['Key']}'
									data-default = '{$field['Default']}'
									data-extra = '{$field['Extra']}'
							   >{$field['Field']}</th>";
				}
			}
			$thead .= "<th></th>";
			//krumo($this);
			$this->table['thead'] = $thead_pre.$thead.$thead_app;
		}
		
		function renderTableBody($sql_where = '1=1') {
			$this->sql_where = $sql_where;
			$tbody_pre = '<tbody>';
			$tbody_app = '</tbody>';
			$table = '';
			$sql = "SELECT * FROM {$this->table_name} WHERE {$this->sql_where}";
			$this->table['raw_output'] = $this->select($sql);
			$tbody='';
			foreach ($this->table['raw_output'] as $row) {
				$tbody .= "<tr>";
					foreach ($this->tbl_structure as $field) {
						//dump($field);
						if     ((!isset($this->model['r'][$field['Field']]) || $this->model['r'][$field['Field']] === true)
							&& (!isset($this->model['l'][$field['Field']]) || $this->model['l'][$field['Field']] === true)) {
								$tbody .= "<td>".$row[$field['Field']]."</td>";
						}
					}
					
				if (isset($row['is_active']) && $row['is_active']) {
					$activate="deactivate";
					$activate_label="Deaktiviraj";
				} else {
					$activate="activate";
					$activate_label="Aktiviraj";
				}
				$tbody .= '<td>
								<a href="'.$row[$this->primary_key].'/edit/">Uredi</a>
								<a href="'.$row[$this->primary_key].'/'.$activate.'/">'.$activate_label.'</a>
								<a href="'.$row[$this->primary_key].'/delete/">Izbriši</a>
						   </td>';
				$tbody .= "</tr>\n";
			}
			$this->table['tbody'] = $tbody_pre.$tbody.$tbody_app;
		}
		
		function renderTable() {
			$this->renderTableHeader();
			$this->renderTableBody();
			$this->table['html'] = "<table class='list wide'>".$this->table['thead'].$this->table['tbody']."\n</table>";
		}
		
		
		public function prepareForm() {
			$form = '<form id="main_form" action="" method="post">
					<input type="button" value="Nov vnos" onclick="$(\'fieldset.hidden\').toggle()"/>
					<fieldset class="hidden">';
			//dump($this->tbl_structure);
			foreach ($this->tbl_structure as $fKey => $f) {
				$row = '';
				$input_type = $this->getFieldType($f['Type']);
				if (!isset($input_type['attr'])) $input_type['attr'] = '';
				//dump($input_type);
				if (!isset($this->model['c'][$f['Field']]) || $this->model['c'][$f['Field']]) {
					$row .= '<div class="row">';
						$row .= '<label for="f_'.$f['Field'].'">'.$f['Field'].':</label>';
						$input = "<{$input_type['tag']} {$input_type['attr']} placeholder='".$f['Field']." ...'".'name="f_'.$f['Field'].'" id="f_'.$f['Field'].'"'.">\n";
						$input.= "</{$input_type['tag']}>";
						$row .= $input;
					$row .= "</div>\n";
					$form .= $row;
				}
				
				$this->tbl_structure[$fKey]['cust_input_type'] = $input_type;
			}
			
			$form .= "<div class='row last' style=''><input type='submit' value='Shrani' /></div></fieldset></form>";
			$this->form = $form;
			return $this->form;
		}
		
		function getFieldType($ftype) {
			$arr_field_types = array();
			
			//explode by ( char
			$field = explode("(",rtrim($ftype,")"));
			$input_type['data_type'] = $field[0];
			switch ($field[0]) {
				case 'varchar':
				case 'varchar':
					$input_type['tag']='input';
				break;
				
				case 'int':		//TODO: dokončaj!
				case 'decimal':
				case 'tinyint':
					if ($field[1] > 1) {
						$input_type['tag']='input';
						$input_type['attr']=' type="number" data-max-length="'.$field[1].'"';
						$input_type['condattr'] = '(value:1){checked="checked"}';
					} else {
						$input_type['tag']='input';
						$input_type['attr']='type="checkbox"';
						$input_type['condattr'] = '(value:1){checked="checked"}';
					}
				break;
				
				case 'char':		//TODO: dokončaj!
					if ($field[1] == 32) {
						$input_type['tag']='input';
						$input_type['attr']=' type="password"';
						$input_type['condattr'] = '(value:1){checked="checked"}';
						$input_type['type'] = 'pass';
					}
				break;
				
				default:
					$input_type='input';
				break;
			}
			//dump($field[0].': '.$input_type['tag'].' | : '.$input_type['attr'].' | : '.$input_type['condattr']);
			//dump($field);
			return $input_type;
		}
		
		function validateForm($data) {
			krumo($this->tbl_structure);
			foreach ($this->tbl_structure as $field) {
				if (isset($data[$this->field_separator.$field['Field']]) && !empty($data[$this->field_separator.$field['Field']])) {
					
					//validation
					$data[$this->field_separator.$field['Field']];	//to be validated
					$field; 										//field definition
					
					if (in_array($field['cust_input_type']['data_type'],array('tinyint','int'))) {
						dump('TINYINT');
					}
					
					dump($data[$this->field_separator.$field['Field']].": ");
					dump($field);
					
				}
			}
		}
		function saveForm() {
			
		}
		
		function edit() {
			krumo($this);
		}
		function delete($id) {			
			$sql = "DELETE FROM {$this->table_name} WHERE {$this->primary_key} = {$id}";
			if($this->query($sql)) {
				header("Location: {$_SERVER['HTTP_REFERER']}");
			}
		}
		
		function deactivate($id,$action=false) {
			$bool = ($action) ? 1 : 0;
			$sql = "UPDATE {$this->table_name} SET is_active = {$bool} WHERE {$this->primary_key} = {$id}";
			//dump($sql);
			if($this->query($sql)) {
				header("Location: {$_SERVER['HTTP_REFERER']}");
			}
		}
	}
	
	//$crud = new Crud();
?>