<?

define('FIELD_TYPE_VAL', 1);
define('FIELD_TYPE_FIL', 2);

define('IFX_ERR_INVALID_USER', 100);
define('IFX_ERR_PLAN_NOT_EDITABLE', 101);
define('IFX_ERR_PLAN_DELETED', 102);

require_once('class.stdModule.php');
require_once('class.businessplan.php');

class ifex0200 extends stdModule {

	function ifex0200() {

		$this->stdModule('ifex0200');

		$this->_settings->templates->bsp_editor	= 'editor_step.tpl';
		$this->_settings->templates->bsp_view	= 'bsp_view.tpl';
		$this->_settings->templates->bsp_list	= 'bsp_list.tpl';
		$this->_settings->templates->contactbox	= 'contactbox.tpl';
		$this->_settings->templates->bsp_search_queries	= 'bsp_search_queries.tpl';
		
		$this->_settings->templates->bsp_search	= 'bsp_search.tpl';
		$this->_settings->templates->bsp_movie	= 'bsp_movie.tpl';
		$this->_settings->templates->request_contact	= 'request_contact.tpl';

		$this->_variables->public->current_step	= 1;

//		$this->_smrt->register_function('do_it', 'tpl_do_it');
		$this->setTemplateFunction('generate_table', 'tpl_generate_table');

		$this->_init_ctrl();
	}

	function _init_ctrl() {
		if (!isset($GLOBALS['g_obj_ctrl']) || !is_object ($GLOBALS['g_obj_ctrl'])) {
			include_once('htmlcontrols-1.0/class.htmlcontrols.php');
			$GLOBALS['g_obj_ctrl'] = new htmlControls ($this->_settings->general->project->languageCode, $this->_settings->general->paths->virtual->style.'controls.css');
			$GLOBALS['g_obj_ctrl']->_initialized = 1;
			$GLOBALS['g_obj_ctrl']->_init_status['main'] = 1;
		}

		$this->_ctrl =& $GLOBALS['g_obj_ctrl'];
	}

	function print_bsp_create($bsp_id=null) {
		if (!isset($_SESSION['session_usr_id']) || !is_numeric($_SESSION['session_usr_id'])) {
			$this->triggerError(IFX_ERR_INVALID_USER);
			return;
		}

		$this->_bsp = new businesplan($this->_db, $bsp_id);

		if (!is_numeric($bsp_id) || $bsp_id < 1) {
			$this->_bsp->create_new();
		}

		if (!$this->_bsp->is_owner($_SESSION['session_usr_id'])) {
			$this->triggerError(IFX_ERR_INVALID_USER);
			return;
		}

		if ($this->_bsp->state == 'WAIT') {
			$this->triggerError(IFX_ERR_PLAN_NOT_EDITABLE);
			return;
		}

		if ($this->_bsp->state == 'DECLINE') {
			$this->triggerError(IFX_ERR_PLAN_DELETED);
			return;
		}


		$this->_bsp->_lookup_data(true, 'STEP_'.$this->_variables->public->current_step);

		$this->print_step($this->_variables->public->current_step);

	}

	function print_bsp($bsp_id) {

		$this->_bsp = new businesplan($this->_db, $bsp_id);
		$this->_bsp->_lookup_data();

		if ($_SESSION['session_usr_def_code'] == 'MEM' && !$_SESSION['GATT_USR_CHAMPION_DEAL'] && $this->_bsp->champion) {
			return;
		}


		$this->_smrt->assign('sheet',	array(
											'bsp_id'		=> $this->_bsp->id
										,	'champion'		=> $this->_bsp->champion
										,	'state'			=> $this->_bsp->state
										,	'title'			=> $this->_bsp->title
										,	'video_code'	=> $this->_bsp->video_code
										,	'data'			=> $this->_bsp->get_data()
										,	'current_user'	=> $this->_get_user_level($bsp_id)
										,	'admin_comments' => $this->_bsp->admin_comments
										)
							);

		$this->assignTemplateGlobals();
		$this->_smrt->display($this->_settings->templates->bsp_view);

	}

