<?php

/*************************************************************************/
/* DOCEBO CMS - Content Management System                                */
/* ============================================                          */
/*                                                                       */
/* Copyright (c) 2007 by Giovanni Derks <virtualdarkness[AT]gmail-com>   */
/* http://www.docebo.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.        */
/*************************************************************************/

if(!defined('IN_DOCEBO')) die('You cannot access this file directly');

/**
 * @version  $Id: $
 */
// ----------------------------------------------------------------------------


define("_PRIORITY_LOW", 0);
define("_PRIORITY_MEDIUM", 10);
define("_PRIORITY_HIGH", 20);
define("_PRIORITY_VERYHIGH", 30);

define("_STATUS_NOTSTARTED", 0);
define("_STATUS_INPROGRESS", 10);
define("_STATUS_TOBETESTED", 20);
define("_STATUS_TOBEINSTALLED", 30);
define("_STATUS_FINISHED", 40);
define("_STATUS_PLANNED", 50);
define("_STATUS_SUSPENDED", 60);


class TaskmanManager {

	var $prefix=NULL;
	var $dbconn=NULL;

	var $lang=NULL;

	// Core Company manager
	var $ccm=NULL;

	function TaskmanManager($prefix=FALSE, $dbconn=NULL) {
		$this->prefix=($prefix !== false ? $prefix : $GLOBALS["prefix_crm"]);
		$this->dbconn=$dbconn;

		require_once($GLOBALS["where_framework"]."/lib/lib.company.php");
		$this->ccm=new CoreCompanyManager();

		$this->lang=& DoceboLanguage::createInstance('taskman', "crm");
	}


	function _query( $query ) {
		if( $GLOBALS['do_debug'] == 'on' && isset($GLOBALS['page']) )  $GLOBALS['page']->add( "\n<!-- debug $query -->", 'debug' );
		else echo "\n<!-- debug $query -->";
		if( $this->dbconn === NULL )
			$rs = mysql_query( $query );
		else
			$rs = mysql_query( $query, $this->dbconn );
		return $rs;
	}


	function _insQuery( $query ) {
		if( $GLOBALS['do_debug'] == 'on' ) $GLOBALS['page']->add( "\n<!-- debug $query -->" , 'debug' );
		if( $this->dbconn === NULL ) {
			if( !mysql_query( $query ) )
				return FALSE;
		} else {
			if( !mysql_query( $query, $this->dbconn ) )
				return FALSE;
		}
		if( $this->dbconn === NULL )
			return mysql_insert_id();
		else
			return mysql_insert_id($this->dbconn);
	}


	function getMainTable() {
		return $this->prefix."_taskman";
	}


	function getPriorityArray() {
		$res =array();
		$res[_PRIORITY_LOW]=$this->lang->def("_PRIORITY_LOW");
		$res[_PRIORITY_MEDIUM]=$this->lang->def("_PRIORITY_MEDIUM");
		$res[_PRIORITY_HIGH]=$this->lang->def("_PRIORITY_HIGH");
		$res[_PRIORITY_VERYHIGH]=$this->lang->def("_PRIORITY_VERYHIGH");

		return $res;
	}


	function getStatusArray() {
		$res =array();
		$res[_STATUS_NOTSTARTED]=$this->lang->def("_STATUS_NOTSTARTED");
		$res[_STATUS_INPROGRESS]=$this->lang->def("_STATUS_INPROGRESS");
		$res[_STATUS_TOBETESTED]=$this->lang->def("_STATUS_TOBETESTED");
		$res[_STATUS_TOBEINSTALLED]=$this->lang->def("_STATUS_TOBEINSTALLED");
		$res[_STATUS_FINISHED]=$this->lang->def("_STATUS_FINISHED");
		$res[_STATUS_PLANNED]=$this->lang->def("_STATUS_PLANNED");
		$res[_STATUS_SUSPENDED]=$this->lang->def("_STATUS_SUSPENDED");

		return $res;
	}


	function getTaskList($ini=FALSE, $vis_item=FALSE, $where=FALSE, $order_by=FALSE) {

		$data_info=array();
		$data_info["data_arr"]=array();
		$data_info["user_info"]=array();
		$idst_arr =array();

		$fields="*, DATEDIFF(scheduled_end_date, NOW()) as scheduled_diff";
		$qtxt ="SELECT ".$fields." FROM ".$this->getMainTable()." ";

		if ($where !== FALSE) {
			$qtxt.="WHERE ".$where;
		}

		if ($order_by !== FALSE) {
			$qtxt.="ORDER BY ".$order_by." ";
		}
		else {
			$qtxt.="ORDER BY scheduled_end_date ";
		}
		$q=$this->_query($qtxt);

		if ($q)
			$data_info["data_tot"]=mysql_num_rows($q);
		else
			$data_info["data_tot"]=0;

		if (($ini !== FALSE) && ($vis_item !== FALSE)) {
			$qtxt.="LIMIT ".$ini.",".$vis_item;
			$q=$this->_query($qtxt);
		}


		if (($q) && (mysql_num_rows($q) > 0)) {
			$i=0;
			while($row=mysql_fetch_assoc($q)) {

				$id=$row["task_id"];
				$data_info["data_arr"][$i]=$row;
				$assigned_arr =$this->getAssignedToIdstArr($row["assigned_to"]);
				$data_info["data_arr"][$i]["assigned_arr"]=$assigned_arr;
				foreach($assigned_arr as $idst) {
					if ((!empty($idst)) && (!in_array($idst, $idst_arr))) {
						$idst_arr[]=$idst;
					}
				}

				$i++;
			}
		}

		$idst_arr =array_unique($idst_arr);
		if(count($idst_arr) > 0) {

			$acl_manager = $GLOBALS["current_user"]->getAclManager();
			$user_info =& $acl_manager->getUsers($idst_arr);
			foreach($idst_arr as $idst) {
				$username =$user_info[$idst][ACL_INFO_FIRSTNAME]." ".$user_info[$idst][ACL_INFO_LASTNAME];
				$data_info["user_info"][$idst] =(!empty($username) ? $username : $acl_manager->relativeId($user_info[$idst][ACL_INFO_USERID]));
			}
		}

		return $data_info;
	}


