<?php
require_once(searchinc('utils1.inc'));
require_once(searchinc('dbtable.inc'));
require_once(searchinc('htmlcustom.inc'));
require_once(searchinc('htmlforms.inc'));
require_once(searchinc('compedit.inc'));

// this is a base class that supports form fragments that are
// tied with database tables
class persistedit_base extends htmlcustom_block
{
	function __construct($attrs=null)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		
		parent::__construct(null, $attrs);
		
		if (!$this->is_ok())
		{
			$this->trigger_error();
		}
		$this->dbgecho($proc.' leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
//		return $this->is_ok();
	}
	
	// override this in derived classes to customize fetching from database into
	// the HTML controls of this object
	function load_ctrls($id)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$id.') entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		$this->dbgecho($proc.' leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	// override this in derived classes to customize storing the values of 
	// HTML controls of this object into the database
	function store_ctrls()
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		$this->dbgecho($proc.' leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	// Not sure whether this belongs here, but here it is for now
	
	// create a selection control that allows selection of an enum or set
	function create_field_option_selection_ctrl($dbobj, $field, $attrs, $style='select')
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (!is_a($dbobj, 'db_table_ex'))
		{
			$this->set_error('Database object of class '.get_class($dbobj).' not of correct type', __FILE__, __LINE__);
		}
		else
		{
			// check that the field referenced is either an enum or a set field
			$field_desc = $dbobj->get_field_desc($field);
			if (($field_desc->type != 'enum') && ($field_desc->type != 'set'))
			{
				$this->set_error('Database field '.$field.' is not of correct type', __FILE__, __LINE__);
			}
			else
			{
				// if a set, allow multiple selections
				if ($field_desc->type == 'set') $attrs['multiple'] = true;
			
				// get the value list for that field
				$vallist = $field_desc->valuelist;
			
				// create an option for each entry in the value list
				$options=array();
				foreach($vallist as $val)
				{
					$options[$val] = $val;
				}
			
				// if style is select, create the selection control
				if ($style == 'select')
				{
					$ctrl = new editselect($options, $attrs);
					if (!$ctrl->is_ok())
					{
						$this->copy_error($ctrl);
						$this->set_error('Unableto create field option selection control: select style', __FILE__, __LINE__);
					}
				}
				// if style is checkbox, create a series of checkboxes
				elseif ($style == 'checkbox')
				{
					$ctrl = new select_ck($options, $attrs);
					if (!$ctrl->is_ok())
					{
						$this->copy_error($ctrl);
						$this->set_error('Unableto create field option selection control: checkbox style', __FILE__, __LINE__);
					}
				}
				else
				{
					$this->set_error('Unknown style ['.$style.'] specified for field option selection control', __FILE__, __LINE__);
				}
			}
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($ctrl);
	}
	
	// create a selection control that allows selection of fields from a database table
	function create_field_selection_ctrl($dbobj, $field, $attrs, $style='select')
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (!is_a($dbobj, 'db_table_ex'))
		{
			$this->set_error('Database object of class '.get_class($dbobj).' not of correct type', __FILE__, __LINE__);
		}
		else
		{
			// get the list of fields in this table
			$field_list = $dbobj->list_fields();
			
			// create an option for each entry in the value list
			$options=array();
			foreach($field_list as $fld)
			{
				$options[$fld] = $fld;
			}
			
			// if style is select, create the selection control
			if ($style == 'select')
			{
				$ctrl = new editselect($options, $attrs);
				if (!$ctrl->is_ok())
				{
					$this->copy_error($ctrl);
					$this->set_error('Unableto create field option selection control: select style', __FILE__, __LINE__);
				}
			}
			// if style is checkbox, create a series of checkboxes
			elseif ($style == 'checkbox')
			{
				$ctrl = new select_ck($options, $attrs);
				if (!$ctrl->is_ok())
				{
					$this->copy_error($ctrl);
					$this->set_error('Unableto create field selection control: checkbox style', __FILE__, __LINE__);
				}
			}
			else
			{
				$this->set_error('Unknown style ['.$style.'] specified for field selection control', __FILE__, __LINE__);
			}
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($ctrl);
	}
}

class auto_persistedit extends persistedit_base
{
//	var $_debug = DEBUG_DETAIL_TRACE;
	
