<?php 

if(!defined('APP_INCLUDE')){ die('invalid inclusion'); }
 
function gmtoffset() {
	global $db;
	# default 00:00 should be +01:00
	$offset = "+01:00";
	# set a base 00:00 as time_zone to get a good check 
	$db->Execute("set time_zone ='+00:00'");
	# Get MYSQL timestamp

	$time = time();
	$now = date("Y-m-d H:i:s", $time);

	$q = "SELECT UNIX_TIMESTAMP('". $now ."')";
	$result = $db->Execute($q); 

	if ($data = $result->FetchRow()) {
		$mysql_timestamp = (int)$data[0];
	}
	# Get PHP timestamp
	$php_timestamp = $time;
	
	# check if the query went good..	
	if(!empty($mysql_timestamp)){
		$dif = $mysql_timestamp - $php_timestamp;
		$hours = floor($dif / 3600);
		if($hours > 0){
			$offset = "+{$hours}:00";
		} else {
			$offset = "{$hours}:00";
		}
	}
	return $offset;
}

function SyncTimezones($profile) {
	global $db,$system_warning;
	# the timezone set in the profile should be used if available
	# both PHP and MYsql should use that timezone if possible
	
	if(empty($profile->profilename)){
		return;
	}
	
	if($profile->timezone == "System"){
		$offset = gmtoffset();
		$q = "set time_zone = '".$offset."'";
		@$db->Execute($q);	
		return;
	}

	if ($profile->timezone!="") {
		$setzone = $profile->timezone;
		date_default_timezone_set($setzone);
	} else {
		$setzone = date_default_timezone_get();
	}
	
	$q = "set time_zone = '".$setzone."'";
	@$db->Execute($q);
	
    $result = $db->Execute("SELECT @@session.time_zone;"); 
    if ($data = $result->FetchRow()) {

        if ($data[0]==$setzone) {
           # Success
        } else {
			# new way, try this:
			$offset = gmtoffset();
			$q = "set time_zone = '".$offset."'";
			@$db->Execute($q);

        }                    
    } else {
        $system_warning = "Unknown Error: Mysql returned no timezone at all. We failed setting the mysql timezone.";
    }
}

function DateToTimestamp($min,$max) {
	global $from,$to, $lang_date;
	
	$minD = rawurldecode($min);
	$maxD = rawurldecode($max);
	//dump($max);
	//dump($maxD);
	$cformat = GetCustomDateFormat("PHP",true);

	$format = [];
	foreach($cformat as $k => $v){
		# 1,3,5 are the seperators in the format
		if($k == 1 || $k == 3 || $k == 5){
			$minD = str_replace($v,",",$minD);
			$maxD = str_replace($v,",",$maxD);			
		}else{
			if(!empty($v)){
				$format[] = $v;
			}
		}
	}
	
	$fromparts = explode(",", $minD);
	$toparts = explode(",", $maxD);
		
	if(!isset($format[3]) || empty($format[3])){
		if(isset($fromparts[3])){
			unset($fromparts[3]);
		}
		if(isset($toparts[3])){
			unset($toparts[3]);
		}
	}
	
	$fparts = [];
	$tparts = [];
	$i = 0;

	if(count($fromparts) == count($format)){
		foreach($format as $f => $p){
			# check for month		
			if(strtolower($p) == "m"){
				if(is_numeric($fromparts[$i])){
					# it is numeric so just set it for mktime later on..
					$fparts["month"] = $fromparts[$i];
					$tparts["month"] = $toparts[$i];
				} else {
					# convert string to number for mktime...
					for($ij=1;$ij<=12;$ij++){
						//if(strtolower(date("M", mktime(0, 0, 0, $ij, 1, 0))) == strtolower($fromparts[$i])){
						//echo strtolower(LogaDate(array("M"), mktime(0, 0, 0, $ij, 1, 0))). " - ".strtolower($fromparts[$i]) ."<br>";
						//add international support (daterangepicker locales must match PHP!)
						
						if(strtolower(LogaDate(array("M"), mktime(0, 0, 0, $ij, 1, 0))) == strtolower($fromparts[$i]) || strtolower(date("M", mktime(0, 0, 0, $ij, 1, 0))) == strtolower($fromparts[$i])){
							$fparts["month"] = $ij;
							
						} else {

						}
						if(strtolower(LogaDate(array("M"), mktime(0, 0, 0, $ij, 1, 0))) == strtolower($toparts[$i]) || strtolower(date("M", mktime(0, 0, 0, $ij, 1, 0))) == strtolower($toparts[$i])){
							$tparts["month"] = $ij;

						} else {
							//echo LogaDate(array("M"), mktime(0, 0, 0, $ij, 1, 0)) . " != ".$toparts[$i];
						}						
					}

					if(empty($fparts["month"]) || empty($tparts["month"])) {
						// dump($fromparts[$i]);
						// dump(LogaDate(array("M"), mktime(0, 0, 0, $ij, 1, 0)));
						// dump(date("M", mktime(0, 0, 0, $ij, 1, 0)));
					
						// This might me a month string in a language other than english that we're not using now, let's do a lookup
						foreach($lang_date as $dstrings) {
							$key = array_search($fromparts[$i], $dstrings["monthsShort"]);
							if ($key !== false) {
    							// Found...
    							$fparts["month"] = $key+1;
							}
							$key = array_search($toparts[$i], $dstrings["monthsShort"]);
							if ($key !== false) {
    							// Found...
    							$tparts["month"] = $key+1;
							}
						}
					}
				}
			}			

			if($p == "d"){
				$fparts["day"] = $fromparts[$i];
				$tparts["day"] = $toparts[$i];
			}
			if($p == "Y"){
				$fparts["year"] = $fromparts[$i];
				$tparts["year"] = $toparts[$i];
			}
			$i ++;
		}
		$from = mktime(0,0,0,$fparts["month"],$fparts["day"],$fparts["year"]);
		$to = mktime(23,59,59,$tparts["month"],$tparts["day"],$tparts["year"]);
	} else {
		$from = strtotime($min." 00:00:00");
		$to = strtotime($max." 23:59:59");
	}

	$r['from'] = $from;
	$r['to'] = $to;
	//exit();
	return $r;
}