	function getTaskInfo($id) {

		$res = array();
		$qtxt = "SELECT * "
			." FROM ".$this->getMainTable()." "
			."WHERE task_id='".(int)$id."'";
		if(!$q = $this->_query($qtxt)) return $res;

		if(mysql_num_rows($q) > 0) {
			$res = mysql_fetch_assoc($q);
		}
		return $res;
	}


	function saveData($data) {

		$id=(int)$data["id"];
		$res =$id;

		$project =$data["project"];
		$description =$data["description"];
		$task_type =$data["task_type"];
		$start_date =$GLOBALS["regset"]->regionalToDatabase($data["start_date"]);
		$scheduled_end_date =$GLOBALS["regset"]->regionalToDatabase($data["scheduled_end_date"]);
		$actual_end_date =$GLOBALS["regset"]->regionalToDatabase($data["actual_end_date"]);
		$priority_id =(int)$data["priority_id"];
		$status_id =(int)$data["status_id"];
		$waiting_answer =(int)$data["waiting_answer"];
		$waiting_answer_notes =$data["waiting_answer_notes"];
		$notes =$data["notes"];

		if ($task_type == "customer") {
			$customer_id =(int)$data["customer_id"];
		}

		if ($id == 0) {

			$field_list =(isset($customer_id) ? "customer_id, " : "");
			$field_list.="project, description, task_type, start_date, scheduled_end_date, ";
			$field_list.="actual_end_date, priority_id, status_id, waiting_answer, ";
			$field_list.="waiting_answer_notes, notes";
			$field_val =(isset($customer_id) ? "'".$customer_id."', " : "");
			$field_val.="'".$project."', '".$description."', '".$task_type."', '".$start_date."', ";
			$field_val.="'".$scheduled_end_date."', '".$actual_end_date."', '".$priority_id."', ";
			$field_val.="'".$status_id."', '".$waiting_answer."', '".$waiting_answer_notes."', '".$notes."'";

			$qtxt ="INSERT INTO ".$this->getMainTable()." (".$field_list.") VALUES(".$field_val.")";
			$id =$this->_insQuery($qtxt);

			if ($id > 0) {
				$res =$id;
			}
			else {
				echo $qtxt."<br />".mysql_error();
				die();
			}
		}
		else if ($id > 0) {

			$qtxt ="UPDATE ".$this->getMainTable()." SET ";
			$qtxt.=(isset($customer_id) ? "customer_id='".$customer_id."', " : "");
			$qtxt.="project='".$project."', description='".$description."', ";
			$qtxt.="start_date='".$start_date."', scheduled_end_date='".$scheduled_end_date."', ";
			$qtxt.="actual_end_date='".$actual_end_date."', priority_id='".$priority_id."', ";
			$qtxt.="status_id='".$status_id."', waiting_answer='".$waiting_answer."', ";
			$qtxt.="waiting_answer_notes='".$waiting_answer_notes."', notes='".$notes."' ";
			$qtxt.="WHERE task_id='".$id."'";
			$q =$this->_query($qtxt);
			$res =$id;
		}

		return $res;
	}


	function deleteTask($task_id) {

		$qtxt ="DELETE FROM ".$this->getMainTable()." WHERE task_id='".(int)$task_id."' LIMIT 1";
		$q=$this->_query($qtxt);

		return $q;
	}


	function getAssignedToIdstArr($val) {
		return explode(",", trim($val, ","));
	}


	function getAssignedToIdstStr($val) {
		return ",".implode(",", (array)$val).",";
	}


	function updateAssignedTo($task_id, $assigned_to_arr) {
		$assigned_to =$this->getAssignedToIdstStr($assigned_to_arr);

		$qtxt ="UPDATE ".$this->getMainTable()." SET ";
		$qtxt.="assigned_to='".$assigned_to."' ";
		$qtxt.="WHERE task_id='".(int)$task_id."'";
		$q =$this->_query($qtxt);
		if (!$q) { echo $qtxt; die(); }
		return $q;
	}


	function getStatusColorArr() {
		$res =array();

		$res[_STATUS_NOTSTARTED]="back_color_white";
		$res[_STATUS_INPROGRESS]="back_color_yellow";
		$res[_STATUS_TOBETESTED]="back_color_lightorange";
		$res[_STATUS_TOBEINSTALLED]="back_color_darkorange";
		$res[_STATUS_FINISHED]="back_color_green";
		$res[_STATUS_PLANNED]="back_color_cyan";
		$res[_STATUS_SUSPENDED]="back_color_grey";

		return $res;
	}


}


?>
