<?php
/* $Id: index.php,v 1.71 2006/04/27 11:44:17 k-fish Exp $ */

$myEnv["module"] = "projects";
$myEnv["output"] = "html";

include("../../config.inc.php");
include(INCLUDEPATH . "container.inc.php");
revisionInit("\$Revision: 1.71 $", __FILE__);

if($_SERVER['REQUEST_METHOD'] == 'POST') {
    switch($_POST['obj']){
        case 'project':
	    switch($_POST['action']) {
	    case 'create':
		$id = createProject($_POST);
		redirect(ROOTURL.'modules/projects/index.php?obj=project&view=details&pid='.$id.'&'.SID);
		break;
	    case 'edit':
		editProject($_POST);
		redirect(ROOTURL.'modules/projects/index.php?obj=project&view=details&pid='.$_POST['pid'].'&'.SID);
		break;
	    case 'delete':
		if(isset($_POST['confirmation_yes']))
		    deleteProject($_POST['itemid']);
		redirect(ROOTURL.'modules/projects/index.php?obj=project&view=active&'.SID);
		break;
	    }
	break;
	case 'task':
	    switch($_POST['action']) {
	    case 'create':
		createTask($_POST);
		redirect(ROOTURL.'modules/projects/index.php?obj=project&view=details&pid='.$_POST['pid'].'&'.SID);
		break;
	    case 'edit':
		editTask($_POST);
		redirect(ROOTURL.'modules/projects/index.php?obj=project&view=details&pid='.$_POST['pid'].'&'.SID);
		break;
	    case 'delete':
		if(isset($_POST['confirmation_yes']))
		    deleteTask($_POST['itemid']);
		redirect(ROOTURL.'modules/projects/index.php?obj=project&view=details&pid='.$_GET['pid'].'&'.SID);
		break;
	    }
	    
	break;
        case 'comment':
	    
	break;
    }
}
elseif(isset($_GET['obj'])){
    switch($_GET['obj']){
        case 'project':
	    switch($_GET['view']) {
	    case 'active':
		listProjects(1);
		exit();
		break;
	    case 'completed':
		listProjects(0);
		exit();
		break;
	    case 'newform':
		newProjectForm();
		exit();
		break;
	    case 'editform':
		editProjectForm((int)$_GET['pid']);
		exit();
		break;
	    case 'delete':
		deleteProjectForm((int)$_GET['pid']);
		exit();
		break;
	    case 'gantt':
		projectGANTT((int)$_GET['pid']);
		exit();
		break;
	    case 'details':
		projectDetails((int)$_GET['pid']);
		exit();
		break;
	    case 'finish':
		projectFinish((int)$_GET['pid']);
		redirect(ROOTURL.'modules/projects/index.php?obj=project&view=completed&'.SID);
		exit();
		break;
	    case 'cancel':
		projectCancel((int)$_GET['pid']);
		redirect(ROOTURL.'modules/projects/index.php?obj=project&view=active&'.SID);
		exit();
		break;
	    }
	break;

    case 'task':
	if(isset($_GET['action'])){
	    switch($_GET['action']) {
	    case 'finish':
		finishTask($_GET['tid']);
		redirect(ROOTURL.'modules/projects/index.php?obj=project&view=details&pid='.$_GET['pid'].'&'.SID);
		break;
	    case 'reset':
		resetTask($_GET['tid']);
		redirect(ROOTURL.'modules/projects/index.php?obj=project&view=details&pid='.$_GET['pid'].'&'.SID);
		break;
	    }
	}
	if(isset($_GET['view'])){
	    switch($_GET['view']) {
	    case 'add':
		newTaskForm((int)$_GET['pid']);
		exit();
		break;
	    case 'edit':
		editTaskForm($_GET);
		exit();
		break;
	    case 'delete':
		deleteTaskForm($_GET['tid']);
		exit();
		break;
	    }
	}
	break;

    case 'comment':
	switch($_GET['view']) {
	case 'newform':
	    newCommentForm($_GET['tid']);
	    exit();
	    break;
	}
	
	break;
    }
}

myTasks();
exit();