	function print_step($step) {


		$this->_smrt->assign('sheet',	array(
											'bsp_id'		=> $this->_bsp->id
										,	'champion'		=> $this->_bsp->champion
										,	'total_steps'	=> 6
										,	'current_step'	=> $step
										)
							);

		$this->_smrt->assign('step_data', $this->_bsp->get_group_data('STEP_'.$step));

		$this->assignTemplateGlobals();
		$this->_smrt->display($this->_settings->templates->bsp_editor);

	}

	function get_bsp_info(&$result, $ids) {

		if (!is_array($ids)) {
			$single = true;
			$ids = array($ids);
		}

		foreach ($ids as $id) {

			$bsp = new businesplan($this->_db, $id);
			$result[$id] = $bsp->get_main_data();

		}

		if ($single) $result = current($result);
	}

	function print_movie($bsp_id) {
		global $globalSettings;
		
		$bsp = new businesplan($this->_db, $bsp_id);
		$bsp_info = $bsp->get_main_data();
		
		if ($bsp_info['video_code']) {
			$chapter_file = $globalSettings->general->paths->absolute->public .'video/'. $bsp_info['video_code'] . '/chapters.xml';
			$xsl_file = $globalSettings->general->paths->absolute->public .'video/chapters.xsl';
			if (file_exists($chapter_file)) {

				$xh = xslt_create();
				$res = xslt_process($xh, 'arg:xmldata', $xsl_file, NULL, array('xmldata' => file_get_contents($chapter_file)));
				xslt_free($xh);
				preg_match_all('/\[([0-9]*)\|(.*)\]/',$res, $out);
				$chapter_list = array_combine($out[1], $out[2]);

				$this->_smrt->assign('chapter_list', $chapter_list);
			}
		}
	
		$this->_smrt->assign('bsp', $bsp_info);

		$this->assignTemplateGlobals();
		$this->_smrt->display($this->_settings->templates->bsp_movie);

	}

	function print_search($query=array(), $ufs_id=null) {
		$bsp = new businesplan($this->_db);

		if (!is_null($query) || count($query) > 0 || is_numeric($ufs_id)) {

			$cd_state_sql = '';
			if (($_SESSION['session_usr_def_code'] == 'MEM' && !$_SESSION['GATT_USR_CHAMPION_DEAL']) || (!is_numeric($_SESSION['session_usr_id']))) {
				$cd_state_sql = ' AND bsp_champion != 1 ';
			}
			
			if (count($query) > 0 || is_numeric($ufs_id)) {

				if (is_numeric($ufs_id)) {
					$query = $this->_get_ufs($ufs_id);
				}

				if (isset($query['INACTIVE_PLANS']) && $query['INACTIVE_PLANS'] && $_SESSION['session_usr_def_code'] == 'IFP') {
					$bsp_state_list = "'NEW','WAIT','ACCEPT'";
				} else {
					$bsp_state_list = "'ACCEPT'";
				}

				$bsp_ids = null;
				foreach ($query as $fld_code => $fld_search) {

					if (is_array($fld_search)) {
						if (count($fld_search)) {

							foreach ($fld_search as $opt_id) {
								$search_query[$fld_code][$opt_id] = 'on';
							}

							$sql = "SELECT v1.val_bsp_id as bsp_id, bsp_state, v1.val_version, max(v2.val_version) as current_version
									FROM ibp_values AS v1, ibp_val_options
									LEFT JOIN ibp_values AS v2 ON v2.val_fld_id = v1.val_fld_id AND v2.val_bsp_id = v1.val_bsp_id AND v2.val_version_state = 'ACCEPT'
									INNER JOIN ibp_businessplan ON bsp_id = v1.val_bsp_id AND bsp_state IN (".$bsp_state_list.")
									WHERE v1.val_id = vop_val_id
									AND vop_opt_id IN (".implode(',', $fld_search).")
									". $cd_state_sql ." 
									GROUP BY v1.val_id
									HAVING v1.val_version = current_version";
							$rs = $this->_db->query($sql);
						}
					} else {
						
						if ($fld_code == 'CHAMPIONDEALS') {

							$search_query[$fld_code] = 'on';
							$sql = "SELECT bsp_id FROM ibp_businessplan WHERE bsp_champion = 1 AND bsp_state IN (".$bsp_state_list.")";
							$rs = $this->_db->query($sql);

						} elseif ($fld_code == 'INACTIVE_PLANS') {

							$search_query[$fld_code] = 'on';
							$sql = "SELECT bsp_id FROM ibp_businessplan WHERE bsp_state IN (".$bsp_state_list.")";
							$rs = $this->_db->query($sql);

						}
					}

					if ($rs) {

						if (is_array($bsp_ids)) {
							$bsp_ids = array_intersect($bsp_ids, array_keys(rs2arr($rs, 'bsp_id')));
						} else {
							$bsp_ids = array_keys(rs2arr($rs, 'bsp_id'));
						}
					}
				}

			} elseif (!is_null($query)) {
				
				$rs = $this->query("SELECT bsp_id FROM ibp_businessplan WHERE bsp_state = 'ACCEPT' ". $cd_state_sql);
				$bsp_ids = array_keys(rs2arr($rs, 'bsp_id'));

			}


			$search_result = array	(	'hits'			=> count($bsp_ids)
									,	'search_query'	=> $search_query
									);
		}

		if (count($bsp_ids) > 0) {

			$this->get_bsp_info($search_result['list'], $bsp_ids);

		} else {

		}


		$this->_smrt->assign('search_result', $search_result);


		$this->_smrt->assign('ufs_list', $this->_get_ufs_list());

		$this->_smrt->assign('search_form',
								array (		'country'	=> $bsp->get_options_by_code('COUNTRY')
										,	'industry'	=> $bsp->get_options_by_code('INDUSTRY', array('f1.opt_parent_id IS NULL'))
										,	'capital'	=> $bsp->get_options_by_code('CAPITAL_REQUIRED')
										,	'reason'	=> $bsp->get_options_by_code('REASON')
								)
							);



		$this->assignTemplateGlobals();
		$this->_smrt->display($this->_settings->templates->bsp_search);

	}