function newDateSelector($from,$to) {
  $minimumDate=date("m/d/Y", $from);
  $maximumDate=date("m/d/Y", $to);
  ?>
  <table style="border-collapse:collapse;vertical-align:top;"
        cellpadding="3" cellspacing="0" border=0>
          <tr>
            <td>
              <div style="text-align:center;">
                <?php echo _DATE_FROM;?> <input class="logaholic_qdate" type="text" name="minimumDate" style="width:75px;" value="<?php echo $minimumDate; ?>" alt="MM/DD/YYYY" onclick="date_selector.showDateSelector('minimumDate');">
                 <?php echo _DATE_TO;?>
                <input class="logaholic_qdate" type="text" name="maximumDate" style="width:75px;"
                value="<?php echo $maximumDate; ?>" alt="MM/DD/YYYY" onclick="date_selector.showDateSelector('maximumDate' );">
              </div>
              <div id="dateSelectorPane" onmouseover="indatediv()" onmouseout="outdatediv()"></div>
              <!-- this is some idiotic fix for the IE problem that select shine though any div, but it doesn't work right-->
              <iframe id="dateSelectorPaneIF" class="dateSelectorPaneIF"></iframe>
            </td>
          </tr>
      </table>
      <script language="javascript" type="text/javascript">
         date_selector.init(window.document.forms['form1']); 
      </script>  
  <?php
}

function DateSelector($from = 0,$to = 0) {
    echo "<table class='generic-dateselector'><tr><td><label>"._DATE_FROM.":</label>";
    // From Day
    echo "<select name=fday>";
    $i=1;
    $fd = date("d",$from);
    while ($i <=31) {
        if ($i == $fd) {
            $s="selected";
        } else {
            $s="";
        }
        echo "<option value=$i $s> $i";
        $i++;
    }
    echo "</select>";
    
    // From Month
    echo "<select name=fmonth>";
    $i=1;
    $fm = date("m",$from);
    while ($i <=12) {
        if ($i == $fm) {
            $s="selected";
        } else {
            $s="";
        }
        echo "<option value=$i $s> " . date("M",mktime(0,0,0,$i,1,date("Y")));
        $i++;
    }
    echo "</select>";

    // From Year
    echo "<select name=fyear>";
    $i=date("Y")-15;
    $n=$i+30;
    $fy = date("Y",$from);
    while ($i <= $n) {
        if ($i == $fy) {
            $s="selected";
        } else {
            $s="";
        }
        echo "<option value=$i $s> $i";
        $i++;
    }
    echo "</select>";
    echo "</td><td><label>"._DATE_TO.":</label>";
    
    // To Day
    echo "<select name=tday>";
    $i=1;
    $td = date("d",$to);
    while ($i <=31) {
        if ($i == $td) {
            $s="selected";
        } else {
            $s="";
        }
        echo "<option value=$i $s> $i";
        $i++;
    }
    echo "</select>";
    
    // To Month
    echo "<select name=tmonth>";
    $i=1;
    $tm = date("m",$to);
    while ($i <=12) {
        if ($i == $tm) {
            $s="selected";
        } else {
            $s="";
        }
        echo "<option value=$i $s> " . date("M",mktime(0,0,0,$i,1,date("Y")));
        $i++;
    }
    echo "</select>";

    // To Year
    echo "<select name=tyear>";
    $i=date("Y")-15;
    $n=$i+30;
    $ty = date("Y",$to);
    while ($i <= $n) {
        if ($i == $ty) {
            $s="selected";
        } else {
            $s="";
        }
        echo "<option value=$i $s> $i";
        $i++;
    }
    echo "</select>";
    echo "</td></tr></table>";
}

