<?php
 
class asset
{
	function asset($def)
	{
		$this->db = $GLOBALS['db'];
		
		$this->name = $def['name'];
		$this->title = $def['title'];
		$this->elements = $def['elements'];
		$this->list_sql = $def['list_sql'];
		$this->edit_sql = $def['edit_sql'];
		$this->save_sql = $def['save_sql'];
		$this->add_sql = $def['add_sql'];
		$this->delete_sql = $def['delete_sql'];
		$this->per_page = $def['list_per_page'];
		$this->script = empty($def['script']) ? 'index.php?show=' . $this->name : $def['script'];
		
		if (isset($def['list_width']))
			$this->list_width = $def['list_width'];
		
		$this->param_element = $def['param'];
		
		// edit parameter
		$this->param = $_REQUEST['param'];
		
		$action = $_GET['action'];
		
		if ($action === 'add')
		{
			$this->prepareAdd();
		} elseif ($action === 'edit') {
			$this->prepareEdit();
		} elseif ($action === 'add_new') {
			$this->prepareAddNew();
		} elseif ($action === 'save') {
			$this->prepareSave();
		} elseif ($action === 'delete') {
			$this->prepareDelete();
		} else {
			$this->prepareList();
		}
	}
	
	function prepareElementArray($values = array())
	{
		$elements = array();
		
		$q = preg_replace('~%param%~i', mysql_real_escape_string($this->param), $this->edit_sql);
		$s = $this->db->query($q);
		
		$uid = 0;
		
		foreach ($this->elements as $n => $element)
		{
			$uid++;
			$value = isset($values[$n]) ? $values[$n] : $v['default'];
			$smarty = i_want_smarty();
			
			$name = 'values[' . $n . ']';
			
			if (file_exists($GLOBALS['base_path'] . '/scripts/html/' . $element['type'] . '.php'))
				include($GLOBALS['base_path'] . '/scripts/html/' . $element['type'] . '.php');
			
			$smarty->assign('name', $name);
			$smarty->assign('value', $value);
			
			if (is_array($element['params']))
			{
				foreach($element['params'] as $pn => $pv)
				{
					$smarty->assign($pn, $pv);
				}
			}
				
			$element['element_html'] = $smarty->fetch('html/' . $element['type'] . '.tpl');
			
			$elements[] = $element;
		}
		
		return $elements;
	}
	
	function prepareAdd()
	{
		define('editing', 1);
		
		$this->out['action'] = 'add';
		$this->out['form_action'] = 'add_new';
		$this->out['button_caption'] = 'Add new';
		
		$this->out['list_width'] = isset($this->list_width) ? $this->list_width : '100%';
		
		$this->out['elements'] = $this->prepareElementArray();
	}
	
	function prepareEdit()
	{
		define('editing', 1);
		
		$this->out['action'] = 'edit';
		$this->out['form_action'] = 'save';
		$this->out['param'] = urlencode($this->param);
		$this->out['button_caption'] = 'Update';
		
		$this->out['list_width'] = isset($this->list_width) ? $this->list_width : '100%';
		
		$q = preg_replace('~%param%~i', mysql_real_escape_string($this->param), $this->edit_sql);
		$s = $this->db->query($q);
		
		$this->out['elements'] = $this->prepareElementArray($s[0]);
	}
	
	function prepareAddNew()
	{
		define('saving', 1);
		
		$sql = array();
		$sql_left = array();
		$sql_right = array();
		
		foreach ($this->elements as $n => $element)
		{
			$exclude = false;
			$value = stripslashes($_POST['values'][$n]);
			
			if (file_exists($GLOBALS['base_path'] . '/scripts/html/' . $element['type'] . '.php'))
				include($GLOBALS['base_path'] . '/scripts/html/' . $element['type'] . '.php');
				
			if (!$exclude)
				$sql[] = array($n, $value);
		}
		
		if (!empty($sql))
		{
			foreach($sql as $n => $v)
			{
				array_push($sql_left, "`" . $v[0] . "`");
				array_push($sql_right, "'" . mysql_real_escape_string($v[1]) . "'");
			}
			
			$search = array();
			$search[] = '~%sql_left%~i';
			$search[] = '~%sql_right%~i';
			
			$replace = array();
			$replace[] = implode(',', $sql_left);
			$replace[] = implode(',', $sql_right);
			
			$q = preg_replace($search, $replace, $this->add_sql);
			$this->db->query($q);
		}
		
		header('Location: ' . $this->script);
		exit();
	}
	