	function print_request_contact($bsp_id, $confirm=false) {
		if (!isset($_SESSION['session_usr_id']) || !is_numeric($_SESSION['session_usr_id'])) return false;

		$this->get_bsp_info($bsp, $bsp_id);
		$user_state = $this->_get_user_level($bsp_id);
		if ($user_state['has_contact']) {
		
			$this->_smrt->assign('request_exists', 1);

		} elseif ($user_state['has_pending_contact']) {

			$this->_smrt->assign('request_pending', 1);

		} elseif ($user_state['is_owner']) {

			$this->_smrt->assign('is_owner', 1);

		}


		if ($confirm && !$user_state['has_contact'] && !$user_state['has_pending_contact']) {
			
			$sql = "INSERT INTO ibp_bp_repository SET
						rep_bsp_id	= ".$bsp_id."
					,	rep_usr_id	= ".$_SESSION['session_usr_id']."
					,	rep_state	= 'NEW'
					,	rep_createdate = NOW()";

			$this->_db->execute($sql);		
		
			// send an email
			$err = $this->_tcc->doCall("SEND_EMAIL", 
										array(	'code'		=> 'REQ_CTCT'
											,	'org_id'	=> $this->_variables->public->org_id
											,	'usr_id'	=> null
											,	'lng_code'	=> $this->_variables->public->lng_code
											,	'variables'	=> array(
																 'USERNAME'	 => $_SESSION['session_usr_greeting']
																,'BSP_TITLE' => $bsp['title']
																)
										),
										$call_result
									);

			if ($bsp['champion']) {
				$err = $this->_tcc->doCall("SEND_EMAIL", 
											array(	'code'		=> 'L3R_LIC'
												,	'org_id'	=> $this->_variables->public->org_id
												,	'usr_id'	=> $_SESSION['session_usr_id']
												,	'lng_code'	=> $this->_variables->public->lng_code
												,	'variables'	=> array(
																	 'USERNAME'	 => $_SESSION['session_usr_greeting']
																	,'BSP_TITLE' => $bsp['title']
																	,'DATE'		 => date('Y m d')
																	)
											),
											$call_result
										);
			}
			
			$this->_smrt->assign('confirmed', 1);
		}


		$this->_smrt->assign('bsp', $bsp);

		$this->assignTemplateGlobals();
		$this->_smrt->display($this->_settings->templates->request_contact);
	}