function QuickDate($from,$to) {
 global $quickdate;
 
    echo "<select name=quickdate class=\"logaholic_qdate\" onmousedown=\"Qdate();\">";
    if ($quickdate) {
         echo "<option value=\"\"> $quickdate";
    } else {
        echo "<option value=\"\"> "._QUICKDATE."</option>";
    }
    echo "<option value=\""._TODAY."\">"._TODAY."</option>";
    echo "<option value=\""._YESTERDAY."\">"._YESTERDAY."</option>";
    echo "<option value=\""._LAST_24_HOURS."\">"._LAST_24_HOURS."</option>";
    echo "<option value=\""._LAST_7_DAYS."\">"._LAST_7_DAYS."</option>";
    echo "<option value=\""._LAST_14_DAYS."\">"._LAST_14_DAYS."</option>";
    echo "<option value=\""._LAST_30_DAYS."\">"._LAST_30_DAYS."</option>";
    echo "<option value=\""._THIS_MONTH."\">"._THIS_MONTH."</option>";
    echo "<option value=\""._LAST_MONTH."\">"._LAST_MONTH."</option>";
    echo "<option value=\""._LAST_3_MONTHS."\">"._LAST_3_MONTHS."</option>";
    echo "<option value=\""._ALL_TIME."\">"._ALL_TIME."</option>";
    
    echo "</select>";
}

/**
* Timezone settings. We only want to do stuff if it's PHP 5.1+
* We only want to set the timezone if it is actually different 
* from the system timezone, because otherwise mysql will loose 
* DST ability unless the timezone tables are loaded (see mysql manual)
* (Since we can't rely on those tables being loaded, we set it using GMT +-
* but that is probably the reason it looses DST.)
* So, we really only want to mess with this if we really have to.
*/
//this piece of code should be moved really, to common
/**
* Now set up the date variables
*/
$dateFormat = array(
	"format1" => "d",
	"seperator1" => " ",
	"format2" => "M",
	"seperator2" => " ",
	"format3" => "Y",
	"seperator3" => " ",
	"format4" => ""				
);
$dateFormat = json_encode($dateFormat);

//add some date related stuff
$lang_date['dutch']['months'] = explode("_", 'januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december');
$lang_date['dutch']['monthsShort'] = explode("_",'jan_feb_mrt_apr_mei_jun_jul_aug_sep_okt_nov_dec');

