<?php

class form {

	var $obj;
	var $templ = "attrs/form.htm";
	var $form = array();
	var $hidden_vars = array();
	var $title = '';
	var $parsed = false;
	
	function __construct( $obj ) {
		global $cat;
		$this->obj = $obj;
	}

	function setTempl( $filename ) {
		$this->templ = $filename;	
	}

	function setTitle( $title ) {
		$this->title = $title;	
	}

	function set_sql_where( $attr_name, $sql_where ) {
		$this->obj->attrs[$attr_name]['attr_obj']->sql_where = $sql_where;
	}

	function _parse() {
		if ($this->parsed) return;
		foreach ( $this->obj->attrs as $k => $attr ) {
			$this->form[$k]['title'] = $attr['desc'];
			if ( $attr['hide'] || in_array( $k, $this->obj->force_hidden ) ) {
				$this->form[$k]['html'] = '';
			} else {
			    $this->form[$k]['html'] = $attr['attr_obj']->render_input();
			}
			$this->form[$k]['mand'] = $attr['mand'];
			$this->form[$k]['hidden'] = $attr['hide'];
			$this->form[$k]['error'] = $this->obj->errors[$k];
		}
		$this->parsed = true;
	}
	
	function _html( $act = "save_edit" ) {
		global $R;
		$tpl = $R->getTpl( $this->templ, 'body' );
		$tplr = $R->getTpl( $this->templ, 'row' );
		$tplr_chbox = $R->getTpl( $this->templ, 'row_checkbox' );

		$tplm = $R->getTpl( $this->templ, 'mand' );
		foreach( $this->form as $k => $v ) {
			if ( in_array( $k, $this->obj->force_hidden ) ) continue;
			if ( $v['hidden'] || ( in_array($k, $this->hidden_vars)) ) {
				$tt = '<input type="hidden" name="' . $k . '" value="' . $this->obj->get( $k ) . '">';
				$tpl = $R->parse( 'hidden_attrs', $tt, $tpl );
			} else {

				$tt = $tplr;
				if ($this->obj->attrs[$k]['type'] == 'checkbox' ) {
					$tt = $tplr_chbox;
				}

				$tt = $R->set( 'attr_title', $v['title'], $tt );
				$tt = $R->set( 'attr_html', $v['html'], $tt );
				$tt = $R->set( 'attr_name', $k, $tt );

				if ( $v['mand'] ) {
					$tt = $R->set( 'attr_mand', $tplm, $tt );
				} else {
					$tt = $R->set( 'attr_mand', '' ,$tt );	
				}
				if ( $v['error'] ) {
					$tt = $R->set( 'attr_error', '<div>'.$v['error'].'</div>', $tt );
				} else {
					$tt = $R->set( 'attr_error', '', $tt );
				}
				$tpl = $R->parse( 'form_rows', $tt, $tpl );
			}
		}
		if ( $this->title ) {
			$tplt = $R->getTpl( $this->templ, 'th' );
			$tplt = $R->set('title', $this->title, $tplt );
			$tpl = $R->set('title_row', $tplt, $tpl );
		}

		$tpl = $R->set( 'id', $this->obj->id, $tpl );
		$tpl = $R->set( 'send_act', $act, $tpl );
		return $R->clear( $tpl );
	}
	
	function render( $act = "save_edit" ) {
		$this->_parse();
		return $this->_html( $act );	
	}
	
	function set_hidden( $attr_name ) {
		$this->hidden_vars[] = $attr_name;		
	}
	
	/**
	 * Получаем HTML код артибута
	 * @param  string $fieldName имя атрибута
	 * @return html            
	 */
	function fieldHTML($fieldName) {
        $this->_parse();
        $arr = $this->form[$fieldName];
		if ( $arr['hidden'] ) {
				return '<input type="hidden" name="'.$attr_name.'" value="'.$this->obj->get($attr_name).'">';
		} else {
			return $arr['html'];
				$tpl = $R->set( $attr_name .'_title', $arr['title'].($arr['mand']?'<span class="error">*</span>':''), $tpl );	
				$tpl = $R->set( $attr_name .'_html', $arr['html'], $tpl );	
	            $tpl = $R->set( $attr_name .'_error', '<div class="error">'.$this->obj->errors[$attr_name].'</div>', $tpl );
       }
	}