	function print_bsp_list() {

		switch ($_SESSION['session_usr_def_code']) {

			case 'BPS':
				$sql = "SELECT
							bsp_id
						,	bsp_usr_id
						,	bsp_title
						,	bsp_state
						,	bsp_champion
						,	count(rep_id) as repositories_count
						FROM ibp_businessplan
						LEFT JOIN ibp_bp_repository ON rep_bsp_id = bsp_id AND rep_state = 'ACCEPT'
						WHERE bsp_usr_id = ".$this->_variables->public->usr_id ."
						AND	bsp_state != 'DECLINE'
						GROUP BY bsp_id";

				$plans = array();

				$rs = $this->_db->query($sql);
				while ($r = $rs->row()) {
					if (!$plans[$r['bsp_state']]) $plans[$r['bsp_state']] = array();

					if ($r['repositories_count'] > 0) {
						$r['repositories'] = array();
						$rs_rep = $this->_db->query("SELECT rep_usr_id FROM ibp_bp_repository WHERE rep_bsp_id = ".$r['bsp_id']);
						while (!$rs_rep->EOF()) {
							$r['repositories'][$rs_rep->Row('rep_usr_id')] = $this->_get_user_greeting($rs_rep->Row('rep_usr_id'));
							$rs_rep->moveNext();
						}
						$rs_rep->Close();
					}

					$plans[$r['bsp_state']][] = $r;
					$rs->moveNext();
				}
				$rs->Close();

				$this->_smrt->assign('bsp_list', $plans);
				break;

			case 'IFP':
			case 'MEM':

				$sql = "SELECT
							bsp_id
						,	bsp_usr_id
						,	bsp_title
						,	bsp_champion
						,	!ISNULL(rep_id) bsp_is_rep
						, 	!ISNULL(ufb_bsp_id) bsp_is_fav
						FROM ibp_businessplan
						LEFT JOIN ibp_bp_repository ON rep_bsp_id = bsp_id AND rep_usr_id = ".$_SESSION['session_usr_id']." AND rep_state = 'ACCEPT'
						LEFT JOIN ibp_usr_fav_bp ON ufb_bsp_id = bsp_id AND ufb_usr_id = ".$_SESSION['session_usr_id']."
						WHERE bsp_state = 'ACCEPT'
						AND (!ISNULL(rep_id) OR !ISNULL(ufb_bsp_id))";
				$rs = $this->_db->query($sql);
				$plans = array();

				$rs = $this->_db->query($sql);
				while ($r = $rs->row()) {
					if ($r['bsp_is_rep']) $plans['rep'][] = $r;
					if ($r['bsp_is_fav']) $plans['fav'][] = $r;

					$rs->moveNext();
				}
				$rs->Close();

				$this->_smrt->assign('bsp_list', $plans);

				break;

		}


		$this->assignTemplateGlobals();
		$this->_smrt->display($this->_settings->templates->bsp_list);

	}

	function print_bsp_search_queries() {
	
		$this->_smrt->assign('ufs_list', $this->_get_ufs_list());

		$this->assignTemplateGlobals();
		$this->_smrt->display($this->_settings->templates->bsp_search_queries);

	}

	function delete_bsp_search_queries($ufs_id) {
		if (!isset($_SESSION['session_usr_id']) || !is_numeric($_SESSION['session_usr_id'])) return false;

		$sql = "DELETE FROM ibp_usr_fav_search 
				WHERE ufs_usr_id = ".$_SESSION['session_usr_id']."
				AND ufs_id = ".$ufs_id;
		$this->_db->execute($sql);
		
	}