function projectGANTT($pid){
    global $smarty, $conn;
    $smarty->assign("pagetitle",Lang::getLanguageString("ganttprojects"));

    // graph library
    define('CACHE_DIR',CACHE_FOLDER); // for jpgraph.php itself!
    define("TTF_DIR", INCLUDEPATH . "fonts/"); // Font Directory (where the VERA font is)
    include (JPGRAPHPATH . "jpgraph.php");
    include (JPGRAPHPATH . "jpgraph_gantt.php");

    // A new graph with automatic size 
    $graph = new GanttGraph();
    $graph->ShowHeaders(GANTT_HDAY | GANTT_HWEEK | GANTT_HMONTH);
    $graph->scale->week->SetStyle(WEEKSTYLE_FIRSTDAY);
    $graph->scale->month->SetStyle(MONTHSTYLE_SHORTNAMEYEAR4);
    $graph->SetFrame(false);

    $vline = new GanttVLine(date('Y-m-d', time()));
    $vline->title->Set(Lang::getLanguageString('today'));
    $graph->Add($vline);

    if((int)$_GET['pid'] == 0){
        // all projects view
        $sql = "SELECT title, startdate, targetdate, project_id FROM mgw_projects WHERE status='A'";
        if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

        while($row = $res->FetchRow()){
            $timedone = percentTimeComplete($row['project_id']);
            $wpercent = percentcomplete($row['project_id']);
            $safe_td = max(0, min(100, $timedone));
            if ($conn->UnixTimestamp($row["startdate"]) > time())
            $color = "gray";
            elseif ($safe_td < $wpercent)
            $color = "green";
            elseif ($timedone < 100)
            $color = "yellow";
            else
            $color = "red";

            $bar = new GanttBar($o++,$row["title"],$row["startdate"],$row["targetdate"]);
            $bar->SetPattern(GANTT_SOLID, $color);
            $bar->progress->Set($wpercent/100);
            $bar->SetCSIMTarget("index.php?obj=project&amp;view=details&amp;pid=".$row['project_id']."&amp;".SID);
            $bar->title->SetCSIMTarget("index.php?obj=project&amp;view=details&amp;pid=".$row['project_id']."&amp;".SID);
            $bar->SetCSIMAlt(Lang::getLanguageString('details'));
            $bar->title->SetCSIMAlt(Lang::getLanguageString('details'));

            $graph->Add($bar);
        }
    }
    else{
    // single project view
    $sql = "SELECT title, startdate, targetdate, project_id FROM mgw_projects WHERE project_id=".(int)$_GET['pid'];
    if(($row = $conn->GetRow($sql)) === false) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

    // Set up a new array to keep track of the items on the graph
    $o = array();
    $newbar = array();

    $timedone = percentTimeComplete($row['project_id']);
    $wpercent = percentcomplete($row['project_id']);
    $safe_td = max(0, min(100, $timedone));
    if ($conn->UnixTimestamp($row["startdate"]) > time())
    $color = "gray";
    elseif ($safe_td < $wpercent)
    $color = "green";
    elseif ($timedone < 100)
    $color = "yellow";
    else
    $color = "red";

    // Title ( Not sure about the font)
    $graph->title->Set($row["title"]);
    if(function_exists('imagettfbbox')) {
	$graph->title->SetFont(FF_VERA, FS_BOLD, 18);
    }

    $bar = new GanttBar(count($o),$row["title"],$row["startdate"],$row["targetdate"]);
    $bar->leftMark->SetType(MARK_LEFTTRIANGLE);
    $bar->leftMark->Show();
    $bar->leftMark->SetWidth(8);
    $bar->leftMark->SetColor('black');
    $bar->leftMark->SetFillColor('black');
    $bar->rightMark->SetType(MARK_RIGHTTRIANGLE);
    $bar->rightMark->Show();
    $bar->rightMark->SetWidth(8);
    $bar->rightMark->SetColor('black');
    $bar->rightMark->SetFillColor('black');
    $bar->SetPattern(GANTT_SOLID, $color);
    $bar->progress->Set($wpercent/100);
    $bar->SetCSIMTarget("index.php?obj=project&amp;view=details&amp;pid=".$pid."&amp;".SID);
    $bar->title->SetCSIMTarget("index.php?obj=project&amp;view=details&amp;pid=".$pid."&amp;".SID);
    $bar->SetCSIMAlt(Lang::getLanguageString('details'));
    $bar->title->SetCSIMAlt(Lang::getLanguageString('details'));
    $graph->Add($bar);
    $o[] = "";

    // Call recurrsive function, give it graph object and begin with tasks with parentid of 0
    projectGraphTasks($graph,0,$o,$newbar);

    // All bars should be drawn 
    // Now go back and set the constraints (Has to be done last)
    //  Get all the tasks with constraints 
    $sql = "SELECT task_id, constrain_id FROM mgw_projects_tasks WHERE project_id=" . (int)$_GET['pid'] . " AND constrain_id > 0";
    if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    // Step through each task and draw in its constraints
    while($row = $res->FetchRow()){
        if ($row['constrain_id']) {
            // Get the Constraint and task ID and make sure they are int
            $constrain_id = (int)$row['constrain_id'];
            $current_tid = (int)$row['task_id'];
            // Find the place of the associated bar
            $constrain_bar = (int)array_search($constrain_id,$o);
            $current_bar = (int)array_search($current_tid,$o);
            $newbar[$constrain_bar]->SetConstrain($current_bar, CONSTRAIN_ENDSTART);
            // Must redraw the bar now.
            $graph->Add($newbar[$constrain_bar]);
        }


    }


}
/* For Debugging 
ob_start();
print_r($o);
$ganttlist = ob_get_contents();
ob_end_clean();
$smarty->assign('ganttlist', $ganttlist);
*/
// Display the Gantt chart
$graph->Stroke(CACHE_FOLDER."gantt$pid.png");
$smarty->assign('ganttimg', CACHE_URL."gantt$pid.png");
$smarty->assign('ganttmap', $graph->GetHTMLImageMap('ganttmap'));

$smarty->display('projects_gantt.tpl');
exit();
}