	var $_dbobjs_list = array();	// descriptions of a database table objects.  Should inlcude
									// class name (unique_indexed_table or relationship_table)
									// database and database user, as below
									// 'dbo1' => array('classname' => 'my_table_class',
									//		 		   'database' => MEMBER_DB_NAME,
									//		 		   'user' => DBTAB_MEMBER_MYSQL_USER),
	
	var $_htmlctrls_list = array();	// descriptions of HTML control objects.  Should include
									// class name, a name attribute suffix, any attributes, 
									// an optional default value, and if a select control is 
									// specified, a list of options, as below
									// 'ctrl1' => array('classname' => 'editselect',
									//		 			'name_suffix' => '_sel',
									//					'attributes' = array('size' => '5'
									//                                       'multiple' => false),
									//		 			'default' => 'normal',
									//		 			'options' => array('0' => 'low',
									//                  			       '1' => 'normal',
									//									   '2' => 'high')),
	
	var $_objctrlmap = array();		// description of which database field is linked to
									// which HTML control, as below
									// array('dbobj' => 'dbo1',
									//		 'dbfield' => 'desc',
									//		 'key' => false,
									//		 'ctrl' => 'ctrl1'),
	
	var $_dbobjs;
	var $_htmlctrls;
	var $_links = array('ctrl' => array(), 'dbobj' => array());
	
	function __construct($attrs=null)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		
		// create all db objects
		if ($this->_init_db_objs($attrs))
		{
			// create all controls
			if ($this->_init_ctrls($attrs))
			{
				// initialize links structure from supplied map
				if ($this->_init_links())
				{
					parent::__construct($attrs);
					if ($this->is_ok())
					{
						$this->readonly = (isset($attrs['readonly'])?$attrs['readonly']:FALSE);
					}
				}
			}
		}
		
		if (!$this->is_ok())
		{
			$this->trigger_error();
		}
		$this->dbgecho($proc.' leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
//		return $this->is_ok();
	}
	
	function _init_db_objs($attrs=null)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		
		foreach($this->_dbobjs_list as $id => $info)
		{
			$dbobj = new $info['classname']($info['database'], $info['user'], (isset($attrs['mode'])?$attrs['mode']:NULL));
			if (!$dbobj->is_ok())
			{
				$this->copy_error($dbobj);
				$this->set_error('Unable to create '.$id.' object of class '.$info['classname'], __FILE__, __LINE__);
				break;
			}
			else
			{
				$this->_dbobjs[$id] = $dbobj;
			}
		}
		