	function print_contactbox($bsp_id, $usr_id) {
		if (!isset($_SESSION['session_usr_id']) || !is_numeric($_SESSION['session_usr_id'])) return false;
		if (!is_numeric($bsp_id)) return;

		if (is_numeric($usr_id)) {
			$rep_usr_id = $usr_id;
		} else {
			$rep_usr_id = $_SESSION['session_usr_id'];
		}


		$sql = "SELECT rep_id
				FROM ibp_bp_repository
				".( is_numeric($usr_id) ? (
					' INNER JOIN ibp_businessplan ON bsp_id = '.$bsp_id.' AND bsp_usr_id = '.$_SESSION['session_usr_id']) : '')."
				WHERE rep_bsp_id = ".$bsp_id."
				AND rep_usr_id = ".$rep_usr_id." 
				AND rep_state = 'ACCEPT'";
		
		$rs = $this->_db->query($sql);
		if (!is_numeric($rs->Row('rep_id'))) return; #no valid repository found
		$rep_id = $rs->Row('rep_id');

		if (isset($_REQUEST['btn_save']) && $_REQUEST['btn_save'] == 'pressed') {
		
			if (strlen($_REQUEST['rep_new_subject']) > 0 && strlen($_REQUEST['rep_new_body']) > 0) {
			
				$create_date = time();

				$sql = "INSERT INTO ibp_bp_rep_messages SET
							msg_usr_id		= ". $_SESSION['session_usr_id'] ."
						,	msg_rep_id		= ".$rep_id ."
						,	msg_subject		= '".mysql_escape_string($_REQUEST['rep_new_subject'])."'
						,	msg_body		= '".mysql_escape_string($_REQUEST['rep_new_body'])."'
						,	msg_createdate	= FROM_UNIXTIME(".$create_date.")";
				$this->_db->execute($sql);

				if (is_uploaded_file($_FILES['rep_new_file']['tmp_name'])) {
					
					$sql = "INSERT INTO ibp_files SET
								fil_bsp_id		= ".$bsp_id."
							,	fil_fld_id		= NULL
							,	fil_rep_id		= ".$rep_id."
							,	fil_rep_usr_id	= ". $_SESSION['session_usr_id'] ."
							,	fil_filename	= '".mysql_escape_string($_FILES['rep_new_file']['name'])."'
							,	fil_data		= '".addslashes(file_get_contents($_FILES['rep_new_file']['tmp_name']))."'
							,	fil_mime		= '".mysql_escape_string($_FILES['rep_new_file']['type'])."'
							,	fil_size		= ".$_FILES['rep_new_file']['size']."
							,	fil_createdate	= FROM_UNIXTIME(".($create_date+5).")";
					$this->_db->execute($sql);
				}

			}

		}

		$this->get_bsp_info($bsp, $bsp_id);
		$this->_smrt->assign('bsp', $bsp);


		$contactbox = array();

		//--- first get all messages
		$sql = "SELECT
					rep_id
				,	msg_id
				,	msg_usr_id
				,	msg_subject	
				,	msg_body
				,	DATE_FORMAT(msg_createdate, '%d-%m-%Y %H:%i') as msg_createdate
				,	UNIX_TIMESTAMP(msg_createdate) as ts_date
				FROM ibp_bp_rep_messages
				INNER JOIN ibp_bp_repository ON msg_rep_id = rep_id AND rep_bsp_id = ". $bsp_id ." AND rep_usr_id = ". $rep_usr_id ." AND rep_state = 'ACCEPT'";
	
		$rs = $this->_db->query($sql);
		while ($r = $rs->row()) {
			$r['usr_greeting'] = $this->_get_user_greeting($r['msg_usr_id']);
			$contactbox[] = $r;

			$rs->moveNext();
		}
		$rs->Close();
					
		//--- And now get all documents
		$sql = "SELECT
					rep_id
				,	fil_rep_usr_id 
				,	fil_id
				,	fil_title
				,	fil_filename
				,	fil_mime
				,	fil_size
				,	DATE_FORMAT(fil_createdate, '%d-%m-%Y %H:%i') as fil_createdate
				,	UNIX_TIMESTAMP(fil_createdate) as ts_date
				FROM ibp_files
				INNER JOIN ibp_bp_repository ON fil_rep_id = rep_id AND rep_bsp_id = ". $bsp_id ." AND rep_usr_id = ". $rep_usr_id ." AND rep_state = 'ACCEPT'";

		$rs = $this->_db->query($sql);
		while ($r = $rs->row()) {
			$r['usr_greeting'] = $this->_get_user_greeting($r['fil_rep_usr_id']);
			$contactbox[] = $r;
			$rs->moveNext();
		}
		$rs->Close();

	
		$contactbox = aasort($contactbox, 'ts_date');