// =================================================
// finish project
// =================================================
function projectFinish($pid){
    global $conn;
    $date = $conn->DBTimeStamp(time());
    $sql = "UPDATE mgw_projects SET status='F', enddate=$date WHERE project_id=$pid";
    if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
}

// =================================================
// cancel project
// =================================================
function projectCancel($pid){
    global $conn;
    $date = $conn->DBTimeStamp(time());
    $sql = "UPDATE mgw_projects SET status='C', enddate=$date WHERE project_id=$pid";
    if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
}

// =================================================
// finish task
// =================================================
function finishTask($tid){
    global $conn;
    $sql = "UPDATE mgw_projects_tasks SET status=0 WHERE task_id=$tid";
    if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
}

// =================================================
// reset task
// =================================================
function resetTask($tid){
    global $conn;
    $sql = "UPDATE mgw_projects_tasks SET status=1 WHERE task_id=$tid";
    if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

    $sql = "UPDATE mgw_projects SET status='A' WHERE project_id=".
	$conn->GetOne('SELECT project_id FROM mgw_projects_tasks WHERE task_id='.$tid);
    if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
}

// =================================================
// create task
// =================================================
function createTask($data){
    global $conn;

    // get the sequence number
    $tid = mgw_genID('mgw__seq_projects_tasks');

    $pid = (int)$data['pid'];
    $qname = (empty($data['taskname'])) ? "'[".Lang::getLanguageString('notitle')."]'" : $conn->QMagic($data['taskname']);
    $qdesc = $conn->QMagic($data['description']);
    $assignedto = (int) $data['assignedto'];
    $parent_id = (int) $data['parent_id'];
    $constrain_id = (int) $data['constrain_id'];
    $hours = (float) $data['hours'];
    $usedhours = (float) $data['usedhours'];
    $billable = (isset($data['billable'])) ? '1' : '0';
    $milestone = (isset($data['milestone'])) ? '1' : '0';
    $startdate=$conn->DBTimeStamp($data["StartYear"]."-".$data["StartMonth"]."-".$data["StartDay"]." 00:00:00");
    $targetdate=$conn->DBTimeStamp($data["EndYear"]."-".$data["EndMonth"]."-".$data["EndDay"]." 00:00:00");
    $enddate=($milestone > 0) ? $startdate : $targetdate;
    //BUGFIX: Transposed constrain_id and Parent_ID
    $sql = "INSERT INTO mgw_projects_tasks (task_id, project_id, constrain_id, parent_id, title, description, milestone, hours, usedhours, startdate, targetdate, assignee, billable, status) VALUES ($tid, $pid, $constrain_id, $parent_id,  $qname, $qdesc, $milestone, $hours, $usedhours, $startdate, $targetdate, $assignedto, '$billable', '1')";

    if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

    // Notification
    $msg = Lang::getLanguageString('delegatedtask') . " " . $qname . " \n\n" . Lang::getLanguageString('description') . ": " . $qdesc;
    $sql = "SELECT title FROM mgw_projects WHERE project_id=$pid";
    if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    $row = $res->FetchRow();
    $subj = "more.groupware: " . Lang::getLanguageString('newproject') . " " . Lang::getLanguageString('task') . ": " . $row["title"];  

    // to fix bug #899784
    if(get_magic_quotes_gpc()){
    	$subj = addslashes($subj);
		$msg = addslashes($msg);
    }

    if(in_array(NOTIFY_MIM,$_SESSION['MGW']->settings['projects_notification']))
	$GLOBALS['notify']->message($msg, NOTIFY_MIM, 'u:'.$assignedto, $subj);
    if(in_array(NOTIFY_SCREEN,$_SESSION['MGW']->settings['projects_notification']))
	$GLOBALS['notify']->message($msg, NOTIFY_SCREEN, 'u:'.$assignedto, $subj);
    if(in_array(NOTIFY_MAIL,$_SESSION['MGW']->settings['projects_notification']))
	$GLOBALS['notify']->message($msg, NOTIFY_MAIL, 'u:'.$assignedto, $subj);

    $data['tid']=$tid;
    
    // Check Dates  of Parent
    $sql = "SELECT task_id,startdate,targetdate FROM mgw_projects_tasks WHERE task_id=$parent_id AND (targetdate < $enddate OR startdate > $startdate)";
    if(!($row = $conn->GetRow($sql))===false){
	    
	$data['startdate']= $startdate;
	$data['targetdate'] = $enddate;

        if ($conn->UnixTimestamp($row["targetdate"]) < $conn->UnixDate($data["EndYear"]."-".$data["EndMonth"]."-".$data["EndDay"])){
	        
	    $red['targetdate'] = "Parent Target date is " . $row['targetdate'] ; 
	}
	    
	if ($conn->UnixTimestamp($row["startdate"]) > $conn->UnixDate($data["StartYear"]."-".$data["StartMonth"]."-".$data["StartDay"])){
	    $red['startdate'] = "Parent Start date is " . $row['startdate']  ; 
	}
	    
	editTaskForm($data,$red);
	return;
    }
	
    // Fix the Parent's hours    
    if ($parent_id){
        projectCalcParentHours($parent_id);
    }
}