	/**
	 * Имя атрибута для формы
	 * @param  string $fieldName имя атрибута
	 * @return html            
	 */
	function fieldTitle($fieldName) {
        $this->_parse();
		return $arr['title'].($arr['mand']?'<span class="error">*</span>':'');
	}

	/**
	 * Ошибка атрибута для формы
	 * @param  string $fieldName имя атрибута
	 * @return html            
	 */
	function fieldError($fieldName) {
        $this->_parse();
        if ( isset($this->obj->errors[$attr_name]) && $this->obj->errors[$attr_name] != "") {
        	return '<div class="error">'.$this->obj->errors[$attr_name].'</div>';
        }
        return '';
	}


	function manual($tpl) {
        global $R;
        $this->_parse();
		foreach( $this->form as $attr_name => $arr ) {
			if ( $arr['hidden'] ) {
				$t = '<input type="hidden" name="'.$attr_name.'" value="'.$this->obj->get($attr_name).'">';
				$tpl = $R->parse('hidden_items', $t, $tpl );
			} else {
				$tpl = $R->set( $attr_name .'_title', $arr['title'].($arr['mand']?'<span class="error">*</span>':''), $tpl );	
				$tpl = $R->set( $attr_name .'_html', $arr['html'], $tpl );	
	            $tpl = $R->set( $attr_name .'_error', '<div class="error">'.$this->obj->errors[$attr_name].'</div>', $tpl );
            }
		}      
        return $tpl;  
    }

    /**
     * Автоматический блок формы
     * @param  string $tpl строка старого шаблонизатора
     * @return html|object      возвращает или строку старого шаблонизатора или объект для blade
     */
	function autotpl($tpl = "") {
		global $R;


        $this->_parse();

		$tplr = $R->getTpl( $this->templ, 'row' );
		$tplr_chbox = $R->getTpl( $this->templ, 'row_checkbox' );
		$tplm = $R->getTpl( $this->templ, 'mand' );

		$tpls = [];

		foreach( $this->form as $k => $v ) {
			if ( in_array( $k, $this->obj->force_hidden ) ) continue;
			if ( $v['hidden'] || ( in_array($k, $this->hidden_vars)) ) {
				$tt = '<input type="hidden" name="' . $k . '" value="' . $this->obj->get( $k ) . '">';
				$tpls[$k] = $tt;
			} else {

				$tt = $tplr;
				if ($this->obj->attrs[$k]['type'] == 'checkbox' ) {
					$tt = $tplr_chbox;
				}

				$tt = $R->set( 'attr_title', $v['title'], $tt );
				$tt = $R->set( 'attr_html', $v['html'], $tt );
				$tt = $R->set( 'attr_name', $k, $tt );

				if ( $v['mand'] ) {
					$tt = $R->set( 'attr_mand', $tplm, $tt );
				} else {
					$tt = $R->set( 'attr_mand', '' ,$tt );	
				}
				if ( $v['error'] ) {
					$tt = $R->set( 'attr_error', '<div>'.$v['error'].'</div>', $tt );
				} else {
					$tt = $R->set( 'attr_error', '', $tt );
				}
				$tpls[$k] = $tt;
			}
		}

		// Старый шаблонизатор
		if ($tpl != "") {
			foreach( $tpls as $k => $v ) {
				$tpl = $R->set($k . '_block', $v, $tpl);
			}
			$tpl = $this->manual($tpl);
			return $tpl;		
		} else {
			// Возвращаем в виде объекта
			$retObj = new stdClass();
            $tpls['id'] = '<input type="hidden" name="id" value="'.intval($this->obj->id).'">';
			foreach( $tpls as $k => $v ) {
				$retObj->$k = $v;
				$htmlKey = $k . '_html';
				if ( in_array( $k, $this->obj->force_hidden ) ) { 
					$retObj->$htmlKey = '';
				} else {
					if ($this->form[$k]['hidden'] || ( in_array($k, $this->hidden_vars)) ) {
						$retObj->$htmlKey = '<input type="hidden" name="' . $k . '" value="' . $this->obj->get( $k ) . '">';
					} else {
						$retObj->$htmlKey = $this->form[$k]['html'];
					}
				}
			}			
			return $retObj;
		}

	}	
}	

?>