//		echo "<pre>";
//		print_r($contactbox);
//		echo "</pre>";

		$this->_smrt->assign('contactbox', $contactbox);

		$this->assignTemplateGlobals();
		$this->_smrt->display($this->_settings->templates->contactbox);	
	}

	function delete_rep_msg($msg_id) {
		if (!isset($_SESSION['session_usr_id']) || !is_numeric($_SESSION['session_usr_id'])) return false;
		
		$sql = "DELETE FROM ibp_bp_rep_messages WHERE msg_id = ". $msg_id ." AND msg_usr_id = ".$_SESSION['session_usr_id'];
		$this->_db->execute($sql);

	}

	function delete_rep_fil($fil_id) {
		if (!isset($_SESSION['session_usr_id']) || !is_numeric($_SESSION['session_usr_id'])) return false;

		$sql = "DELETE FROM ibp_files WHERE fil_id = ". $msg_id ." AND fil_rep_usr_id = ".$_SESSION['session_usr_id'];
		$this->_db->execute($sql);
	
	}

	function save_ufs($label, $searchfields) {

		$sql = "INSERT INTO ibp_usr_fav_search SET
					ufs_usr_id			= ".$_SESSION['session_usr_id']."
				,	ufs_search_label	= '".mysql_escape_string($label)."'";
		$this->_db->execute($sql);
		$ufs_id = $this->_db->lastInsertId();

		if ($ufs_id) {
			$values = array();

			foreach ($searchfields as $fld_code => $fld_value) {

				if (is_array($fld_value)) {
					$values[] = "(".$ufs_id.",'".$fld_code."','".implode(',',$fld_value)."')";
				} else {
					$values[] = "(".$ufs_id.",'".$fld_code."','".$fld_value."')";
				}

			}
			if ($values) {
				$sql = "INSERT INTO ibp_usr_fav_search_fields (uff_ufs_id, uff_fld_code, uff_value) VALUES ". implode(', ', $values);
				$this->_db->execute($sql);
			}

		}
	}

	function delete_bsp($bsp_id) {
		if (!isset($_SESSION['session_usr_id']) || !is_numeric($_SESSION['session_usr_id'])) return false;
		if (!is_numeric($bsp_id)) return;
		if ($_SESSION['session_usr_def_code'] != 'BPS') return;
		

		$this->get_bsp_info($bsp, $bsp_id);

		if ($bsp['state'] == 'ACCEPT') {
			//-- send e-mail to IFEX

			$err = $this->_tcc->doCall("SEND_EMAIL", 
										array(	'code'		=> 'BSP_DEL'
											,	'org_id'	=> $this->_variables->public->org_id
											,	'lng_code'	=> $this->_variables->public->lng_code
											,	'variables'	=> array(
																	'BSP_TITLE' => $bsp['title']
																,	'USR_NAME'	=> $_SESSION['session_usr_greeting']
																)
										),
										$call_result
									);

		}

		$this->_db->execute("UPDATE ibp_businessplan SET bsp_state = 'DECLINE' WHERE bsp_id = ".$bsp_id." AND bsp_usr_id = ".$_SESSION['session_usr_id']);
	
	}

	function _get_ufs($ufs_id) {
		if (!isset($_SESSION['session_usr_id']) || !is_numeric($_SESSION['session_usr_id'])) return false;

		$sql = "SELECT uff_fld_code, fld_type, uff_value
				FROM ibp_usr_fav_search_fields, ibp_usr_fav_search 
				LEFT JOIN ibp_fields ON fld_code = uff_fld_code
				WHERE
					uff_ufs_id = ufs_id
				AND	ufs_usr_id = ".$_SESSION['session_usr_id']."
				AND ufs_id = ".$ufs_id;

		$ufs = array();

		$rs = $this->_db->query($sql);
		while ($r = $rs->Row()) {

			if ($r['fld_type'] == 'rdo' || $r['fld_type'] == 'chk2' || $r['fld_type'] == 'olv' || $r['fld_type'] == 'cmb') {
				$value = explode(',',$r['uff_value']);
			} else {
				$value = $r['uff_value'];
			}
			$ufs[$r['uff_fld_code']] = $value;

			$rs->moveNext();
		}

		return $ufs;

	}

	function _get_ufs_list() {
		if (!isset($_SESSION['session_usr_id']) || !is_numeric($_SESSION['session_usr_id'])) return false;

		$sql = "SELECT ufs_id, ufs_search_label
				FROM ibp_usr_fav_search
				WHERE ufs_usr_id = ".$_SESSION['session_usr_id']."
				ORDER BY ufs_search_label";
		$rs = $this->_db->query($sql);
		return rs2arr($rs, 'ufs_id');
	}

	function save_bsp($bsp_id, $data, $data_tree=null) {
		$this->_bsp = new businesplan($this->_db, $bsp_id);

		if (!is_numeric($bsp_id) || $bsp_id < 1) {
			$this->_bsp->create_new();
		}

		$this->_bsp->save($data, $data_tree);
	}

	function do_download($bsp_id, $fil_id) {
		$this->_bsp = new businesplan($this->_db, $bsp_id);
		$this->_bsp->print_download($fil_id);

	}

	function set_fav($bsp_id, $state) {
		if (!isset($_SESSION['session_usr_id']) || !is_numeric($_SESSION['session_usr_id']) || !is_numeric($bsp_id)) {
			return;
		}

		if ($state) {
			$sql = "REPLACE INTO ibp_usr_fav_bp SET ufb_usr_id = ".$_SESSION['session_usr_id'].", ufb_bsp_id = ".$bsp_id;
		} else {
			$sql = "DELETE FROM ibp_usr_fav_bp WHERE ufb_usr_id = ".$_SESSION['session_usr_id']." AND ufb_bsp_id = ".$bsp_id;
		}
		$this->_db->execute($sql);
	}

	function set_bsp_state ($bsp_id, $state) {
		if (!isset($_SESSION['session_usr_id']) || !is_numeric($_SESSION['session_usr_id'])) {
			return;
		}

		$this->get_bsp_info($bsp, $bsp_id);
		
		//error_log("set_bsp_state ($bsp_id, $state) --> ". $bsp['state']);

		if ($bsp['state'] == 'NEW' && $state == 'WAIT') {

			$err = $this->_tcc->doCall("SEND_EMAIL", 
										array(	'code'		=> 'BSP_REC'
											,	'org_id'	=> $this->_variables->public->org_id
											,	'usr_id'	=> $_SESSION['session_usr_id']
											,	'lng_code'	=> $this->_variables->public->lng_code
											,	'variables'	=> array(
																'BSP_TITLE' => $bsp['title']
																)
										),
										$call_result
									);

		} elseif ($bsp['state'] == 'ACCEPT' && ($state == 'WAIT' || $state == 'CHANGED') && $bsp['champion']) {
			if (!isset($_SESSION['sess_bsp_change_mail_sent'][$bsp_id]) || $_SESSION['sess_bsp_change_mail_sent'][$bsp_id] > (time()+3600)) {

				$err = $this->_tcc->doCall("SEND_EMAIL", 
											array(	'code'		=> 'BSP_CHNG'
												,	'org_id'	=> $this->_variables->public->org_id
												,	'usr_id'	=> null
												,	'lng_code'	=> $this->_variables->public->lng_code
												,	'variables'	=> array(
																	'BSP_TITLE' => $bsp['title']
																	)
											),
											$call_result
										);
				$_SESSION['sess_bsp_change_mail_sent'][$bsp_id] = time();
			}

			return; # do not update bsp_state
		}

		if ($state != 'CHANGED') {

			$sql = "UPDATE ibp_businessplan SET bsp_state = '".$state."'
					WHERE bsp_id = ".$bsp_id." AND bsp_usr_id = ".$_SESSION['session_usr_id'];
			$this->_db->execute($sql);
		}
	}

	function _get_user_level($bsp_id) {

		$return = array(
				'level'					=> 1
			,	'is_owner'				=> false
			,	'has_contact'			=> false
			,	'has_pending_contact'	=> false
			,	'is_favorite'			=> false
		);

		if (!isset($_SESSION['session_usr_id']) || !is_numeric($_SESSION['session_usr_id'])) {
			return $return;
		} else {

			$sql = "SELECT
						(bsp_usr_id = ".$_SESSION['session_usr_id']." ) AS is_owner
					,	(r1.rep_usr_id = ".$_SESSION['session_usr_id']." ) AS has_contact
					,	(r2.rep_usr_id = ".$_SESSION['session_usr_id']." ) AS has_pending_contact
					,	(ufb_usr_id = ".$_SESSION['session_usr_id']." ) AS is_favorite
					FROM ibp_businessplan
					LEFT JOIN ibp_bp_repository r1 ON r1.rep_bsp_id = bsp_id AND r1.rep_usr_id = ".$_SESSION['session_usr_id']." AND r1.rep_state = 'ACCEPT'
					LEFT JOIN ibp_bp_repository r2 ON r2.rep_bsp_id = bsp_id AND r2.rep_usr_id = ".$_SESSION['session_usr_id']." AND (r2.rep_state = 'NEW' || r2.rep_state = 'WAIT')
					LEFT JOIN ibp_usr_fav_bp ON ufb_bsp_id = bsp_id AND ufb_usr_id = ".$_SESSION['session_usr_id']."
					WHERE bsp_id = ".$bsp_id;
			$rs = $this->_db->query($sql);
			if ($rs->Row('is_owner') || $rs->Row('has_contact') || $_SESSION['session_usr_def_code'] == 'IFP') {
				$return['level'] = 3;
			} else {
				$return['level'] = 2;
			}

			$return['is_owner']		= $rs->row('is_owner');
			$return['has_contact']	= $rs->row('has_contact');
			$return['has_pending_contact']	= $rs->row('has_pending_contact');
			$return['is_favorite']	= $rs->row('is_favorite');

			return $return;

		}
	}

	function _get_user_greeting($usr_id) {
		global $g_obj_i3a;
		if (is_numeric($usr_id)) {
			return $g_obj_i3a->getUserGreeting($usr_id, false);
		}
	}

}