	function prepareSave()
	{
		define('saving', 1);
		
		$sql = array();
		$sql_left = array();
		$sql_right = array();
		
		foreach ($this->elements as $n => $element)
		{
			$exclude = false;
			$value = stripslashes($_POST['values'][$n]);
			
			if (file_exists($GLOBALS['base_path'] . '/scripts/html/' . $element['type'] . '.php'))
				include($GLOBALS['base_path'] . '/scripts/html/' . $element['type'] . '.php');
				
			if (!$exclude)
				$sql[] = array($n, $value);
		}
		
		$sql_upd = '';
		$i = 0; $total = count($sql) - 1;
		foreach($sql as $n => $v)
		{
			$sql_upd .= "`" . $v[0] . "`='" . mysql_real_escape_string($v[1]) . "'";
			if ($i < $total) $sql_upd .= ",";
			$i++;
		}
		
		if(!empty($sql_upd))
		{
			$search = array();
			$search[] = '~%update_sql%~i';
			$search[] = '~%param%~i';
			
			$replace = array();
			$replace[] = $sql_upd;
			$replace[] = mysql_real_escape_string($this->param);
			
			$q = preg_replace($search, $replace, $this->save_sql);
			$this->db->query($q);
		}
		
		header('Location: ' . $this->script);
		exit();
	}
	
	function prepareDelete()
	{
		if (is_array($_REQUEST['sel']) && count($_REQUEST['sel']) > 0)
		{
			$p = $_REQUEST['sel'];
		} else {
			$p = array(0 => $_REQUEST['param']);
		}
		
		$q = preg_replace('~%param%~i', implode(',', $p), $this->delete_sql);
		$this->db->query($q);
		
		header('Location: ' . $this->script);
		exit();
	}
	
	function prepareList()
	{
		define('listing', 1);
		
		$this->out['action'] = 'list';
		$this->out['dList'] = array();
		$this->out['list_width'] = isset($this->list_width) ? $this->list_width : '100%';
		
		foreach ($this->elements as $n => $v)
		{
			if ($v['in_list'] === true)
			{
				$this->out['dList'][] = array(
					'value'	=>	$n,
					'title'	=>	$v['caption'],
					'type'	=>	$v['type'],
					'preview_path'	=>	$v['params']['preview_path'],
					'subdir'	=>	$v['subdir'],
					'truncate'	=>	$v['list_truncate'],
					'date_format'	=>	$v['date_format']
				);
			}
		}
		
		$search = array();
		$search[] = '~%sql_val%~i';
		$search[] = '~%sql_order%~i';
		$search[] = '~%sql_limit%~i';
		
		$replace = array();
		$replace[] = 'count(*) as `count`';
		$replace[] = '';
		$replace[] = '';
		
		$paging_query = preg_replace($search, $replace, $this->list_sql);
		include($GLOBALS['base_path'] . '/scripts/paging.php');
		
		// did we pass sorting info in url? if no then grab it from session
		$order_by = empty($_GET['order_by']) ? $_SESSION['order_by_' . $this->name] : $_GET['order_by'];
		$order_how = empty($_GET['order_how']) ? $_SESSION['order_how_' . $this->name] : $_GET['order_how'];
		
		// what do we sort by? we need correct sql paths to columns
		$order_by_sql = $this->elements[$order_by]['sql_path'];
		
		// there is only asc and desc ordering
		$order_how = $order_how === 'desc' ? 'desc' : 'asc';
		
		// save sorting preferences in session
		$_SESSION['order_by_' . $this->name] = $order_by;
		$_SESSION['order_how_' . $this->name] = $order_how;
		
		// pass sorting info to template
		$this->out['order_by'] = $order_by;
		$this->out['order_how'] = $order_how;
		
		$search = array();
		$search[] = '~%sql_val%~i';
		$search[] = '~%sql_order%~i';
		$search[] = '~%sql_limit%~i';
		
		$replace = array();
		$replace[] = '*';
		$replace[] = empty($order_by_sql) ? '' : "order by `" . $order_by_sql . "` " . $order_how;
		$replace[] = "limit " . $first_record . ", " . $per_page;
		
		$query = preg_replace($search, $replace, $this->list_sql);
		$this->out['list'] = $this->db->query($query);
	}
	
	function out()
	{
		$this->out['name'] = $this->name;
		$this->out['title'] = $this->title;
		$this->out['param_element'] = $this->param_element;
		$this->out['script'] = $this->script;
		
		return $this->out;
	}
}
 
?>