<?php
/* $Id: crm.class.php,v 1.24 2003/11/08 18:10:57 emailtotom Exp $ */

class CRM {

    function opCreate(){
	global $conn;

	$id = mgw_genID('mgw__seq_contacts_history');
	$company = isset($_POST["company"])?(int) $_POST["company"]:0;
	$person = $conn->QMagic(isset($_POST["person"])?$_POST["person"]:"");
	$date = $conn->DBTimeStamp($_POST["dateYear"]."-".$_POST["dateMonth"]."-".$_POST["dateDay"]." ".$_POST["dateHour"].":".$_POST["dateMinute"]);
	$userid = (int) $_POST["userid"];
	$todo = $conn->QMagic(isset($_POST["todo"])?$_POST["todo"]:"");
	$note = $conn->QMagic(isset($_POST["note"])?$_POST["note"]:"");
	
	queryRights2("root_modules_contact_crm_create");

    $sql = "select id from mgw_companies where (ispublic=1 or owner=".$_SESSION["MGW"]->userid.") and id=".(int)$company;
    if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

    if ($res->RecordCount()==1) {
	  $sql = "INSERT INTO mgw_contacts_history (contactid, contact_company, contact_person, contact_date, contact_userid, contact_todo, contact_comment, lu_user, lu_date) VALUES ($id, $company, $person, $date, $userid, $todo, $note, ".$_SESSION["MGW"]->userid.", ".$conn->DBTimeStamp(time()).")";
	  if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    }

	return true;
    }

    function opUpdate($id){
	global $conn;

	$company = isset($_POST["company"])?(int) $_POST["company"]:0;
	$person = $conn->QMagic(isset($_POST["person"])?$_POST["person"]:"");
	$date = $conn->DBTimeStamp($_POST["dateYear"]."-".$_POST["dateMonth"]."-".$_POST["dateDay"]." ".$_POST["dateHour"].":".$_POST["dateMinute"]);
	$userid = (int) $_POST["userid"];
	$todo = $conn->QMagic(isset($_POST["todo"])?$_POST["todo"]:"");
	$note = $conn->QMagic(isset($_POST["note"])?$_POST["note"]:"");

	queryRights2("root_modules_contact_crm_modify");

    $sql = "select id from mgw_companies where (ispublic=1 or owner=".$_SESSION["MGW"]->userid.") and id=".(int)$company;
    if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

    if ($res->RecordCount()==1) {
  	  $sql="UPDATE mgw_contacts_history SET contact_company=$company, contact_person=$person, contact_date=$date, contact_userid=$userid, contact_todo=$todo, contact_comment=$note, lu_user=".$_SESSION["MGW"]->userid.", lu_date=".$conn->DBTimeStamp(time())." WHERE contactid = ".(int)$id;
	  if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	}

	return true;
    }

    function opDelete($id){
	global $conn;

	queryRights2("root_modules_contact_crm_delete");

    $sql = "select id from mgw_companies a, mgw_contacts_history b where (a.ispublic=1 or a.owner=".$_SESSION["MGW"]->userid.") and a.id=b.contact_company and b.contactid=".(int)$id;
    if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

    if ($res->RecordCount()==1) {
  	  $sql = "DELETE FROM mgw_contacts_history WHERE contactid=".(int)$id;
	  if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    }

	return true;
    }

    function viewDelete($id){
	global $smarty, $conn, $appconf;
	queryRights2("root_modules_contact_crm_delete");

	$sql = "SELECT a.*, b.name1 FROM mgw_contacts_history a LEFT JOIN mgw_companies b ON a.contact_company = b.id WHERE (b.ispublic=1 or b.owner=".$_SESSION["MGW"]->userid.") and contactid=".(int)$id;
	if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	$row = $res->FetchRow();

	$smarty->assign("menuid", "4");
	$smarty->assign("itemid", $id);
	$smarty->assign("parms", str_replace("delete","list",$_SERVER["QUERY_STRING"]));
	$smarty->assign("reallydeleteitem", Lang::getLanguageString("reallydelcontact"));
	$smarty->assign("deleteheader", Lang::getLanguageString("deletecontacth"));
	$smarty->assign("deletedetail1", $row["name1"]);
	$smarty->assign("deletedetail2", $row["contact_date"]);
	$smarty->assign("deletedetail3", $row["contact_person"]);
	$smarty->assign("suclass", "submit");
	$smarty->display($appconf["gentemplates"] ."/delete_item.tpl");

	return true;
    }

