<?php
/* $Id: subj_followup.php,v 1.5 2004/07/15 13:24:06 k-fish Exp $ */
error_reporting  (E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
$myEnv["module"] = "calendar";
$myEnv["output"] = "html";

header('P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"'); //MSIE6 P3P header

include("../../config.inc.php");
include(INCLUDEPATH . "container.inc.php");
include(INCLUDEPATH . "mSelectBox.class.php");

// adding file revision into global array
if(function_exists("revisionInit")) revisionInit("\$Revision: 1.5 $", __FILE__);

//// NATYS //// Date langage :
include(CAL1_INC_DIR."date_lang.php");
$_SESSION["date_lang"] = array ("language" => $_SESSION["MGW"]->spkz,
								"lang_dir" => CAL1_DIR."lang/"
								);
///////////////

if(isset($_GET["action"]) || isset($_POST["action"])) $action = (isset($_GET["action"])) ? $_GET["action"] : $_POST["action"];

if(isset($_GET["goto"]) || isset($_POST["goto"])) $goto = (isset($_GET["goto"])) ? $_GET["goto"] : $_POST["goto"];
else $goto="";

//---------------------------
// Abort an appointment : JUST FOR ME....
//---------------------------
if (IsSet($action) && $action=="abort") {
	$id = (int) $_GET["id"];
	$userid=$_SESSION["MGW"]->userid;
	// verif:
	$sql = "SELECT userid,id_class FROM mgw_calendar where id = '".$id."' and userid='$userid'";
    if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
   	//if the appointment is that of the current user  AND if the appointment can be aborted=> ok
	$row=$res->FetchRow();
	if ($res->NumRows() > 0 && ($row["id_class"]==0 || $row["id_class"]==1)) {
		$sql = "UPDATE mgw_calendar SET id_class='3', date=date Where id='$id' and userid='$userid'";    
		if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	}		
	else exit(Lang::getLanguageString("forbidden")."<br> <a href=\"javascript:history.go(-1);\">back</a>");
    
	unset($action);
	redirect("subj_followup.php?&action=view&".SID);
}



//---------------------------
// Validate an appointment :
//---------------------------
if (IsSet($action) && $action=="validate") {
	
	$id = (int) $_GET["id"];
	
	if(isset($_GET["userid"]) || isset($_POST["userid"])) {  // FOR ONE USER
		$userid = (isset($_GET["userid"])) ? $_GET["userid"] : $_POST["userid"];
		
		// verif:
		$sql = "SELECT userid FROM mgw_calendar where id = '".$id."' and userid='$userid'";
		if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
		if ($res->NumRows() > 0) {//if it's an appointment of current user => ok
			
			// validate ONE appointment for ONE participant :
			//determine if appointment can be validated or just on standby (wait for others validations)
			$onStandby = FALSE;
			$sql = "SELECT id_class FROM mgw_calendar WHERE id='$id' AND userid!='$userid'";
			if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
			while ($row=$res->FetchRow()) {
				// if at least one of all is aborted(3) OR subjected(0) => new class = standby
				$onStandby = $onStandby || ( ($row["id_class"]==3 || $row["id_class"]==0) );
			}		
			// if at least one of all is aborted OR subjected => new class = standby
			if ($onStandby) {
				$sql = "UPDATE mgw_calendar SET id_class='1', date=date Where id='$id' and userid='$userid'";    
				if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
			}
			else {
			// if all are on standby => ALL must be validated (class=2)
			$sql = "UPDATE mgw_calendar SET id_class='2', date=date Where id='$id'";    
			if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
			}
		
		}
		else exit(Lang::getLanguageString("forbidden")."<br> <a href=\"javascript:history.go(-1);\">back</a>");

	}
	else { // FOR ALL USERS
		$userid=$_SESSION["MGW"]->userid;
		
		// verif:
		$sql = "SELECT userid FROM mgw_calendar where id = '".$id."' and userid='$userid'";
		if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
		if ($res->NumRows() > 0) {//if it's an appointment of current user => ok
				//validate for all except people who have aborted (class 3):
				$sql = "UPDATE mgw_calendar SET id_class='2', date=date Where id='$id' and id_class!='3'";    
				if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
				
				//send mail to participants who have validated: "The appointment is set..."
//				$GLOBALS['notify']->message($msg, NOTIFY_MAIL, 'u:'.$delegade);
				// + send on screen message			
//	 			$GLOBALS['notify']->message($msg, NOTIFY_SCREEN, 'u:'.$delegade);				
				
				//send mail to participants who don't have validated: "In spite of your "NO" answer, the appointment have been set..."
//				$GLOBALS['notify']->message($msg, NOTIFY_MAIL, 'u:'.$delegade);
				// + send on screen message			
//	 			$GLOBALS['notify']->message($msg, NOTIFY_SCREEN, 'u:'.$delegade);				
				

		}
		else exit(Lang::getLanguageString("forbidden")."<br> <a href=\"javascript:history.go(-1);\">back</a>");
	}
	
		
	unset($action);
	redirect("subj_followup.php?action=view&".SID);	
}



$timemask = $_SESSION["MGW"]->settings["timefmt"];

    $icons = getIconStrings();
	$Cal_icons = getCalIconStrings();
    $icons = array_merge($icons, $Cal_icons);
    // =========================================================
    // set calenderid = userid if calendarid is not set
    // =========================================================
    if (!isset($_SESSION["calendarid"]) || $_SESSION["calendarid"] == "") {
	$_SESSION["calendarid"] = $_SESSION["MGW"]->userid;
	$_SESSION["calendarname"] = $_SESSION["MGW"]->fullusername;
    }


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

    // =========================================================
    // get appointments of day $date
    // =========================================================
    $sql_tag  = date("Ymd", $date);
	$currentuserid = $_SESSION["MGW"]->userid;   

	
	//get data from mgw_calendar_class :
	$classes = array();
	$sql_class = "SELECT * FROM mgw_calendar_class ORDER BY id";
	if(!$res_class = $conn->Execute($sql_class)) exit(showSQLerror($sql_class, $conn->ErrorMsg(), __LINE__, __FILE__));
	while($row_class = $res_class->FetchRow()){
		$classes []= array ("class" => $row_class["class"],
							"color" => $row_class["color"]
							);
	}
				
				
				
	// 2 LOOPS : one for "what i proposed" , and one for what one proposed to me
	for ($l=1;$l<=2;$l++){
		
		if($l==1){
		//all appointment subjected by current user and not validated(class 2):
		$sql = "SELECT DISTINCT id, date
				FROM mgw_calendar WHERE inituserid='$currentuserid' AND id_class!='2'
				GROUP BY date, id
				ORDER BY date";
		}
		else if($l==2){
		//all appointment subjected to current user and not validated(class 2):
		/*$sql = "SELECT DISTINCT b.id
				FROM mgw_calendar a, mgw_calendar b WHERE a.userid='$currentuserid' AND a.inituserid!='$currentuserid' AND a.id = b.id and b.id_class!='2'
				GROUP BY b.date
				ORDER BY b.date";		
		*/
		$sql = "SELECT DISTINCT id
			FROM mgw_calendar WHERE userid='$currentuserid' AND inituserid!='$currentuserid' 
			AND id_class!='2'";
		}		
				
	    if(!$res_first_select = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	//    $row = $res->FetchRow();
	    $num = $res_first_select->RecordCount();
	   
		
		//--------
	
				
		    //-------------------------------------------------------------
		    // loop through result
		    //-------------------------------------------------------------
		    $res_first_select->Move(0);
		    while ($row_first_select = $res_first_select->FetchRow()) {
						
			$sql_appt = "SELECT id_class, date, id_appt_type, id_location_type, subject_summ, subject, location, private, id, duration, availability, telephone, dategroup_id, COUNT(DISTINCT subject) AS appointment_count, inituserid 
				FROM mgw_calendar WHERE id='".$row_first_select["id"]."'
				GROUP BY date, id_class, id_appt_type, id_location_type, subject_summ, subject, location, private, id, duration, availability, telephone, dategroup_id, inituserid  
				ORDER BY date, id_class";
			if(!$res = $conn->Execute($sql_appt)) exit(showSQLerror($sql_appt, $conn->ErrorMsg(), __LINE__, __FILE__));		
			$row = $res->FetchRow();
			
			// compute start/end of appointment in unix-timestamp
			$vmin = $res->UnixTimeStamp($row["date"]);
			$bmin = $vmin + $row["duration"] * 60;
			
			$myid = $row["id"];
			$t = $vmin;
				
			//---- NATYS : appointment type :
				$id_appt_type = $row["id_appt_type"];
				$sql_appt_type = "SELECT * FROM mgw_calendar_appt_type WHERE id=$id_appt_type";
				if(!$res_appt_type = $conn->Execute($sql_appt_type)) exit(showSQLerror($sql_appt_type, $conn->ErrorMsg(), __LINE__, __FILE__));
				$row_appt_type = $res_appt_type->FetchRow();
				$appointment_type = array( 	"text" => Lang::getLanguageString("gentemp_".$row_appt_type["type"]),
											"color"=> $row_appt_type["color"]
										 );
			
			//----- location type
				$id_loc = $row["id_location_type"];
				$sql_loc = "SELECT * FROM mgw_calendar_location_type WHERE id=$id_loc";
				if(!$res_loc = $conn->Execute($sql_loc)) exit(showSQLerror($sql_loc, $conn->ErrorMsg(), __LINE__, __FILE__));
				$row_loc = $res_loc->FetchRow();
				$location_type = Lang::getLanguageString("gentemp_".$row_loc["location_type"]);
		
			//-------------
		
			// $global_class of the subjected appt : 
			// "standby" : nobody has answered "NO"
			// OR 
			// "aborted" : somebody has answered "NO"
				
			// $can_validate : to know if the appt can be validated = all participants have answered
			$can_validate = TRUE;
			
			// $can_validate_for_me : can validate just for me
			$can_validate_for_me = FALSE ;
			
			//$can_abort : can abort just for me
			$can_abort = FALSE;
			
			// $is_already_validated : to know if appt has been already validated = somebody has answered "NO" but the appt was validated ( classes are 2 and 3 but no 0 or 1)
			$is_already_validated = TRUE;
			
			//----- Participants and class (answers)
				if (isset($global_class)) unset($global_class);
				    
				$sql_part = "SELECT b.id, ".$conn->Concat("b.firstname", "' '", "b.lastname")." AS name, inituserid, ".$conn->Concat("c.firstname", "' '", "c.lastname")." AS initusername FROM mgw_calendar a, mgw_users b, mgw_users c WHERE NOT(b.level=".UDELETED.") AND a.id = ".$row["id"]." AND a.userid = b.id AND a.inituserid=c.id";
				//"SELECT * FROM mgw_calendar WHERE id=".$row["id"];
				if(!$res_part = $conn->Execute($sql_part)) exit(showSQLerror($sql_part, $conn->ErrorMsg(), __LINE__, __FILE__));
				if($n = $res_part->RecordCount()>0)
				{
					$parties = array();
					$answers = array();
					while($row_part = $res_part->FetchRow()){
						
						//init username
						//if (!isset($initusername) || (isset($initusername) && $initusername=="")) {
						    $initusername = $row_part["initusername"];
						//}
						//participants:
						$parties []= $row_part;
						//answers:
						$sql_ans = "SELECT id_class FROM mgw_calendar a WHERE a.id ='$myid' AND a.userid='".$row_part["id"]."'";
						if(!$res_ans = $conn->Execute($sql_ans)) exit(showSQLerror($sql_ans, $conn->ErrorMsg(), __LINE__, __FILE__));
						$row_ans = $res_ans->FetchRow();
						
						$answers []= array( "text" => ($row_ans["id_class"]=="1" ? Lang::getLanguageString("class_".$classes["2"]["class"]) : Lang::getLanguageString("class_".$classes[$row_ans["id_class"]]["class"])), // if on standby : participant has validated
											"color" => ($row_ans["id_class"]=="1" ? $classes["2"]["color"] : $classes[$row_ans["id_class"]]["color"])
											);
						
					
						if ( ($row_ans["id_class"]=="1" || $row_ans["id_class"]=="0") && !isset($global_class)) { // no participant has aborted:
						    $global_class = array( 	"idclass" => 1,
													"color" => $classes["1"]["color"]
													);
						}
	
						if ($row_ans["id_class"]=="3") { // at least one participant has aborted:
						    $global_class = array( 	"idclass" => 3,
													"color" => $classes["3"]["color"]
													);
						}
						
						if ($l==1) {
							$can_validate = $can_validate && $row_ans["id_class"]!="0";
						}
						else if($l==2){
							$can_validate = FALSE;
						}
						
						if ($row_part["id"] == $_SESSION["MGW"]->userid) {
							$can_validate_for_me = $row_ans["id_class"]!="1" && $row_ans["id_class"]!="2";
							$can_abort = $row_ans["id_class"]=="0" || $row_ans["id_class"]=="1";
						}
						
						$is_already_validated = $is_already_validated && $row_ans["id_class"]!="0" && $row_ans["id_class"]!="1";
					}
				}
				else $parties = "";
			//-------------
			
			if (!$is_already_validated) { // if not already validated => show it
			    
				$topic_type = $appointment_type["text"];
				$topic_color ="";
	  
				$detlink  = "<td> <a href=\"details.php?id=$myid&userid=".$_SESSION["MGW"]->userid."&".SID."\" class=\"edit\">". $icons["details"] . "</a> </td>";   
				
				
					//"validate" buttons :
					if ($can_validate_for_me) { //can validate just for me
						$validformelink = "<td> <a href=\"javascript:void(0);\" onclick=\"javascript:if(confirm('".Lang::getLanguageString("query_validate")."')){ window.location.href='subj_followup.php?action=validate&id=$myid&userid=".$_SESSION["MGW"]->userid."&".SID."';}\" class=\"edit\">".$icons["validate"]."</a> </td>";    
					}
					else $validformelink ="";
					
					if ($can_validate) { // can validate an appt for ALL
						$validlink = "<td> <a href=\"javascript:void(0);\" onclick=\"javascript:if(confirm('".Lang::getLanguageString("query_validate")."')){ window.location.href='subj_followup.php?action=validate&id=$myid&".SID."';}\" class=\"edit\">".$icons["validateforall"]."</a> </td>";    
					}
					else $validlink ="";
					
					//"edit" button :
					if (is_modifiable_by_current_user($myid,$_SESSION['calendarid'])) {
						$editlink = "<td> <a href=\"index.php?action=editform&id=$myid&date=$vmin&".SID."\" class=\"edit\">". $icons["edit"] . "</a> </td>";	    
					}
					else $editlink ="";
				
				
					if ($can_abort){ //can abort just for me
						//abort appointment
						$abortlink  = "<td><a href=\"javascript:void(0);\" onclick=\"javascript:if(confirm('".Lang::getLanguageString("query_abort")."')){ window.location.href='subj_followup.php?action=abort&id=$myid&".SID."';}\" class=\"delete\">" . $icons["abort"] ."</a></td>";
					}
					else $abortlink = "";
					/*	//NO delete button:
						$dellink = "";
					}
					else {
						//NO abort button:
						$abortlink = "";
					*/	
						//delete appointment
						if (is_modifiable_by_current_user($myid,$_SESSION['calendarid'])) {
							$dellink  = "<td><a href=\"index.php?action=del&delete=all&id=$myid&".SID."\" class=\"delete\">" . $icons["delete"] . "</a></td>";
						}
						else $dellink ="";
					//}
				
				$day_index  =  Lang::getLanguageString("gentemp_weekday_" . (date("w", $t) + 1));
				
				$zeile = array(
						  "global_class" => $global_class,
						  "day" => "<strong>".$day_index."<br>".date_lang("d F", $t)."</strong>",
						  "hour" => "<strong>".date_lang($timemask, $t)."&nbsp;-&nbsp;".date_lang($timemask, $bmin)."</strong>",
						  "topic" => str_decode($row["subject_summ"]),
						  "topic_type" => $topic_type,
						  "topic_color" => $topic_color,
						  "availability" => $row["availability"],
						  "telephone" => $row["telephone"],
						  "initusername" => $initusername,
						  "parties" => $parties,
						  "answers" => $answers,
						  "class"	=> "tab",
						  "location" => str_decode($row["location"]),
						  "location_type" => $location_type.(str_decode($row["location"]) != "" ? "&nbsp;:" : ""),
						  //"rowactions" => $detlink . $icons["space"] . $editlink . $icons["space"] . $dellink . $icons["space"] . $tseditlink . $icons["space"] . $vCallink );
						  "rowactions" => "<table border=\"0\" cellspacing=\"10\" cellpadding=\"0\"><tr>". $detlink . $editlink . $validformelink . $abortlink . $validlink . $dellink . "</tr></table>");
				
				
				if($l==1){
					$smarty->append("td", $zeile);
					}
				else if($l==2){
					$smarty->append("td2", $zeile);
					//print_r($zeile);
					}
					
					
						
				}//and if no validated			
	   		}//end while
	

	}// end for	
	
	//--------
	

    

//    $smarty->assign('header_date',	$text . " ".$additionaltext);
    $smarty->assign('cur_date', 	date(Lang::getLanguageString("gentemp_date_format_php"), $date));
    $smarty->assign('SID', 		SID);
    $smarty->assign('date', 		$date);
    if( Date("Ymd")==Date("Ymd",$date) ) {
	$smarty->assign('menu_today', "yes");
    }
    else {
	$smarty->assign('menu_today', "no");
    }

    $smarty->assign("timefmt", $_SESSION["MGW"]->settings["timefmt"]);

    $smarty->assign("priv",Lang::getLanguageString("gentemp_short_private"));
	$smarty->assign("avail",Lang::getLanguageString("gentemp_short_available"));
	$smarty->assign("part",Lang::getLanguageString("gentemp_short_participants"));
	
	$smarty->assign("goto",$goto);
	
	$smarty->display('calendar_subj_followup.tpl');
    $smarty->clear_assign('action');
    $smarty->clear_assign('holiday');
    $smarty->clear_assign('celebration_day');
    exit();



?>