// =================================================
// edit task
// =================================================
function editTask($data){
    global $conn;

    $tid = (int)$data['tid'];
    $pid = (int)$data['pid'];
    $qtitle = (empty($data['taskname'])) ? "'[".Lang::getLanguageString('notitle')."]'" : $conn->QMagic($data['taskname']);
    $qdesc = $conn->QMagic($data['description']);
    $assignedto = (int) $data['assignedto'];
    $parent_id = (int) $data['parent_id'];
    $constrain_id = (int) $data['constrain_id'];
    $hours = (float) $data['hours'];
    $milestone = (isset($data['milestone'])) ? '1' : '0';
    $usedhours = (float) $data['usedhours'];
    $billable = (isset($data['billable'])) ? '1' : '0';
    $startdate=$conn->DBTimeStamp($data["StartYear"]."-".$data["StartMonth"]."-".$data["StartDay"]." 00:00:00");
    $enddate=($milestone > 0) ? $startdate : $conn->DBTimeStamp($data["EndYear"]."-".$data["EndMonth"]."-".$data["EndDay"]." 00:00:00");
    
    
    // Check Dates  of Parent
    $sql = "SELECT task_id,startdate,targetdate FROM mgw_projects_tasks WHERE task_id=$parent_id AND (targetdate < $enddate OR startdate > $startdate)";
	if(!($row = $conn->GetRow($sql))===false){
	    
	    $data['startdate']= $startdate;
	    $data['targetdate'] = $enddate;

        if ($conn->UnixTimestamp($row["targetdate"]) < $conn->UnixDate($data["EndYear"]."-".$data["EndMonth"]."-".$data["EndDay"])){
	        
	        $red['targetdate'] = "Parent Target date is " . $row['targetdate'] ; 
	    }
	    
	    if ($conn->UnixTimestamp($row["startdate"]) > $conn->UnixDate($data["StartYear"]."-".$data["StartMonth"]."-".$data["StartDay"])){
	        $red['startdate'] = "Parent Start date is " . $row['startdate']  ; 
	    }
	    

	    editTaskForm($data,$red);
	    return;
	}
    
    
    if($parent_id != $tid){
	$GLOBALS['notify']->message(Lang::getLanguageString('task_updated'), NOTIFY_SCREEN);
	$sql = "UPDATE mgw_projects_tasks SET parent_id=$parent_id, constrain_id=$constrain_id, title=$qtitle, description=$qdesc, hours=$hours, usedhours=$usedhours, startdate=$startdate, targetdate=$enddate, assignee=$assignedto, billable=$billable, milestone=$milestone WHERE task_id=$tid";
    }
    else{
	$GLOBALS['notify']->message(Lang::getLanguageString('task_subloop'), NOTIFY_SCREEN);
	$sql = "UPDATE mgw_projects_tasks SET title=$qtitle, constrain_id=$constrain_id, description=$qdesc, hours=$hours, usedhours=$usedhours, startdate=$startdate, targetdate=$enddate, assignee=$assignedto, billable=$billable, milestone=$milestone  WHERE task_id=$tid";
    }
    if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    
    // Notification
    
    $msg = Lang::getLanguageString('delegatedtask') . " " . $qtitle . " \n\n" . Lang::getLanguageString('description') . ": " . $qdesc;
    $sql = "SELECT title FROM mgw_projects WHERE project_id=$pid";
    if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    $row = $res->FetchRow();
    $subj = "more.groupware: " . Lang::getLanguageString('changedproject') . ": " . $row["title"];
    
    // to fix bug #899784
    if(get_magic_quotes_gpc()){
    	$subj = addslashes($subj);
		$msg = addslashes($msg);
    }
    
    if(in_array(NOTIFY_MIM,$_SESSION['MGW']->settings['projects_notification']))
    $GLOBALS['notify']->message($msg, NOTIFY_MIM, 'u:'.$assignedto, $subj);
    if(in_array(NOTIFY_SCREEN,$_SESSION['MGW']->settings['projects_notification']))
    $GLOBALS['notify']->message($msg, NOTIFY_SCREEN, 'u:'.$assignedto, $subj);
    if(in_array(NOTIFY_MAIL,$_SESSION['MGW']->settings['projects_notification']))
    $GLOBALS['notify']->message($msg, NOTIFY_MAIL, 'u:'.$assignedto, $subj);
    
    //
    
    if(isset($data['commenttoedit']) && $data['commenttoedit'] != ''){
	$cid = $data['cid'];
 	$qcomment = $conn->QMagic($data['commenttoedit']);

 	$sql="UPDATE mgw_projects_comments SET date=".$conn->DBTimeStamp(time()).", comment=$qcomment WHERE comment_id=$cid";
 	if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    }

    if($data['comment'] != ''){
	$cid = mgw_genID('mgw__seq_projects_comments');
 	$qcomment = $conn->QMagic($data['comment']);

 	$sql="INSERT INTO mgw_projects_comments (comment_id, task_id, project_id, owner, date, comment) VALUES ($cid, $tid, $pid,".$_SESSION["MGW"]->userid.", ".$conn->DBTimeStamp(time()).", $qcomment)";
 	if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
 	$sql="UPDATE mgw_projects_tasks SET comments='1' WHERE task_id=$tid";
 	if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
}
    
    // Fix the hours
    if ($parent_id){
        projectCalcParentHours($parent_id);
    }
    else
    {
        projectCalcParentHours($tid);
    }
}