    function viewNewForm(){
	global $smarty, $conn;
	queryRights2("root_modules_contact_crm_create");
	include(INCLUDEPATH . "mSelectBox.class.php");
	
	$sb1 = new mSelectBox("userid");
	$sb1->setContentType("sql");
	$sb1->setSQLvalue("id");
	$sb1->setSQLcontent("name");
	$concat=$conn->Concat("lastname", "', '", "firstname");
	$sb1->addContent("SELECT *, $concat AS name FROM mgw_users ORDER BY lastname, firstname");
	$smarty->assign("usersb", $sb1->draw());

	$sb2 = new mSelectBox("company");
	$sb2->setContentType("sql");
	$sb2->setSQLvalue("id");
	$sb2->setSQLcontent("name1");
	$sb2->addContent("SELECT * FROM mgw_companies WHERE (ispublic=1 or owner=".$_SESSION["MGW"]->userid.") ORDER BY name1");
	$sb2->addOption("0", Lang::getLanguageString("chosecompanytext"), "pre");
	$smarty->assign("companysb", $sb2->draw());

	$smarty->assign("suname", "create");
	$smarty->assign("suvalue", Lang::getLanguageString("create"));
	$smarty->assign("suclass", "submit");
	$smarty->assign("mode", "new");
	$smarty->assign("contentheader", Lang::getLanguageString("createnewcontact"));
	$smarty->display('contact_crm_edit.tpl');

	return true;
    }

    function viewEditForm($id){
	global $conn, $smarty;
	queryRights2("root_modules_contact_crm_modify");
	include(INCLUDEPATH . "mSelectBox.class.php");

	$backid = isset($_GET["backid"])?(int) $_GET["backid"]:0;

	$sql = "SELECT a.* FROM mgw_contacts_history a, mgw_companies b WHERE (b.ispublic=1 or b.owner=".$_SESSION["MGW"]->userid.") and a.contactid=".(int)$id;
	if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	$row = $res->FetchRow();

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

	$sb2 = new mSelectBox("company");
	$sb2->setContentType("sql");
	$sb2->setSQLvalue("id");
	$sb2->setSQLcontent("name1");
	$sb2->addContent("SELECT * FROM mgw_companies WHERE (ispublic=1 or owner=".$_SESSION["MGW"]->userid.") ORDER BY name1");
	$sb2->addOption("0", Lang::getLanguageString("chosecompanytext"), "pre");
	$smarty->assign("companysb", $sb2->draw($row["contact_company"]));

	$smarty->assign("td", $row);
	$smarty->assign("id",$id);
	$smarty->assign("endyear", date("Y")+1);
	$smarty->assign("backid",$backid);
	$smarty->assign("suname", "edit");
	$smarty->assign("suvalue", Lang::getLanguageString("edit"));
	$smarty->assign("suclass", "submit");
	$smarty->assign("contentheader", Lang::getLanguageString("editcontact"));
		
	$smarty->display('contact_crm_edit.tpl');

	return true;
    }

    function viewDetails($id){
	global $conn, $smarty;

	$concat = $conn->Concat("lastname","', '","firstname");
	$sql = "SELECT name1, contact_company, contact_person, contact_date, contactid, ".$concat." AS contact_username, contact_todo, contact_comment FROM mgw_contacts_history a LEFT OUTER JOIN mgw_users c ON a.contact_userid = c.id LEFT OUTER JOIN mgw_companies d ON a.contact_company = d.id WHERE (d.ispublic=1 or d.owner=".$_SESSION["MGW"]->userid.") and a.contactid = ".(int)$id;

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

	$row['contact_date'] = $conn->UnixDate($row['contact_date']);
	$row["contact_todo"] = nl2br($row["contact_todo"]);
	$row["contact_comment"] = nl2br($row["contact_comment"]);

	$smarty->assign("td", $row);
	$smarty->display('contact_crm_details.tpl');

	return true;
    }