$lang_date['french']['months'] = explode("_", 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre');
$lang_date['french']['monthsShort'] = explode("_",'janv._févr._mars_avril_mai_juin_juil._août_sept._oct._nov._déc.');

$lang_date['italian']['months'] = explode("_", 'gennaio_febbraio_marzo_aprile_maggio_giugno_luglio_agosto_settembre_ottobre_novembre_dicembre');
$lang_date['italian']['monthsShort'] = explode("_",'gen_feb_mar_apr_mag_giu_lug_ago_set_ott_nov_dic');

$lang_date['german']['months'] = explode("_", 'Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember');
$lang_date['german']['monthsShort'] = explode("_",'Jan_Feb_Mär_Apr_Mai_Jun_Jul_Aug_Sep_Okt_Nov_Dez');

$lang_date['spanish']['months'] = explode("_", 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre');
$lang_date['spanish']['monthsShort'] = explode("_",'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic');

$lang_date['portuguese']['months'] = explode("_", 'Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro');
$lang_date['portuguese']['monthsShort'] = explode("_",'Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez');


if (function_exists("date_default_timezone_get")) {    
    # only do this if we are already logged in 
	if (function_exists("LoggedIn")) { 
		if (LoggedIn()==true) {
			if (!isset($profile) && !empty($conf) && $conf!="newcnf") { 
				$profile = new SiteProfile($conf);
				SyncTimezones($profile);
			} 
		}
	}
}

if (!empty($_REQUEST['minimumDate']) && !empty($_REQUEST["maximumDate"])) {
	// set the session values
	$_SESSION["minimumDate"]= $_REQUEST['minimumDate'];
	$_SESSION["maximumDate"]= $_REQUEST['maximumDate'];
	$r = DateToTimestamp($_SESSION["minimumDate"], $_SESSION["maximumDate"]);
	if(empty($reporting)) {
		$_SESSION["from"] = $r['from'];
		$_SESSION["to"] = $r['to'];
	}
} else if (!empty($_SESSION['from']) && !empty($_SESSION["to"])) {	
	//dump($_SESSION)		;
	//exit();
	//$r = DateToTimestamp($_SESSION["minimumDate"], $_SESSION["maximumDate"]);	
	$from = $_SESSION["from"];
	$to = $_SESSION["to"];
}

if (isset($_REQUEST["quickdate"])) { $quickdate = $_REQUEST["quickdate"]; }

if (!isset($quickdate)) {$quickdate="";}

if ($quickdate==_TODAY) {
	 $from   = mktime(0,0,0,date("m"),date("d"),date("Y"));
	 $to     = mktime(23,59,59,date("m"),date("d"),date("Y"));
}
if ($quickdate==_YESTERDAY) {
	 $from   = mktime(0,0,0,date("m"),date("d")-1,date("Y"));
	 $to     = mktime(23,59,59,date("m"),date("d")-1,date("Y"));
}
if ($quickdate==_LAST_24_HOURS) {
    $from   = time() - 86400; 
    $to     = time();
}
if ($quickdate==_LAST_7_DAYS) {
	$to     = mktime(23,59,59,date("m"),date("d"),date("Y"));  
    $from 	= mktime(0,0,0,date("m"),date("d") - 7,date("Y"));
	 
}
if ($quickdate==_LAST_14_DAYS) {
	$to     = mktime(23,59,59,date("m"),date("d"),date("Y"));
    $from 	= mktime(0,0,0,date("m"),date("d") - 14,date("Y"));
}
if ($quickdate==_LAST_30_DAYS) {
	$to     = mktime(23,59,59,date("m"),date("d"),date("Y"));
    $from 	= mktime(0,0,0,date("m"),date("d") - 30,date("Y"));
}
if ($quickdate==_THIS_MONTH) {
	$from   = mktime(0,0,0,date("m"),01,date("Y"));
	$to     = mktime(23,59,59,date("m"),date("d"),date("Y"));
}
if ($quickdate==_LAST_MONTH) {
	$from   = mktime(0,0,0,date("m")-1,01,date("Y"));
	$to     = mktime(23,59,59,date("m")-1,30,date("Y"));
}
if ($quickdate==_LAST_3_MONTHS) {
	$from   = mktime(0,0,0,date("m")-2,01,date("Y"));
	$to     = mktime(23,59,59,date("m"),date("d"),date("Y"));
}
if ($quickdate==_ALL_TIME) {
    $from = LogaholicFirstTimestamp();
    $date = GetMaxDateRange($profile);
	$to = $date["to"];
}
if (!$quickdate || $quickdate==_QUICKDATE) {
	if (isset($_REQUEST["fmonth"])) {
		$from   = mktime(0,0,0,$_REQUEST["fmonth"],$_REQUEST["fday"],$_REQUEST["fyear"]);
		$to     = mktime(23,59,59,$_REQUEST["tmonth"],$_REQUEST["tday"],$_REQUEST["tyear"]);
	} else if (isset($_REQUEST["minimumDate"])) {
		
		$r = DateToTimestamp($_REQUEST["minimumDate"], $_REQUEST["maximumDate"]);
		
		$from = $r['from'];
		$to = $r['to'];
		
        $tparts="";
		if(empty($reporting)) {
			if(!empty($from)) { $_SESSION["from"]=$from; }
			if(!empty($to)) { $_SESSION["to"]=$to; }
		}		
	} else {
		##
	}
}
if (empty($from) && empty($fmonth)) {
	# default values - 30 days
	$from   = @mktime(0,0,0,date("m"),date("d") - 30,date("Y"));
	$to     = @mktime(23,59,59,date("m"),date("d"),date("Y"));
}

if ($to < $from) {
    # haha, we can't do this, reset from to be the same day as to
    $from = mktime(0,0,0,date("m",$to),date("d",$to),date("Y",$to));
}