// =================================================
//	              Eintrag createn
// =================================================
function createProject($data){
    global $conn;

    // get the sequence number
    $id = mgw_genID('mgw__seq_projects');

    $qname = (empty($data['name'])) ? "'[".Lang::getLanguageString('notitle')."]'" : $conn->QMagic($data['name']);
    $qdesc = $conn->QMagic($data['description']);
    $company = (int) $data['_company'];
    $projleader = (int) $data['_projleader'];
    $keyaccount = (int) $data['_keyaccount'];

    $startdate=$conn->DBTimeStamp($data["StartYear"]."-".$data["StartMonth"]."-".$data["StartDay"]." 00:00:00");
    $targetdate=$conn->DBTimeStamp($data["EndYear"]."-".$data["EndMonth"]."-".$data["EndDay"]." 00:00:00");

    $sql = "INSERT INTO mgw_projects (project_id, title, description, companyid, projleaderid, keyaccountid, startdate, targetdate, status, owner, lu_user, lu_date) VALUES ($id, $qname, $qdesc, $company, '$projleader', '$keyaccount', $startdate, $targetdate, 'A', ".$_SESSION["MGW"]->userid.", ".$_SESSION["MGW"]->userid.", ". $conn->DBTimeStamp(time()). ")";

    if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    return $id;
}

// =================================================
//	              Eintrag ?ndern
// =================================================
function editProject($data){
    global $conn;

    $qname = (empty($data['name'])) ? "'[".Lang::getLanguageString('notitle')."]'" : $conn->QMagic($data['name']);
    $qdesc = $conn->QMagic($data['description']);
    $company = (int) $data['_company'];
    $projleader = (int) $data['_projleader'];
    $keyaccount = (int) $data['_keyaccount'];

    $startdate=$conn->DBTimeStamp($data["StartYear"]."-".$data["StartMonth"]."-".$data["StartDay"]." 00:00:00");
    $enddate=$conn->DBTimeStamp($data["EndYear"]."-".$data["EndMonth"]."-".$data["EndDay"]." 00:00:00");

    $sql="UPDATE mgw_projects SET companyid=$company, title=$qname, projleaderid=$projleader, startdate=$startdate, targetdate=$enddate, description=$qdesc, keyaccountid=$keyaccount, lu_user=".$_SESSION["MGW"]->userid.", lu_date=". $conn->DBTimeStamp(time()). " WHERE project_id=".(int)$data["pid"];

    if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
}

// =================================================
//	              Project delete
// =================================================
function deleteProjectForm($pid){
    global $appconf, $conn, $smarty;
    $sql = "SELECT title, description FROM mgw_projects WHERE project_id=$pid";

    if(($row = $conn->GetRow($sql))===false) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

    $smarty->assign("obj", 'project');
    $smarty->assign("itemid", $pid);
    $smarty->assign("reallydeleteitem", Lang::getLanguageString("reallydelproject"));
    $smarty->assign("deletedetail1", $row["title"]);
    $smarty->assign("deletedetail2", $row["description"]);
    $smarty->assign("suclass","submit");
    $smarty->display($appconf["gentemplates"] ."/delete_item.tpl");
}

function deleteProject($pid){
    global $conn;

    $sql = "DELETE FROM mgw_projects WHERE project_id=$pid";
    if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    $sql = "SELECT task_id FROM mgw_projects_tasks WHERE project_id=$pid";
    if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    while($row = $res->FetchRow()){
	$sql = "DELETE FROM mgw_projects_comments WHERE task_id=".$row['task_id'];
	if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    }
    $sql = "DELETE FROM mgw_projects_tasks WHERE project_id=$pid";
    if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
}

