<?php
/* $Id: month.php,v 1.84 2006/01/09 22:54:26 leyeti Exp $ */
error_reporting  (E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
$myEnv["module"] = "calendar";
$myEnv["output"] = "html";

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

//include(CAL1_INC_DIR."check_settings.inc.php");

// adding file revision into global array
if(function_exists("revisionInit")) revisionInit("\$Revision: 1.84 $", __FILE__);
		
//////////////////////////////////////////////////////////////////////////////////////////
/// SET variable $date
//////////////////////////////////////////////////////////////////////////////////////////
/// if $date is not passed, set $date to today
/// if $gotodate (is passed by submit for datesearch in main template of day-view) is set,
///    check validity of gotodate and set date to gotodate
//////////////////////////////////////////////////////////////////////////////////////////

$timemask = $_SESSION["MGW"]->settings["timefmt"];
$concat=$conn->Concat("firstname", "' '", "lastname");

if ((!isset($_GET["date"]) || $_GET["date"]=="") && (!isset($_POST["gotodate"]) || $_POST["gotodate"]=="") ){
	$date = mktime(0,0,0, date("m", time()), date("d", time()), date("Y", time()));
	$_SESSION['calendar_year'] = ( isset($_SESSION["calendar_year"]) && (int)$_SESSION["calendar_year"] > 0) ? $_SESSION["calendar_year"] : date("Y", $date);
	$_SESSION['calendar_month'] = ( isset($_SESSION["calendar_month"]) && (int)$_SESSION["calendar_month"] > 0 && (int)$_SESSION["calendar_month"] < 13) ? $_SESSION["calendar_month"] : date("m", $date);
} else if (isset($_POST["gotodate"])) {
	if (isset($_GET["gdatum"])) { //wap only
		$gmonat = substr($_GET["gdatum"],3,2);
		$gtag = substr($_GET["gdatum"],0,2);
		$gjahr = substr($_GET["gdatum"],6,4);
	} else {
		$gmonat = (int)$_POST["gmonat"];
		$gtag = (int)$_POST["gtag"];
		$gjahr = (int)$_POST["gjahr"];
	}

	$gtag = ($gtag > 0) ? $gtag : $_SESSION['calendar_day'];
	$gmonat = ($gmonat > 0) ? $gmonat : $_SESSION['calendar_month'];
	$gjahr = ($gjahr > 0) ? $gjahr : $_SESSION['calendar_year'];

	if (checkdate($gmonat, $gtag, $gjahr)){
		$date  = mktime(0,0,0, $gmonat, $gtag, $gjahr);
		$monat = $gmonat;
		$jahr  = $gjahr;
		$_SESSION['calendar_year'] = $gjahr;
		$_SESSION['calendar_month'] = $gmonat;
	} else if (!isset($_GET["date"])) {
		$date = mktime(0,0,0, date("m", time()), date("d", time()), date("Y", time()));
		$_SESSION['calendar_year'] = ((int)$_SESSION["calendar_year"] > 0) ? $_SESSION["calendar_year"] : date("Y", $date);
		$_SESSION['calendar_month'] = ((int)$_SESSION["calendar_month"] > 0 && (int)$_SESSION["calendar_month"] < 13) ? $_SESSION["calendar_month"] : date("m", $date);
	}
} else {
     $_SESSION['calendar_year'] = ( isset($_SESSION["calendar_year"]) && (int)$_SESSION["calendar_year"] > 0) ? $_SESSION["calendar_year"] : date("Y", $_GET["date"]);
     $_SESSION['calendar_month'] = ( isset($_SESSION["calendar_month"]) && (int)$_SESSION["calendar_month"] > 0 && (int)$_SESSION["calendar_month"] < 13) ? $_SESSION["calendar_month"] : date("m", $_GET["date"]);
}

//$mondate = date("Ym", $date);
$anzahl_tage = date("t",$date); // Anzahl Tage im Monat
$mon_start = mktime(0,0,0,date("m",$date),1,date("Y", $date))+1;
$mon_ende = mktime(0,0,0,date("m",$mon_start)+1,1,date("Y", $mon_start))-1;
$mende1 = mktime(0,0,0,date("m",$date),date("t",$date),date("Y",$date));
$ldays = 7 - date("w",$mende1); //weekday os last day in month
if ($ldays < 7) $mon_ende += (86400 * $ldays);
$mondate1 = date("Ymd",$mon_ende);


$date_str =  str_pad( date("d", $date).date("m", $date).date("Y", $date),8,"0",STR_PAD_LEFT);
$smarty->assign("date_str", $date_str);

// =======================
//  calendar change
// =======================
if (isset($_POST["new_calendarid"])){
	if ($_POST["new_calendarid"] == "all") {
		$_SESSION['calendarid'] = "all";
		$_SESSION['calendarname'] = Lang::getLanguageString("calendarownerall"); // translated all
	} else {
		$sql = "SELECT id, $concat AS name FROM mgw_users WHERE NOT(level=".UDELETED.") AND id = ".$_POST["new_calendarid"];
		if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
		$row = $res->FetchRow();

		$_SESSION['calendarid']   = $row["id"];
		$_SESSION['calendarname'] = $row["name"];	// Owner - Name of calendar
	
	}
}

// =======================
// monthview back
// =======================
if (IsSet($_GET["action"]) && $_GET["action"] == "mback") {
	if ($_SESSION['calendar_month'] == 1) {
		$_SESSION['calendar_month'] = 12;
		$_SESSION['calendar_year']--;
	} else {
		$_SESSION['calendar_month']--;
	}
	unset($_GET["action"]);
}

// =======================
// monthview next
// =======================
if (IsSet($_GET["action"]) && $_GET["action"] == "mforw") {
	if ($_SESSION['calendar_month'] == 12) {
		$_SESSION['calendar_month'] = 1;
		$_SESSION['calendar_year']++;
	} else {
		$_SESSION['calendar_month']++;
	}
	unset($_GET["action"]);
}

// =======================
// year back
// =======================
if (IsSet($_GET["action"]) && $_GET["action"] == "yback") {
	$_SESSION['calendar_year']--;
	unset($_GET["action"]);
}

// =======================
//  year forward
// =======================
if (IsSet($_GET["action"]) && $_GET["action"] == "yforw") {
	$_SESSION['calendar_year']++;
	unset($_GET["action"]);
}

// =======================
// entry Monthview
// =======================
if(!isset($_GET["action"])){
	if (!IsSet($_SESSION["calendarid"])) {
		$sql = "SELECT $concat AS name FROM mgw_users WHERE NOT(level=".UDELETED.") AND id = ".$_SESSION["MGW"]->userid;
		if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
		$row = $res->FetchRow();
		$_SESSION['calendarid']	 = $_SESSION["MGW"]->userid;
		$_SESSION['calendarname'] = $row["name"];	// Owner - Name of calendar

	}

	////////////////////////////////////////////////////////////////////////
    // show user list as possible calendar owners
    ////////////////////////////////////////////////////////////////////////
    include_once("inc/user_list.inc.php");
	
	/*
	// select owner
	$sql = "SELECT id, $concat AS name FROM mgw_users ORDER BY name";

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

	while ($td = $res->FetchRow()) {
		$smarty->append("td2", $td);
	}
	*/

	// Einstieg Tagesansicht : Festlegung Kalenderid
	if ($_SESSION['calendarid']=="all") {
		$sql_owner_part="";
	} else {
		$sql_owner_part="userid = ".$_SESSION['calendarid']." AND";
	}

//	$sql = "SELECT * FROM mgw_calendar WHERE $sql_owner_part (SUBSTRING(date,1,8) >= '".$mondate."01' AND SUBSTRING(date,1,8) <= '$mondate1') AND id_class!='3' ORDER BY date";
	$sql_mon_start = $conn->DBTimeStamp($mon_start);
	$sql_mon_ende = $conn->DBTimeStamp($mon_ende);
	$sql = "SELECT * FROM mgw_calendar 
        	WHERE $sql_owner_part date >= $sql_mon_start AND 
			date <= $sql_mon_ende AND 
			id_class!='3' 
			ORDER BY date";

	if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	$num = $res->RecordCount();

	$kwstart = get_weeknumber($mon_start);

	// get birthdays
	$date_arr = Array();
	if($_SESSION["MGW"]->settings["calendar_show_birthdays"]) {
		$concat = $conn->Concat("'* '","firstname","' '","lastname");
		$bd_start = $conn->DBDate(mktime(0,0,1,date("m",$mon_start),1,date("Y",$mon_start)));
		$bd_end = $conn->DBDate(mktime(23,59,59,date("m",$mon_start)+1,0,date("Y",$mon_start)));
		//SUBSTRING(birthday,6,2)='".date("m",$mon_start)."' AND 
		$bdsql = "SELECT birthday, $concat AS jubilee 
        		  FROM mgw_contacts 
				  WHERE birthday >= $bd_start AND
				  birthday <= $bd_end AND 
				  (ispublic='1' OR owner='".$_SESSION["MGW"]->userid."')";
		if(!$bdres = $conn->Execute($bdsql)) exit(showSQLerror($bdsql, $conn->ErrorMsg(), __LINE__, __FILE__));
		while($bdrow = $bdres->FetchRow()){
			$kwn = get_weeknumber($res->UnixTimeStamp(date("Y",$mon_start)."-".substr($bdrow["birthday"],5,5)));
			$z_ind   = $kwn - $kwstart;
			$s_ind   = date("w", $res->UnixTimeStamp(date("Y",$mon_start)."-".substr($bdrow["birthday"],5,5)))-1;
			if ($s_ind==-1) $s_ind=6;
			//hack:
			if (!IsSet($date_arr[$z_ind][$s_ind])) {
			    $date_arr[$z_ind][$s_ind] = "";
			}
			$date_arr[$z_ind][$s_ind] .= "<strong>".$bdrow["jubilee"]."</strong><br />";
		}
	}
	
	
	while ($row = $res->FetchRow()){
		if (get_celebrate_days($res->UnixTimeStamp($row["date"]), $_SESSION["MGW"]->settings["calendar_holiday_system"]) != "" ) $kl = "feiertag";
		else if (date("dmY", $res->UnixTimeStamp($row["date"])) == date("dmY", mktime(0,0,1, date("m",time()), date("j", time()), date("Y", time())))) $kl = "heute";
		else if (( (date("w", $res->UnixTimeStamp($row["date"])))%7 == 6) || ((date("w", $res->UnixTimeStamp($row["date"])))%7 ==0)) $kl = "wochenende";
		else $kl = "tab"; //css class

		$kwn = get_weeknumber($res->UnixTimeStamp($row["date"]));
		
		if($kwn < $kwstart) $kwstart = 0;
		
		$z_ind   = $kwn - $kwstart;
		$s_ind   = date("w", $res->UnixTimeStamp($row["date"]))-1;
		if ($s_ind==-1) $s_ind=6;
		$end_date = $res->UnixTimeStamp($row["date"]) + $row["duration"]*60;
		if (($row["private"]==0) || ($row["private"]==1 && $_SESSION["MGW"]->userid == $row["userid"])) {
			if(!IsSet($date_arr[$z_ind][$s_ind]) || !strstr($date_arr[$z_ind][$s_ind], date($timemask, $res->UnixTimeStamp($row["date"])))){
				
				//----- 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();
					$id_class = $row["id_class"];
					if ($id_class!=2) {
					    // appointment is subjected or on standby:
						$sql_class = "SELECT * FROM mgw_calendar_class WHERE id=$id_class";
						if(!$res_class = $conn->Execute($sql_class)) exit(showSQLerror($sql_class, $conn->ErrorMsg(), __LINE__, __FILE__));
						$row_class = $res_class->FetchRow();
						$appointment_type = array( 	"text" => Lang::getLanguageString("gentemp_".$row_appt_type["type"])."&nbsp;:<BR>".Lang::getLanguageString("class_".$row_class["class"]),
												"color"=> $row_class["color"]
											 	 );
					}
					else {
						$appointment_type = array( 	"text" => Lang::getLanguageString("gentemp_".$row_appt_type["type"]),
												"color"=> $row_appt_type["color"]
											 );
					}
				////////////////////////////
				$bg_color = $appointment_type["color"];
				// here details on a day :
			//	$date_arr[$z_ind][$s_ind] .= "<strong>". date($timemask, $res->UnixTimeStamp($row["date"])) . /* NATYS "<br>". */ "&nbsp;:&nbsp;".
		  	//  "</strong><a href=\"details.php?action=editform&id=".$row["id"]."&".SID."\" class=\"edit\">" . "<FONT STYLE=\"background-color:{$bg_color};\">" . short_string(str_decode($row["subject_summ"]),$max_subject_length) . "</FONT></a><br />";
				
				//hack:
				if (!IsSet($date_arr[$z_ind][$s_ind])) {
				    $date_arr[$z_ind][$s_ind] = "";
				}
				$date_arr[$z_ind][$s_ind] .= "<a href=\"details.php?action=editform&id=".$row["id"]."&".SID."\" class=\"edit\" 
											 onmouseover=\"return overlib('".jsencode($appointment_type["text"]."&nbsp;:&nbsp;".str_decode($row["subject_summ"]))."',FGCOLOR,'#FFFFDF',STATUS,' ');\" onmouseout=\"return nd();\">
											 <strong><FONT STYLE=\"background-color:{$bg_color};\">".date($timemask, $res->UnixTimeStamp($row["date"])). "</FONT></strong>
											 </a><br />";
			
		}
	    else {
				$date_arr[$z_ind][$s_ind] = preg_replace("~(.*)".date($timemask, $res->UnixTimeStamp($row["date"])).".*</a><br />(.*)~msiU","\\1<strong>". date($timemask, $res->UnixTimeStamp($row["date"])) . "<br>".
		    	"</strong><a href=\"index.php?action=sel&date=".$res->UnixTimeStamp($row["date"])."&".SID."\" class=\"edit\">" .Lang::getLanguageString("temp_row_label_1") . "</a><br />\\2",IsSet($date_arr[$z_ind][$s_ind]) ? $date_arr[$z_ind][$s_ind] : "");
			}
		}
		else {
	    $date_arr[$z_ind][$s_ind] .= "<strong>". date($timemask, $res->UnixTimeStamp($row["date"])) . " " . "</strong>" . "Privat" . "<br />";
		}
	}

	// start month
	if (date("w", $mon_start)!= 0) $anzahl_zeilen = ceil(($anzahl_tage-1+date("w", $mon_start))/7);
	else $anzahl_zeilen = ceil(($anzahl_tage-1+7)/7);

	$start_ind  = date("w", $mon_start)-1;
	if ($start_ind == -1) $start_ind=6;
	$erst_tag   = mktime(0,0,1,date("m", $mon_start), date("j", $mon_start)-$start_ind, date("Y", $mon_start));
	$akt_tag = $erst_tag;

	// Monatstabelle füllen ($anzahl_zeile, 7) Tabelle
	for ($s = 0; $s <= 7*$anzahl_zeilen-1; $s++){
		if (($s%7) == 0) {
			unset($zeile);
			$zeile["kw"] = "<a class=\"navlink\" href=\"week.php?date=$akt_tag&".SID."\">".get_weeknumber($akt_tag)."</a>";
			$zeile["height"] = 80;
		}

		$w_ind = date("D", $akt_tag);
		$col_ind = "col_$w_ind";

		if (($akt_tag > $mon_start && $akt_tag <= $mon_ende) || ($akt_tag == $mon_start && $s >= $start_ind)) {
			$z  = ceil(($s+1)/7)-1;
			$t  = ($s % 7);
			if (get_celebrate_days($akt_tag, $_SESSION["MGW"]->settings["calendar_holiday_system"]) != "" ) $zeile[$col_ind] = "feiertag";
			else if ($akt_tag == mktime(0,0,1, date("m",time()), date("j", time()), date("Y", time()))) $zeile[$col_ind] = "heute";
			else if (($s%7 == 6) || ($s%7 ==5)) $zeile[$col_ind] = "wochenende";
			else $zeile[$col_ind] = "tab";
			// HERE : details 
			$zeile[$w_ind] = "<a class=\"$zeile[$col_ind]\" href=\"index.php?date=$akt_tag&".SID."\">".date("d", $akt_tag)."  ". get_celebrate_days($akt_tag, $_SESSION["MGW"]->settings["calendar_holiday_system"])."</a><br>". "<b> ". "</b>".(IsSet($date_arr[$z][$t]) ? $date_arr[$z][$t] : "");
			$akt_tag = mktime(0,0,1, date("m", $akt_tag), date("j", $akt_tag)+1, date("Y", $akt_tag));
		}	else{
			$zeile[$w_ind] = "&nbsp";
			$zeile[$col_ind] = "stand";
			$akt_tag = mktime(0,0,1, date("m", $akt_tag), date("j", $akt_tag)+1, date("Y", $akt_tag));
		}

		
		if (($s%7)==6) $smarty->append("cm", $zeile);
	}

	if (!isset($jahr)) $jahr = date("Y", $date);
	if (!isset($monat)) $monat = date("m", $date);

	$kalender  = get_monthview_static($date, $_SESSION['calendar_year'], $_SESSION['calendar_month']);
	$kalendername = "<span style=\"color:#000000;\">".$_SESSION['calendarname']."</span>";
	$pmonth  = mktime(0,0,0, date("m", $date)-1,1,date("Y", $date))+1;
	$nmonth  = mktime(0,0,0, date("m", $date)+1,1,date("Y", $date))+1;

	$weiter = "<a class=\"navlink\" href=\"month.php?date=$nmonth&".SID."\" style=\"text-decoration:none;\">". Lang::getLanguageString("forward") .">></a>";
	$zurueck= "<a class=\"navlink\" href=\"month.php?date=$pmonth&".SID."\" style=\"text-decoration:none;\"><< " . Lang::getLanguageString("back") . "</a>";
	$month_var = "gentemp_month_name_" . date("n", $date);
	
	$text   = /* NATYS : Lang::getLanguageString("gentemp_month") . " " . */Lang::getLanguageString("$month_var") . "&nbsp;" . date("Y", $date);
	
	//appt type legend :
	$smarty->assign("appt_type_legend",get_appt_type_legend());
	
	$smarty->assign('SID', SID);
	$smarty->assign('header_date', $text);
	$smarty->assign('kalender', $kalender);
	$smarty->assign('nav_links', $zurueck);
	$smarty->assign('nav_rechts', $weiter);
	$smarty->assign('calendar_owner', $kalendername);
	$smarty->assign('date', $date);
	$smarty->assign('inh', "month.php?action=inh&date=$date&sid=".SID);

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