function tpl_generate_table($vars, &$smarty) {

	echo '<table cellpadding="2" style="border: 1px solid gray;width: 90%">';
	if ($vars['code'] == 'TBL_CAP_USE') {
		echo '<tr><th style="text-align:left;">Category</th><th style="text-align:right;">Amount (&euro; x 1000)</th><th style="text-align:right;">Percentage</th></tr>';
	} elseif ($vars['code'] == 'TBL_INCOME') {
		echo '<tr><th>(€ x 1000)</th><th style="text-align:right;">2005</th><th style="text-align:right;">2006</th><th style="text-align:right;">2007</th><th style="text-align:right;">2008</th><th style="text-align:right;">2009</th></tr>';
	}

	$cur_row = '';
	foreach ($smarty->_tpl_vars['sheet']['data'][$vars['group']]['fields'] as $fld) {

		if ($fld['fld_code'] && strpos($fld['fld_code'], $vars['code']) !== false) {
			$row = substr($fld['fld_code'], -1);
			$col = substr($fld['fld_code'], -2, 1);

			if ($row != $cur_row) {
				if ($cur_row) echo '</tr>';
				echo '<tr>';
				echo '<td>'.$fld['fld_desc'].'</td>';
					 
				$cur_row = $row;
			}
			echo '<td '.($fld['fld_type']=='num' ? 'style="text-align:right;"' : '').'>';
			echo $fld['current_version']['value'];
			echo '</td>';
		}
		
	}

	echo '</table>';


}


?>