// =================================================
function deleteTaskForm($tid){
    global $appconf, $conn, $smarty;
    $sql = "SELECT title, description FROM mgw_projects_tasks WHERE task_id=$tid";

    if(!$row = $conn->Getrow($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

    $smarty->assign("obj", 'task');
    $smarty->assign("itemid", $tid);
    $smarty->assign("parms", 'pid='.$_GET['pid']);
    $smarty->assign("reallydeleteitem", Lang::getLanguageString("reallydeltask"));
    $smarty->assign("deletedetail1", $row["title"]);
    $smarty->assign("deletedetail2", $row["description"]);
    $smarty->assign("suclass","submit");
    $smarty->display($appconf["gentemplates"] ."/delete_item.tpl");
}

function deleteTask($tid){
    global $conn;

    $tasks = get_children($tid,2);
    foreach($tasks as $stid)
	deleteTask($stid);

    $sql = "DELETE FROM mgw_projects_comments WHERE task_id=$tid";
    if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

    $sql = "DELETE FROM mgw_projects_tasks WHERE task_id=$tid";
    if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
}

// =================================================
//	              New Item Formular
// =================================================
function newProjectForm(){
    global $conn, $smarty;
    include(INCLUDEPATH . "mSelectBox.class.php");

    $smarty->assign("suname","create");
    $smarty->assign("suclass","submit");
    $smarty->assign("suvalue",Lang::getLanguageString("create"));

    $sb = new mSelectBox("sday");
    $sb2 = new mSelectBox("smonth");
    $sb3 = new mSelectBox("syear");

    $sb4 = new mSelectBox("eday");
    $sb5 = new mSelectBox("emonth");
    $sb6 = new mSelectBox("eyear");

    $sb7 = new mSelectBox("_company");
    $sb7->setContentType("sql");
    $sb7->setSQLvalue("id");
    $sb7->setSQLcontent("name1");
    $sb7->addContent("SELECT * FROM mgw_companies ORDER BY name1");
    $sb7->addOption("0", Lang::getLanguageString("internalproject"), "pre");
    $smarty->assign("companysb", $sb7->draw());

    $sb8 = new mSelectBox("_projleader");
    $sb8->setContentType("sql");
    $sb8->setSQLvalue("id");
    $sb8->setSQLcontent("myfullname");
    $constr = $conn->Concat("lastname", "', '", "firstname");
    $sb8->addContent("SELECT *, $constr AS myfullname FROM mgw_users ORDER BY lastname");
    $smarty->assign("projleader", $sb8->draw());

    $sb9 = $sb8;
    $sb9->varname = "_keyaccount";
    $smarty->assign("keyaccount", $sb9->draw());

    $smarty->assign("sday", $sb->getSB_Day(date("d", time()), true));
    $smarty->assign("smonth", $sb2->getSB_Month(date("m", time()), true));
    $smarty->assign("syear", $sb3->getSB_Year(date("Y")-5, date("Y")+5, date("Y", time()), true));
    $smarty->assign("eday", $sb4->getSB_Day(0, true));
    $smarty->assign("emonth", $sb5->getSB_Month(0, true));
    $smarty->assign("eyear", $sb6->getSB_Year(date("Y")-5, date("Y")+5, 0, true));

    $smarty->assign("contentheader",Lang::getLanguageString("newproject"));
    $smarty->assign("action","create");

    $smarty->display('projects_edit.tpl');
    exit();
}

// =================================================
// Add Task Form
// =================================================
function newTaskForm($pid){
    global $conn, $smarty;
    include(INCLUDEPATH . "mSelectBox.class.php");

    $sql = "SELECT title FROM mgw_projects WHERE project_id=".$pid;
    if(($row = $conn->GetRow($sql))===false) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    $td['ptitle'] = $row['title'];
    $td['pid'] = $pid;
    $smarty->assign("td",$td);

    $smarty->assign("tasksel", task_dropdown($pid));
    $smarty->assign("constasksel", task_dropdown($pid, 0, "constrain_id"));
    $smarty->assign("suname","create");
    $smarty->assign("suclass","submit");
    $smarty->assign("suvalue",Lang::getLanguageString("create"));

    $sb7 = new mSelectBox("assignedto");
    $sb7->setContentType("sql");
    $sb7->setSQLvalue("id");
    $sb7->setSQLcontent("name");
    $concat = $conn->Concat('lastname', "', '", 'firstname');
    $sb7->addContent("SELECT id, $concat AS name FROM mgw_users ORDER BY lastname");
    $smarty->assign("users", $sb7->draw());

    $smarty->assign("ptitle",Lang::getLanguageString('addtask'));
    $smarty->assign("action","create");

    $smarty->display('projects_taskedit.tpl');
}

// =================================================
// Edit Task Form
// =================================================
function editTaskForm($data,$red=array()){
    global $conn, $smarty;
    include(INCLUDEPATH . "mSelectBox.class.php");

    if ($data['tid']>0){
        $tid = $data['tid'];
        $sql = "SELECT * FROM mgw_projects_tasks WHERE task_id=$tid";
        if(($row = $conn->GetRow($sql))===false) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    }
    else{
        $row = $data;
        $row['project_id']=$row['pid'];
    }
    
    // Check for children, if so then disable the hours boxes
    if (get_children($tid,2)){
        $disabled['usedhours'] = "readonly";
        $disabled['hours'] = "readonly";
        $disabled['billable'] = "readonly";
    }
    // Disable EndDate if milestone
    if (isset($row['milestone'])){
        $disabled['enddate'] = "disabled";
    }
        
    
    $smarty->assign("tasksel", task_dropdown($row['project_id'], $tid, "parent_id"));
    $smarty->assign("constasksel", task_dropdown($row['project_id'], $tid, "constrain_id"));
    $smarty->assign("sts",$conn->UnixDate($row['startdate']));
    $smarty->assign("ets",$conn->UnixDate($row['targetdate']));

    $sb7 = new mSelectBox("assignedto");
    $sb7->setContentType("sql");
    $sb7->setSQLvalue("id");
    $sb7->setSQLcontent("name");
    $concat = $conn->Concat('lastname', "', '", 'firstname');
    $sb7->addContent("SELECT id, $concat AS name FROM mgw_users ORDER BY lastname");
    $smarty->assign("users", $sb7->draw($row['assignee']));

    $smarty->assign("suvalue",Lang::getLanguageString("save"));
    $smarty->assign("ptitle",Lang::getLanguageString('edittask'));
    $smarty->assign("action","edit");
    $smarty->assign("caction",Lang::getLanguageString('save'));
    $sql = "SELECT title FROM mgw_projects WHERE project_id=".$row['project_id'];
    if(($prow = $conn->GetRow($sql))===false) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    $row['ptitle'] = $prow['title'];
    $row['pid'] = $row['project_id'];

    $smarty->assign("td",$row);
    $smarty->assign("red",$red);
    $smarty->assign("disabled",$disabled);
    $fn = $conn->Concat('b.lastname',"', '",'b.firstname');
    $sql = "SELECT a.comment_id, a.comment, a.date, a.owner, $fn AS lu_username FROM mgw_projects_comments a LEFT JOIN mgw_users b ON a.owner=b.id WHERE a.task_id=$tid";
    $comments = $conn->GetArray($sql);
    reset($comments);
    for($i=0;$i < count($comments);$i++){
	if(isset($data['cidtoedit']) && ($comments[$i]['comment_id']==$data['cidtoedit'])) {
	    $comments[$i]['comment'] = htmlspecialchars($comments[$i]['comment']);
	}
	else {
	    $comments[$i]['comment'] = nl2br(htmlspecialchars($comments[$i]['comment']));
	}
	$comments[$i]['date'] = $conn->UnixTimestamp($comments[$i]['date']);
    }

    $smarty->assign("comments", $comments);
    if(isset($data['cidtoedit']))
	$smarty->assign("cidtoedit", $data['cidtoedit']);
    $smarty->assign("userid", $_SESSION['MGW']->userid);

    $smarty->display('projects_taskedit.tpl');
}

// =================================================
//	              Detail Ansicht
// =================================================
function projectDetails($pid){
    global $conn, $smarty;
    include(INCLUDEPATH . "mSelectBox.class.php");

    $sql = "SELECT a.*, b.name1, d.lastname AS kaname, d.email AS kaemail, e.lastname AS plname, e.email AS plemail FROM mgw_projects a LEFT JOIN mgw_companies b ON a.companyid=b.id LEFT JOIN mgw_users d ON a.keyaccountid = d.id LEFT JOIN mgw_users e ON a.projleaderid = e.id WHERE a.project_id=$pid";

    if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    $row = $res->FetchRow();

    if($row["name1"]=="") $row["name1"] = Lang::getLanguageString("internalproject");

    $row['startdate'] = $conn->UnixDate($row['startdate']);
    $row['targetdate'] = $conn->UnixDate($row['targetdate']);

    $row['tpbar'] = draw_time_and_progress_bars($pid);
    $row['todotasks'] = task_list($pid, 1, 'startdate ASC');
    $row['donetasks'] = task_list($pid, 0, 'startdate ASC');
    $smarty->assign("td", $row);
    $smarty->assign("suname","edit");
    $smarty->assign("suvalue","Speichern");
    $smarty->assign("suclass","submit");
    if(hours_todo($pid) == 0)
	$smarty->assign('completable', true);
    $smarty->display("projects_details.tpl");
    exit();
}


// =================================================
//	              Edit Item Formular
// =================================================
function editProjectForm($pid){
    global $conn, $smarty;
    include(INCLUDEPATH . "mSelectBox.class.php");

    $sql = "SELECT * FROM mgw_projects WHERE project_id=$pid";

    if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    $row = $res->FetchRow();

    $sb5 = new mSelectBox("_company");
    $sb5->setContentType("sql");
    $sb5->setSQLvalue("id");
    $sb5->setSQLcontent("name1");
    $sb5->addContent("SELECT * FROM mgw_companies ORDER BY name1");
    $sb5->addOption("0", Lang::getLanguageString("internalproject"), "pre");
    $smarty->assign("companysb", $sb5->draw($row["companyid"]));

    $sb8 = new mSelectBox("_projleader");
    $sb8->setContentType("sql");
    $sb8->setSQLvalue("id");
    $sb8->setSQLcontent("myfullname");
    $constr = $conn->Concat("lastname", "', '", "firstname");
    $sb8->addContent("SELECT *, $constr AS myfullname FROM mgw_users ORDER BY lastname");
    $smarty->assign("projleader", $sb8->draw($row["projleaderid"]));

    $sb9 = $sb8;
    $sb9->varname = "_keyaccount";
    $smarty->assign("keyaccount", $sb9->draw($row["keyaccountid"]));

    $smarty->assign("sts",$conn->UnixDate($row['startdate']));
    $smarty->assign("ets",$conn->UnixDate($row['targetdate']));

    $smarty->assign("pid", $pid);
    $smarty->assign("td", $row);
    $smarty->assign("suvalue",Lang::getLanguageString("edit"));

    $smarty->assign("action","edit");
    $smarty->assign("contentheader",Lang::getLanguageString("editproject"));

    $smarty->display('projects_edit.tpl');
    exit;
}


function myTasks(){
    global $conn, $smarty;

    $rows = array();
    $sql = 'SELECT DISTINCT project_id FROM mgw_projects_tasks WHERE status=1 AND assignee='.$_SESSION['MGW']->userid;
    if(!$projects = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

    while($project = $projects->FetchRow()) {

	// fetch project name
	$sql = 'SELECT title from mgw_projects WHERE project_id='.$project['project_id'];
	if(!$pname = $conn->GetOne($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	$row['pid'] = $project['project_id'];
	$row['ptitle'] = $pname;
	$row['pstatus'] = draw_time_and_progress_bars($project['project_id']);

	// select tasks for project
	$sql = 'SELECT task_id, title, description, hours, usedhours, billable, comments FROM mgw_projects_tasks WHERE project_id='.$project['project_id'].' AND status=1 AND assignee='.$_SESSION['MGW']->userid;
	if(!$tasks = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	while($task = $tasks->FetchRow()) {
	    if (get_children($task['task_id'],1)) {
		$task['action']['url'][0] = "#";
		$task['action']['img'][0] = "d-off.gif";
		$task['action']['url'][1] = "#";
		$task['action']['img'][1] = "f-off.gif";
	    } else {
		$task['action']['url'][0] = "index.php?obj=task&amp;view=delete&amp;tid=$task[task_id]&amp;pid=$project[project_id]&amp;".SID;
		$task['action']['img'][0] = "d-on.gif";
		$task['action']['url'][1] = "index.php?obj=task&amp;action=finish&amp;tid=$task[task_id]&amp;pid=$project[project_id]&amp;".SID;
		$task['action']['img'][1] = "f-on.gif";
	    }
	    $row['tasks'][] = $task;
	}
	$rows[] = $row;
	unset($row);
    }
    $smarty->assign('projects', $rows);
    $smarty->display('projects_mytasks.tpl');
}

// =================================================
//	              List View
// =================================================
function listProjects($status=1){
     global $conn, $smarty;

    // if user wants icons, assign icons if not -> not
    $icons = getIconStrings();

    $sql = ($status == 1) ?
	"SELECT a.*, b.name1, c.lastname AS pllastname FROM mgw_projects a LEFT JOIN mgw_companies b ON a.companyid=b.id LEFT JOIN mgw_users c ON a.projleaderid = c.id WHERE a.status='A'" :
	"SELECT a.*, b.name1, c.lastname AS pllastname FROM mgw_projects a LEFT JOIN mgw_companies b ON a.companyid=b.id LEFT JOIN mgw_users c ON a.projleaderid = c.id WHERE a.status='F' OR a.status='C'" ;
	

//     if($_POST["action"] == "qsearch") {
// 	$searchterm = $conn->QMagic("%".$_POST["searchterm"]."%");
// 	$sql .= " AND a.name LIKE ".$searchterm." OR b.name1 LIKE ".$searchterm;
//     }

    if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    $counter = 0;
    while($row = $res->FetchRow()) {
	$counter++;
	$pid = $row["project_id"];
	$compid = $row["companyid"];

	// if internal project then name it
	if($row["name1"] == "") $internalproject = true;
	else $internalproject = false;

	if($status == 1)
	    $row["bars"] = draw_time_and_progress_bars($row['project_id']);
	else{
	    $row["bars"] = ($row['status'] == 'F') ? Lang::getLanguageString('finished') : Lang::getLanguageString('aborted');
	}
	$row["startdate"] = $conn->UnixTimestamp($row["startdate"]);
	$row["targetdate"] = $conn->UnixTimestamp($row["targetdate"]);
	$numtasks = getNumTasks($pid);
	$row = array_merge($row, $numtasks);
	$smarty->append("td", $row);

	if($internalproject) $companies[] = Lang::getLanguageString("internalproject");
	else $companies[] = "<a href=\"../contact/index.php?mod=contact&obj=company&view=details&id=$compid&".SID."\" class=\"\">". $row["name1"] ."</a>";

	// create Action URLs
	$detlink = "<a href=\"index.php?obj=project&amp;view=details&amp;pid=$pid&amp;".SID."\" class=\"edit\">".$icons['details']."</a>";

	// modify only for user with appropriate rights
	if(queryRights2_bool('root_modules_projects_project_modify') && $row["owner"] == $_SESSION["MGW"]->userid) {
	    $editlink = "<a href=\"index.php?obj=project&amp;view=editform&pid=$pid&amp;".SID."\" class=\"edit\">".$icons["edit"]."</a>";
	}
	else {
	    $editlink = "";
	}

	// delete only for user with appropriate rights
	if(queryRights2_bool('root_modules_projects_project_delete') && $row["owner"] == $_SESSION["MGW"]->userid){
	    $dellink = "<a href=\"index.php?obj=project&amp;view=delete&pid=$pid&amp;".SID."\" class=\"delete\">".$icons["delete"]."</a>";
	}
	else {
	    $dellink = "";
	}
	
	$urls[] = $detlink . $icons["space"] . $editlink . $icons["space"] . $dellink;
    }

    //$smarty->assign('searchterm', $searchterm);
    //$smarty->assign('suvalue', Lang::getLanguageString("search"));
    $smarty->assign('ptitle', ($status == 1) ? Lang::getLanguageString('activeprojects') : Lang::getLanguageString('completedprojects'));
    $smarty->assign('urls', $urls);
    $smarty->display("projects_list.tpl");
}

?>