		$this->dbgecho($proc.' leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	function _init_ctrls($attrs=null)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		
		$saveattrs = $attrs;
		foreach($this->_htmlctrls_list as $id => $info)
		{
			$this->dbgecho($proc.'Control '.$id.' has info: '.look_r($info), DEBUG_DETAIL_TRACE);
			
			// start by overriding passed in attributes with configuration defined ones
                        $attrs = array_Merge_v4($saveattrs, (isset($info['attributes'])?$info['attributes']:array()));
			
			// create the correct control name
			$attrs['name'] = (isset($saveattrs['name'])?$saveattrs['name']:'').$info['name_suffix'];
			
			if(isset($info['classname']))
			{
				if (isset($attrs['options']))
				{
					$this->dbgecho($proc.'Creating '.$info['classname'].' with options '.look_r($attrs['options']).' and attrs: '.look_r($attrs), DEBUG_DETAIL_TRACE);
					$ctrl = new $info['classname']($attrs['options'], $attrs);
				}
				else
				{
					$this->dbgecho($proc.'Creating '.$info['classname'].' with attrs: '.look_r($attrs), DEBUG_DETAIL_TRACE);
					$ctrl = new $info['classname']($attrs);
				}
				if (!$ctrl->is_ok())
				{
					$this->copy_error($ctrl);
					$this->set_error('Unable to create '.$id.' html control of class '.$info['classname'], __FILE__, __LINE__);
					break;
				}
			}
			elseif (isset($info['factory_method']))
			{
                                $ctrl = $this->{$info['factory_method']}($this->_dbobjs[$info['db_object_index']],
													   $info['db_field'],
													   $attrs,
													   $info['extra']);
				if (!is_a($ctrl, 'base'))
				{
					$this->set_error('Unable to create '.$id.' html control using method '.$info['factory_method'], __FILE__, __LINE__);
					break;
				}
				elseif (!$ctrl->is_ok())
				{
					$this->copy_error($ctrl);
					$this->set_error('Unable to create '.$id.' html control using method '.$info['factory_method'], __FILE__, __LINE__);
					break;
				}
			}
			else
			{
				$this->set_error('Unable to create '.$id.' html control.  No constuction information specified', __FILE__, __LINE__);
				break;
			}
			
			if ($this->is_ok())
			{
				if (isset($info['default']))
				{
					$ctrl->value($info['default']);
				}
				$this->_htmlctrls[$id] = $ctrl;
			}
		}
		
		$this->dbgecho($proc.' leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	function _init_links()
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		
		foreach($this->_objctrlmap as $id => $info)
		{
                    $this->dbgecho($proc.'links[\'ctrl\']: '.look_r($this->_links['ctrl']), DEBUG_DETAIL_TRACE);
                    $this->dbgecho($proc.'$info[\'ctrl\']: '.look_r($info['ctrl']), DEBUG_DETAIL_TRACE);
//                  $this->dbgecho($proc.'links[\'ctrl\']['.$info['ctrl'].']: '.look_r($this->_links['ctrl'][$info['ctrl']]), DEBUG_DETAIL_TRACE);
                    
                        if (!isset($this->_links['ctrl'][$info['ctrl']])) {$this->_links['ctrl'] += [$info['ctrl'] => array()];}
//                      if (!isset($this->_links['ctrl'][$info['ctrl']])) {$this->_links['ctrl'][$info['ctrl']] == array();}
			
			$this->_links['ctrl'][$info['ctrl']][] = array('dbobj' => $info['dbobj'],
                                                                       'field' => $info['dbfield'],
                                                                       'key' => (isset($info['key'])?$info['key']:NULL),
                                                                       'identity' => (isset($info['identity'])?$info['identity']:NULL));
                        if (!isset($this->_links['dbobj'][$info['dbobj']])) {$this->_links['dbobj'] += [$info['dbobj'] => array()];}
                        if (!isset($this->_links['dbobj'][$info['dbobj']][$info['dbfield']])) {$this->_links['dbobj'][$info['dbobj']] += [$info['dbfield'] => array()];}
			
			$this->_links['dbobj'][$info['dbobj']][$info['dbfield']][] = array('ctrl' => $info['ctrl'],
											   'key' => (isset($info['key'])?$info['key']:NULL));
		}
		$this->dbgecho($proc.'links: '.look_r($this->_links), DEBUG_DETAIL_TRACE);
		
		$this->dbgecho($proc.' leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	function find_field_ctrls($dbobj, $dbfield)
	{
		return $this->_links['dbobj'][$dbobj][$dbfield];
	}
	
	function find_ctrl_fields($ctrlname)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$ctrlname.')entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		$this->dbgecho($proc.'$this->_links[\'ctrl\']: '.look_r($this->_links['ctrl']), DEBUG_DETAIL_TRACE);
		$retval = $this->_links['ctrl'][$ctrlname];
		
		$this->dbgecho($proc.' leaving - '.($this->is_ok()?look_r($retval):'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($retval, RETURN_NULL_OK);
	}
	
	// returns control index names of controls that 
	// are linkd to record key or relationship identity 
	// fields
	function find_key_controls()
	{
		$idxs = array();
		foreach($this->_links['ctrl'] as $idx => $infoarray)
		{
			foreach($infoarray as $info)
			{
				if (($info['key'] || $info['identity']) && (!in_array($idx, $idxs)))
				{
					$idxs[] = $idx;
				}
			}
		}
		return $idxs;
	}
	
	// ensure all db records and relationships are loaded into
	// the relevant database objects
	// if $id is passed, use that as the key value, otherwise 
	// use the value of linked control(s)
        // if no key value is determined, this must be an action preparing for a
        // new record, so don't try to load anythng
	function ensure_records_loaded($id=null)
	{
		$ctrls = $this->find_key_controls();
		foreach($ctrls as $ctrlidx)
		{
			$dbobjsinfo = $this->find_ctrl_fields($ctrlidx);
			foreach($dbobjsinfo as $info)
			{
				if (is_a($this->_dbobjs[$info['dbobj']], 'unique_indexed_table'))
				{
                                    $key = isset($id)?$id:$this->_htmlctrls[$ctrlidx]->value();
                                    if (!empty($key))
                                    {
                                        $this->_dbobjs[$info['dbobj']]->key($key);
                                    }
				}
				elseif (is_a($this->_dbobjs[$info['dbobj']], 'relationship_table'))
				{
                                    $key = isset($id)?$id:$this->_htmlctrls[$ctrlidx]->value();
                                    if (!empty($key))
                                    {
					$this->_dbobjs[$info['dbobj']]->identity($key);
                                    }
				}
				else
				{
					$this->set_error('Unsupported database object type '.get_class($this->_dbobjs[$info['dbobj']]), __FILE__, __LINE__);
				}
			}
		}
		
		return $this->is_ok();
	}
	
	function populate_contents()
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if ($this->num_contents() == 0)
		{
			// default behavior
			// list all controls
			$contents = array();
			$ctrlkeys = array_keys($this->_htmlctrls);
			foreach($ctrlkeys as $idx)
			{
				if (count($contents)>0) $contents[] = "<br>\n";
				$contents[] = ucfirst($idx).': ';
				$contents[] =& $this->_htmlctrls[$idx];
				$contents[] = "<br>\n";
			}
			$this->set_contentsx($contents);
		}
		parent::populate_contents();
		
		$this->dbgecho($proc.' leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	function load_ctrls($id)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$id.') entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		// make sure we have the relevant record and relationships from the database
		$this->ensure_records_loaded($id);
		
		// for each control, set it's value from the linked database field
		$this->dbgecho($proc.'links[ctrl]: '.look_r($this->_links['ctrl']), DEBUG_DETAIL_TRACE);
		foreach($this->_links['ctrl'] as $name => $infoarray)
		{
			foreach($infoarray as $info)
			{
				if (method_exists($this->_dbobjs[$info['dbobj']], 'get_field'))
				{
//					if (!$info['key'])
					{
						// get the value of the specified field
						$val = $this->_dbobjs[$info['dbobj']]->get_field($info['field']);
						$this->dbgecho($proc.'got '.look_r($val).' from field '.$info['field'], DEBUG_DETAIL_TRACE);
						// for set type fields, convert into an array,splitting on commas
						if ($this->_dbobjs[$info['dbobj']]->fields[$info['field']]->type == 'set')
						{
							if ($val !== null) $val = explode(',', $val);
							$this->dbgecho($proc.'converted value of set type field to array: '.look_r($val), DEBUG_DETAIL_TRACE);
						}
					}
				}
				elseif (method_exists($this->_dbobjs[$info['dbobj']], 'all_relationships'))
				{
					if (!$info['identity'])
					{
						$attrs = $this->_dbobjs[$info['dbobj']]->all_relationships(true);
						$val = array();
						foreach($attrs as $attr)
						{
							$val[] = $attr[$info['field']];
						}
					}
				}
				else
				{
					$this->set_error('Can\'t support database access object of class '.get_class($this->_dbobjs[$info['dbobj']]), __FILE__, __LINE__);
					break;
				}
			
				// inti
				$this->dbgecho($proc.'inserting into contol['.$name.'] of type '.(is_object($this->_htmlctrls[$name])?get_class($this->_htmlctrls[$name]):look_r($this->_htmlctrls[$name])), DEBUG_DETAIL_TRACE);
				if (method_exists($this->_htmlctrls[$name], 'checked'))
				{	
					if (!is_array($val)) $val = array($val);
					foreach ($val as $aval)
					{
						$this->_htmlctrls[$name]->checked($aval);
					}
				}
				else
				{
					$this->_htmlctrls[$name]->value($val);
				}
			}
		}
		
		$this->dbgecho($proc.' leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	// override this in derived classes to customize storing the values of 
	// HTML controls of this object into the database
	function store_ctrls($ctrl_list=null)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (!$this->readonly)
		{
			if (!isset($ctrl_list)) $ctrl_list = array_keys($this->_links['ctrl']);
			
			// TBD make sure that any key and identity fields are used to load the 
			// correct records and relationships prior to processing the remainder 
			// of the controls
                        
                        // For now, try this - should ensure that database and control vakues match up for key or identity fields
                        // but it might be unnecessary to load entire records, could just fill database key values from the appropriate
                        //  controls without doing a database fetch operation.
                        $this->ensure_records_loaded();
			
			if ($this->is_ok())
			{
				$commit_list = array();
				// for each control, save it's value to the linked database field
				foreach($ctrl_list as $name)
				{
					$this->dbgecho($proc.'processing control '.$name, DEBUG_DETAIL_TRACE);
					$infoarray = $this->_links['ctrl'][$name];
					
					foreach($infoarray as $info)
					{
						if (!$this->_htmlctrls[$name]->readonly())
						{
							if (method_exists($this->_dbobjs[$info['dbobj']], 'set_field'))
							{
								// ignore the the key, that has already been handled
								if ($info['key']!==true)
								{
									if (method_exists($this->_htmlctrls[$name], 'checked'))
									{
										$this->_dbobjs[$info['dbobj']]->set_field($info['field'], $this->_htmlctrls[$name]->checked());
										$this->dbgecho($proc.'control '.$name.' setting field '.$info['field'].' to '.($this->_htmlctrls[$name]->checked()?'true':'false'), DEBUG_DETAIL_TRACE);
									}
									else
									{
										$val = $this->_htmlctrls[$name]->value();
										if ($val==='')
										{
											$val = null;
										}
										elseif (is_object($val))
										{
											$val = $val->to_string();
										}
										elseif (is_array($val))
										{
											$val = implode(',', $val);
										}
									
										$this->_dbobjs[$info['dbobj']]->set_field($info['field'], $val);
										$this->dbgecho($proc.'control '.$name.' setting field '.$info['field'].' to '.look_r($val), DEBUG_DETAIL_TRACE);
									}
									if (!$this->_dbobjs[$info['dbobj']]->is_ok())
									{
										$this->copy_error($this->_dbobjs[$info['dbobj']]);
										$this->set_error('Unable to set field '.$info['field'].' of '.get_class($this->_dbobjs[$info['dbobj']]).' object', __FILE__, __LINE__);
										break;
									}
									else
									{
										$commit_list[$info['dbobj']] = true;
									}
								}
								else
								{
									$this->dbgecho($proc.'control '.$name.' ignored because it represents a key', DEBUG_DETAIL_TRACE);
								}
							}
							// consider supporting relationship tables also
							elseif (method_exists($this->_dbobjs[$info['dbobj']], 'has_relationship'))
							{
								if ($info['identity'])
								{
//									TBD - ensure that relationships are loaded
									$this->_dbobjs[$info['dbobj']]->identity($this->_htmlctrls[$name]->value());
								}
								else
								{
									$val = $this->_htmlctrls[$name]->value();
									if (!is_array($val)) $val = array($val);
									foreach($val as $aval)
									{
										if (!$this->_dbobjs[$info['dbobj']]->has_relationship($value, false))
										{
											$this->_dbobjs[$info['dbobj']]->add_relationship($value);
										}
									}
								}
							}
							else
							{
								$this->dbgecho($proc.'dbobject (class '.get_class($this->_dbobjs[$info['dbobj']]).') for control '.$name.' ignored because it has no set_field method', DEBUG_DETAIL_TRACE);
							}
						}
						else
						{
							$this->dbgecho($proc.'readonly control '.$name.' ignored', DEBUG_DETAIL_TRACE);
						}
					}
				}
			
				// commit the record
				if ($this->is_ok())
				{
					foreach($commit_list as $idx => $ignore)
					{
						if (method_exists($this->_dbobjs[$idx], 'put_record'))
						{
							$this->_dbobjs[$idx]->put_record();
							$this->dbgecho($proc.'dbobject '.$idx.' record has been committed', DEBUG_DETAIL_TRACE);
						}
						if (!$this->_dbobjs[$idx]->is_ok())
						{
							$this->copy_error($this->_dbobjs[$idx]);
							$this->set_error('Unable update record of '.get_class($this->_dbobjs[$idx]).' object', __FILE__, __LINE__);
							break;
						}
					}
				}
			}
		}
		
		$this->dbgecho($proc.' leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
}

 ?>