    function viewDetailsList($id){
	global $conn, $smarty;

	$icons = getIconStrings();
	$concat = $conn->Concat("c.lastname", "', '", "c.firstname");
	$sql = "SELECT d.owner, d.name1, b.contact_person, b.contact_date, b.contactid, ".$concat." AS contact_username FROM mgw_contacts_history a, mgw_contacts_history b LEFT OUTER JOIN mgw_users c ON b.contact_userid = c.id LEFT OUTER JOIN mgw_companies d ON d.id = b.contact_company WHERE (d.ispublic=1 or d.owner=".$_SESSION["MGW"]->userid.") and a.contactid = ".(int)$id." AND a.contact_company = b.contact_company ORDER BY b.contact_date DESC";

	if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	
	while($row = $res->FetchRow()){
	    $row['contact_date'] = $conn->UnixDate($row['contact_date']);
	    $smarty->append("td", $row);
	    $id = $row["contactid"];
	    $smarty->assign("detail_overview", Lang::getLanguageString("detail_view") . " " . $row["name1"]);			
		
	    $detlink = "<a href=\"javascript:openSelector($id, '".SID."')\" class=\"edit\">".$icons["details"]."</a>";
	    // modify only for user with appropriate rights
	    if(queryRights2_bool("root_modules_contact_crm_modify")){
		$editlink = "<a href=\"index.php?mod=contact&amp;obj=crm&amp;view=editform&amp;id=$id&amp;backid=$id&amp;".SID."\" class=\"edit\">".$icons["edit"]."</a>";
	    }
	    else {
		$editlink = "";
	    }
		
	    // delete only for user with appropriate rights
	    if(queryRights2_bool("root_modules_contact_crm_delete")){
		$dellink = "<a href=\"index.php?mod=contact&amp;obj=crm&amp;view=delete&amp;id=$id&amp;backid=$id&amp;".SID."\" class=\"delete\">".$icons["delete"]."</a>";
	    }
	    else {
		$dellink = "";
	    }
		
	    $urls[] = $detlink . $icons["space"] . $editlink . $icons["space"] . $dellink;

	    $smarty->assign('urls', $urls);
	}
    
	$smarty->assign("hascreaterights", queryRights2_bool("root_modules_contact_crm_create"));
	$smarty->assign('at', alphabet_table("mod=contact&amp;obj=crm&amp;sort=alpha&amp;view=list"));

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

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

	$icons = getIconStrings();

	$sql0 = "SELECT contact_company, MAX(contact_date) AS ldate FROM mgw_contacts_history GROUP BY contact_company";
	if(!$res0 = $conn->Execute($sql0)) exit(showSQLerror($sql0));

	if(isset($_GET["sort"]) and $_GET["sort"] == "alpha") {
	    reset($res0);
	    $list = $conn->QMagic($_GET['list']."%");
	    $where = " (";
	    while ($row0=$res0->FetchRow()) $where .= "( contact_company  = ".$row0["contact_company"]." AND contact_date = '".$row0["ldate"]."' AND c.name1 LIKE $list) OR ";
	    $where .= " 1=0)";
	}

	elseif(isset($_POST["op"]) and $_POST["op"] == "qsearch") {
	    reset($res0);
	    $where = " (";
	    $searchterm = $conn->QMagic("%".$_POST["searchterm"]."%");
	    while ($row0=$res0->FetchRow()){
		$where .= "( contact_company  = ".$row0["contact_company"]." AND contact_date = '".$row0["ldate"]."' AND (c.name1 LIKE ".$searchterm." OR c.name2 LIKE ".$searchterm.")) OR ";
	    }
	    $where .= "1=0)";
	}
	else{
	    $where = " (";
	    while ($row0 = $res0->FetchRow()) {
		$where .= "( contact_company = '".$row0["contact_company"]."' AND contact_date = '".$row0["ldate"]."') OR ";
	    }
	    $where .= "1=0)";
	}

	$concat = $conn->Concat("b.lastname","', '","b.firstname");
	$sql2 = "SELECT c.owner, c.name1, c.id, contact_date, contact_person, contactid, ".$concat." AS last_contact_internal FROM mgw_contacts_history a LEFT OUTER JOIN mgw_users b ON a.contact_userid = b.id LEFT OUTER JOIN mgw_companies c ON a.contact_company = c.id WHERE (c.ispublic=1 or c.owner=".$_SESSION["MGW"]->userid.") and ".$where;

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

	while($row = $res2->FetchRow()){
	    $row['contact_date'] = $conn->UnixDate($row['contact_date']);

	    $smarty->append("td", $row);
	    $id = $row["contactid"];
			
	    // aktion urls zusammenbauen
	    $detlink = "<a href=\"index.php?mod=contact&amp;obj=crm&amp;view=detail_list&amp;id=$id&amp;".SID."\" class=\"edit\">".$icons["details"]."</a>";
		
	    // modify only for user with appropriate rights
	    if(queryRights2_bool("root_modules_contact_crm_modify")){
		$editlink = "<a href=\"index.php?mod=contact&amp;obj=crm&amp;view=editform&amp;id=$id&amp;".SID."\" class=\"edit\">".$icons["edit"]."</a>";
	    }
	    else {
		$editlink = "";
	    }
		
	    // delete only for user with appropriate rights
	    if(queryRights2_bool("root_modules_contact_crm_delete")){
		$dellink = "<a href=\"index.php?mod=contact&amp;obj=crm&amp;view=delete&amp;id=$id&amp;".SID."\" class=\"delete\">".$icons["delete"]."</a>";
	    }
	    else {
		$dellink = "";
	    }
		
	    $urls[] = $detlink . $icons["space"] . $editlink . $icons["space"] . $dellink;
	    $smarty->assign('urls', $urls);
	}

	$smarty->assign("hascreaterights", queryRights2_bool("root_modules_contact_crm_create"));
	$smarty->assign('at', alphabet_table("mod=contact&amp;obj=crm&amp;sort=alpha&amp;view=list"));
	$smarty->assign('suclass', "submit");

	$smarty->display('contact_crm_list.tpl');

	return true;
    }
}
?>