<?php
	/**************************************************************************\
	* phpGroupWare - todo list                                                 *
	* http://www.phpgroupware.org                                              *
	* Written by Joseph Engo <jengo@phpgroupware.org>                          *
	* --------------------------------------------                             *
	*  This program is free software; you can redistribute it and/or modify it *
	*  under the terms of the GNU General Public License as published by the   *
	*  Free Software Foundation; either version 2 of the License, or (at your  *
	*  option) any later version.                                              *
	\**************************************************************************/

	/* $Id: index.php,v 1.63.2.3 2001/06/25 01:32:38 skeeter Exp $ */

	$phpgw_info['flags'] = array(
		'currentapp'              => 'todo', 
		'enable_nextmatchs_class' => True,
		'enable_categories_class' => True
	);
	include('../header.inc.php');

	$phpgw->todo = createobject('todo.todo');
	$db3 = $phpgw->db;

	$db2 = $phpgw->db;
	$phpgw->template = new Template($phpgw->common->get_tpl_dir('todo'));
	$phpgw->template->set_file(array(
		'todo_list_t' => 'list.tpl'
	));
	$phpgw->template->set_block('todo_list_t','todo_list','list');

	$grants = $phpgw->acl->get_grants('todo');
	$grants[$phpgw_info['user']['account_id']] = PHPGW_ACL_READ + PHPGW_ACL_ADD + PHPGW_ACL_EDIT + PHPGW_ACL_DELETE;

	$common_hidden_vars =
			  '<input type="hidden" name="sort" value="' . $sort . '">'
			. '<input type="hidden" name="order" value="' . $order . '">'
			. '<input type="hidden" name="query" value="' . $query . '">'
			. '<input type="hidden" name="start" value="' . $start . '">'
			. '<input type="hidden" name="filter" value="' . $filter . '">'
			. '<input type="hidden" name="cat_id" value="' . $cat_id . '">';

	if ($action == 'sp')
	{
		$common_hidden_vars
			.= '<input type="hidden" name="action" value="sp">'
			.  '<input type="hidden" name="todo_id" value="' . $todo_id . '">';
	}

	$phpgw->template->set_var(lang_action,lang('todo list'));
	$phpgw->template->set_var(actionurl,$phpgw->link('/todo/add.php'));
	$phpgw->template->set_var('cat_form',$phpgw->link('/todo/index.php'));
	$phpgw->template->set_var('lang_category',lang('Category'));
	$phpgw->template->set_var('lang_all',lang('All'));
	$phpgw->template->set_var('lang_select',lang('Select'));
	$phpgw->template->set_var('categories',$phpgw->categories->formated_list('select','all',$cat_id,'True'));
	$phpgw->template->set_var(common_hidden_vars,$common_hidden_vars);

	// ===========================================
	// list header variable template-declarations
	// ===========================================
	$phpgw->template->set_var(th_bg,$phpgw_info['theme']['th_bg']);
	$phpgw->template->set_var(sort_status,$phpgw->nextmatchs->show_sort_order($sort,'todo_status',$order,'/todo/index.php',lang('Status')));
	$phpgw->template->set_var(sort_urgency,$phpgw->nextmatchs->show_sort_order($sort,'todo_pri',$order,'/todo/index.php',lang('Urgency')));
	$phpgw->template->set_var(sort_todo,$phpgw->nextmatchs->show_sort_order($sort,'todo_des',$order,'/todo/index.php',lang('todo')));
	$phpgw->template->set_var(sort_lastupdated,$phpgw->nextmatchs->show_sort_order($sort,'todo_startdate',$order,'/todo/index.php',lang('start date')));
	$phpgw->template->set_var(sort_datedue,$phpgw->nextmatchs->show_sort_order($sort,'todo_enddate',$order,'/todo/index.php',lang('end date')));
	$phpgw->template->set_var(sort_owner,$phpgw->nextmatchs->show_sort_order($sort,'todo_owner',$order,'/todo/index.php',lang('created by')));
	$phpgw->template->set_var(h_lang_sub,lang('Sub'));
	$phpgw->template->set_var(h_lang_edit,lang('Edit'));
	$phpgw->template->set_var(h_lang_delete,lang('Delete'));
	// -------------- end header declaration -----------------

	if (! $start)
	{
		$start = 0;
	}

	if ($order)
	{
		$ordermethod = 'order by ' . $order . ' ' . $sort;
	}
	else
	{
		$ordermethod = 'order by todo_datecreated asc';
	}

	if (! $filter)
	{
		$filter = 'none';
	}

	if ($filter != 'private')
	{
		$filtermethod = "( todo_owner=" . $phpgw_info['user']['account_id'];
		if (is_array($grants))
		{
			while (list($user) = each($grants))
			{
				$public_user_list[] = $user;
			}
			reset($public_user_list);
			$filtermethod .= " OR (todo_access='public' AND todo_owner in(" . implode(',',$public_user_list) . ")))";
		}
		else
		{
			$filtermethod .= ' )';
		}
	}
	else
	{
		$filtermethod = ' todo_owner=' . $phpgw_info['user']['account_id'] . ' ';
	}

	if ($cat_id)
	{
		$filtermethod .= " AND todo_cat='$cat_id' "; 
	}

	// ------------------ If searched within list ----------------------------

	if ($query)
	{
		if ($action != 'sp')
		{
			// ====================================
			// count list items when project list
			// ====================================
			$phpgw->db->query("select count(*) from phpgw_todo where $filtermethod and todo_des "
				. "like '%$query%'",__LINE__,__FILE__);
		}
		else
		{
			// ======================================
			// count list items when subproject list
			// ======================================
			$phpgw->db->query("select count(*) from phpgw_todo where $filtermethod and todo_des "
				. "like '%$query%' AND todo_id_parent=$todo_id",__LINE__,__FILE__);
		}
	}
	else
	{
		// ------------------ If NOT searched within list ----------------------------
		if ($action != 'sp')
		{
			// ====================================
			// count list items when project list
			// ====================================
			$phpgw->db->query("select count(*) from phpgw_todo where todo_id_parent=0 AND $filtermethod",__LINE__,__FILE__);
		}
		else
		{
			// ======================================
			// count list items when subproject list
			// ======================================
			$phpgw->db->query("select count(*) from phpgw_todo where todo_id_parent=$todo_id AND $filtermethod",__LINE__,__FILE__);
		}
	}

	$phpgw->db->next_record();
	$total = $phpgw->db->f(0);

	if ($total == 1)
	{
		$phpgw->template->set_var(total_matchs,lang('your search returned 1 match'));
	}
	else
	{
		$phpgw->template->set_var(total_matchs,lang('your search returned x matchs',$total));
	}

	if ($total > $phpgw_info['user']['preferences']['common']['maxmatchs'])
	{
		$total_matchs = '<br>' . lang('showing x - x of x',($start + 1),
			($start + $phpgw_info['user']['preferences']['common']['maxmatchs']),$total);
	}
	else
	{
		$total_matchs = '<br>' . lang('showing x',$total);
	}

	$phpgw->template->set_var('total_matchs',$total_matchs);

	// ==========================================
	// project description if subprojectlist
	// ==========================================
	if ($action == 'sp')
	{
		$phpgw->db->query("select * from phpgw_todo where todo_id='$todo_id'",__LINE__,__FILE__);
		$phpgw->db->next_record();

		$accounts = createobject('phpgwapi.accounts',$phpgw->db->f('todo_owner'));
		$accounts->db = $db3;
		$accounts->read_repository();

		$ownerout = $phpgw->common->display_fullname($accounts->data['account_lid'],$accounts->data['firstname'],$accounts->data['lastname']);

		switch ($phpgw->db->f('todo_pri'))
		{
			case 1: $pri = lang('Low'); break;
			case 2: $pri = '<b>' . lang('normal') . '</b>'; break;
			case 3: $pri = '<font color="CC0000">' . lang('high') . '</font>'; break;
		}

		$phpgw->template->set_var('lang_pdheader',lang('Displaying Subprojects of following project'));
		$phpgw->template->set_var('lang_pdproject',lang('Project Description'));
		$phpgw->template->set_var('lang_project', $phpgw->strip_html($phpgw->db->f('todo_des')));
		$phpgw->template->set_var('lang_pdurgency',lang('Urgency'));
		$phpgw->template->set_var('lang_urgency', $pri);
		$phpgw->template->set_var('lang_pdcreated',lang('created by'));
		$phpgw->template->set_var('lang_created',$ownerout);
		$phpgw->template->set_var('lang_pdstatus',lang('Status'));
		$phpgw->template->set_var('lang_status',$phpgw->db->f('todo_status') . '%');
	}
	else
	{
		$phpgw->template->set_block('todo_list_t','projdetails','projdetailshandle');
	}

	// ===========================================
	// nextmatch variable template-declarations
	// ===========================================
	$_query = urlencode(stripslashes($query));
	$next_matchs = $phpgw->nextmatchs->show_tpl('/todo/index.php',$start,$total,
			"order=$order&filter=$filter&sort="
			. "$sort&query=$_query&action=$action&todo_id=$todo_id&cat_id=$cat_id",'95%',$phpgw_info['theme']['th_bg']);
	$phpgw->template->set_var(next_matchs,$next_matchs);
	// ---------- end nextmatch template --------------------

	$limit = $phpgw->db->limit($start);

	if ($action == sp)
	{
		if ($query)
		{
			$phpgw->db->query("SELECT * FROM phpgw_todo WHERE $filtermethod AND "
				. "todo_id_parent=$todo_id AND todo_des like '%$query%' "
				. "$ordermethod $limit",__LINE__,__FILE__);
		}
		else
		{
			$phpgw->db->query("SELECT * from phpgw_todo WHERE todo_id_parent=$todo_id AND "
				. "$filtermethod $ordermethod $limit",__LINE__,__FILE__);
		}
	}
	else
	{
		if ($query)
		{
			$phpgw->db->query("SELECT * FROM phpgw_todo WHERE $filtermethod AND "
				. "todo_id_parent=0 AND todo_des like '%$query%' "
				. "$ordermethod $limit",__LINE__,__FILE__);
		}
		else
		{
			$phpgw->db->query("SELECT * FROM phpgw_todo WHERE todo_id_parent=0 AND "
				. "$filtermethod $ordermethod $limit",__LINE__,__FILE__);
		}
	}

	while ($phpgw->db->next_record())
	{
		// Cache the results for preformance
		if (! $cached[$phpgw->db->f('todo_owner')])
		{
			$accounts = createobject('phpgwapi.accounts',$phpgw->db->f('todo_owner'));
			$accounts->db = $db3;
			$accounts->read_repository();

			$cached[$accounts->data['account_id']] = True;

			$cached_data[$accounts->data['account_id']]['account_lid'] = $accounts->data['account_lid'];
			$cached_data[$accounts->data['account_id']]['firstname']   = $accounts->data['firstname'];
			$cached_data[$accounts->data['account_id']]['lastname']    = $accounts->data['lastname'];
		}

		// ========================================
		// check if actual project has subprojects
		// ========================================
		$db2->query("select count(*) as cnt from phpgw_todo where todo_id_parent=" .$phpgw->db->f('todo_id'),__LINE__,__FILE__);
		$db2->next_record();
		if ($db2->f('cnt') > 0)
		{
			$subproact = 1;
		}
		else
		{
			$subproact = 0;
		}
		// -----------------------------------------

		$phpgw->nextmatchs->template_alternate_row_color(&$phpgw->template);

		$des = $phpgw->db->f('todo_des');

		if ($des)
		{
			$des = $phpgw->strip_html($des);
		}
		else
		{
			$des = '&nbsp;';
		}

		switch ($phpgw->db->f('todo_pri'))
		{
			case 1: $pri = lang('Low'); break;
			case 2: $pri = '<b>' . lang('normal') . '</b>'; break;
			case 3: $pri = '<font color="CC0000">' . lang('high') . '</font>'; break;
		}

		if ($phpgw->db->f('todo_enddate') == 0)
		{
			$datedueout = '&nbsp;';
		}
		else
		{
			$month = $phpgw->common->show_date(time(),'n');
			$day   = $phpgw->common->show_date(time(),'d');
			$year  = $phpgw->common->show_date(time(),'Y');

			$datedue = $datedue + (60*60) * $phpgw_info['user']['preferences']['common']['tz_offset'];

			if (mktime(2,0,0,$month,$day,$year) >= $phpgw->db->f('todo_enddate'))
			{
				$datedueout =  '<font color="CC0000">';
			}
			else
			{
				$datedueout = '';
			}

			$datedueout .= $phpgw->common->show_date($phpgw->db->f('todo_enddate'),$phpgw_info['user']['preferences']['common']['dateformat']);

			if (mktime(2,0,0,$month,$day,$year) >= $phpgw->db->f('todo_enddate'))
			{
				$datedueout .= '</font>';
			}
		}

		$ownerout = $phpgw->strip_html($cached_data[$phpgw->db->f('todo_owner')]['account_lid']
			. ' <' . $cached_data[$phpgw->db->f('todo_owner')]['firstname'] . ' '
			. $cached_data[$phpgw->db->f('todo_owner')]['lastname'] . '>');

		// ============================================
		// template declaration for list records
		// ============================================
		$phpgw->template->set_var(array(
			'status'      => $phpgw->db->f('todo_status'),
			'pri'         => $pri,
			'des'         => $des,
			'datecreated' => $phpgw->common->show_date($phpgw->db->f('todo_startdate'),$phpgw_info['user']['preferences']['common']['dateformat']),
			'datedue'     => $datedueout,
			'owner'       => $ownerout
		));


		if ($phpgw->todo->check_perms($grants[$phpgw->db->f('todo_owner')],PHPGW_ACL_EDIT))
		{
			$phpgw->template->set_var('edit','<a href="' . $phpgw->link('/todo/edit.php','todo_id=' . $phpgw->db->f('todo_id')
				. '&sort=' . $sort . '&order=' . $order . '&query=' . $_query . '&start=' . $start . '&filter=' . $filter)
				. '">' . lang('Edit') . '</a>');
		}
		else
		{
			$phpgw->template->set_var('edit','');
		}

		if ($phpgw->todo->check_perms($grants[$phpgw->db->f('todo_owner')],PHPGW_ACL_DELETE))
		{
			$phpgw->template->set_var('delete','<a href="' . $phpgw->link('/todo/delete.php','todo_id=' . $phpgw->db->f('todo_id')
				. '&sort=' . $sort . '&order=' . $order . '&query=' . $_query . '&start=' . $start . '&filter=' . $filter . '&cat_id=' . $cat_id)
				. '">' . lang('Delete') . '</a>');
		}
		else
		{
			$phpgw->template->set_var('delete','');
		}


		// ================================================================================
		// you can only create one subproject per project, no subprojects of subprojects
		// ================================================================================
		if ($action != 'sp')
		{
			if ($phpgw->todo->check_perms($grants[$phpgw->db->f('todo_owner')],PHPGW_ACL_ADD))
			{
				$phpgw->template->set_var('subadd', '<a href="' . $phpgw->link('/todo/add.php','todo_id=' . $phpgw->db->f('todo_id')
					. '&filter=' . $filter . '&action=sp') . '">' . lang('Add Sub') . '</a>');
			}
		}
		else
		{
			$phpgw->template->set_var('subadd', '');
		} 

		// ================================================================================
		// only display "viewsub" if there are subprojects available for current project
		// ================================================================================
		if ($subproact == 1)
		{
			$phpgw->template->set_var('viewsub', $phpgw->common->check_owner($phpgw->db->f('todo_owner'),'/todo/index.php',
				'<br>' . lang('ViewSub'),"todo_id=" . $phpgw->db->f("todo_id") . "&filter=$filter" . "&action=sp"));
		}
		else
		{
			$phpgw->template->set_var('viewsub', '');
		} 
		$phpgw->template->parse('list','todo_list',True);
		// -------------- end record declaration ------------------------
	}

	// =========================================================
	// back2project list href declaration for subproject list
	// =========================================================

	if ($action == 'sp')
	{
		$phpgw->template->set_var('lang_back2projects', '<br>' . $phpgw->common->check_owner($phpgw_info["user"]["account_id"],"/todo/index.php",
			lang('Back to Projectlist'),"filter=$filter"));
	}

	// get actual date and year for matrixview arguments
	$year = date('Y');
	$month = date('m');
	$phpgw->template->set_var('lang_matrixviewhref', '<br>' . $phpgw->common->check_owner($phpgw_info["user"]["account_id"],"/todo/graphview.php",
		lang('View Matrix of actual Month'),"month=$month&year=$year&filter=$filter"));
	// ============================================
	// template declaration for Add Form
	// ============================================

	$phpgw->template->set_var(lang_add,lang('Add'));
	$phpgw->template->pfp('out','todo_list_t',true);

	// -------------- end Add form declaration ------------------------

	$phpgw->common->phpgw_footer();
?>
