<?php session_start();
		if (isset($_SESSION['logged']) && $_SESSION['logged'] == 'yes') {
			include ('../scripts/classes.php'); if ($_SESSION['lang']=="EN"){include ('../lang/en.php');}elseif ($_SESSION['lang']=="GR"){include ('../lang/gr.php');}else {include ('../lang/en.php');}		
			include("../scripts/pchart/pChart/pData.class");
 			include("../scripts/pchart/pChart/pChart.class");	
			$mode=$lbl_business_analysis_area.": ".$lbl_sales;
			$page_title =$lbl_business_analytics; //Assign Page Title
			$array = getGlobalSettings(); foreach ($array as $settings){extract($settings);}
			$graph = "sales";//$_GET['graph'];
			$graph_mode = $_GET['graph_mode'];
			if ($_GET['splot']=='toggle') {if(isset($_SESSION['plot']) && $_SESSION['plot'] == $lbl_show_labels){$_SESSION['plot'] = $lbl_hide_labels;}else{$_SESSION['plot'] = $lbl_show_labels;}}
			$plot=$_SESSION['plot'];
			$current_month=date("m");
			if ($current_month==1){$month_desc=$lbl_january;}
			if ($current_month==2){$month_desc=$lbl_february;}
			if ($current_month==3){$month_desc=$lbl_march;}
			if ($current_month==4){$month_desc=$lbl_april;}
			if ($current_month==5){$month_desc=$lbl_may;}
			if ($current_month==6){$month_desc=$lbl_june;}
			if ($current_month==7){$month_desc=$lbl_july;}
			if ($current_month==8){$month_desc=$lbl_august;}
			if ($current_month==9){$month_desc=$lbl_september;}
			if ($current_month==10){$month_desc=$lbl_oktober;}
			if ($current_month==11){$month_desc=$lbl_november;}
			if ($current_month==12){$month_desc=$lbl_december;}
			$current_day=date("d");
			$previous_day=date("d")-1;
			$year = isset($_GET['selected_year']) ? $_GET['selected_year'] : @date("Y"); //
			$prev_year=$year-1;
            ##get reported branch
            $selected_branch = $_GET['selected_branch'];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?php echo $page_title ?></title>
<link rel="shortcut icon" href="../img/favicon.png" />
<link href="../cms1.css" rel="stylesheet" type="text/css" />
</head>
<body>
<script>top.document.title=self.document.title;</script>
		<div>
		<fieldset>
		<legend><?php echo $mode ?></legend>
                <div class="like-a-message">            
                <form name="frmBranch" action="reports_daily.php?splot=<?php echo $plot ?>" method="get">
                <span class="pad-left-right-10"><?php echo _BRANCH_SELECTION;  ?></span>
                <input type="hidden" name="graph_mode" value="<?php echo $graph_mode ?>" />
                 <select name="selected_branch" id="selected_branch" class="addform_drop_1">
    			<?php
    				$sql_d = "SELECT id AS branch_code, branch_name FROM cls_branches ORDER BY branch_name ASC";   
    				$result_d = mysqli_query($mysqli, $sql_d) or die("Query failed : " . mysqli_error($mysqli));
    				if (mysqli_num_rows($result_d) == 0){
    					echo $error002;
    					}else{	
                            echo "<option ".(($_GET['selected_branch'] == '') ? "selected" : "")." value=''>-- "._ALL_BRANCHES." --</option>";
    						while ($line_2 = mysqli_fetch_array($result_d, MYSQLI_ASSOC)) {
    							echo "<option ".(($_GET['selected_branch'] == $line_2['branch_code']) ? "selected" : "")." value='".$line_2['branch_code']."'>".$line_2['branch_name']."</option>";
    					}
    				}   			          
    			?>
    			</select>
                <input type="submit" name="btnSubmit" value="<?php echo $lbl_view; ?>" class="button"/>  
		      </form>
         </div>
		 <div style="width:99%; padding-bottom:10px;float:left">
		  <span style="padding-left:5px;"><font size="6"><?php echo (($selected_branch != '') ? $lbl_daily_sales.' ('.getBranchName($selected_branch).')' : $lbl_daily_sales) ?></font></span>
        </div>
		<?php
 $DataSales = new pData;
      	$Requete2 = "SELECT DAY(created_on) AS day, SUM(ROUND(amount,0)) AS total_day
					FROM cls_transactions
					WHERE year(created_on)='$year' AND MONTH(created_on)='$current_month' 
                    AND transaction_type<>'Εξαργύρωση'
                    AND ISNULL(is_reversed)
                    AND ISNULL(reversal)
                    ".(($selected_branch != "") ? " AND branch_id ='".$selected_branch."'" : "")."
                    GROUP BY day ORDER BY 1 ASC";		
                    		
    	$result2  = mysqli_query($mysqli, $Requete2)or die("Query failed : " . mysqli_error($mysqli));  
		$array_total=array();
		if (mysqli_num_rows($result2) == 0){
		$DataSales->AddPoint(0, "Serie1"); 
		$DataSales->AddPoint(1, "Serie2"); 
		$no_data=1;
		}else{
		while ($row = mysqli_fetch_array($result2)) 
     	{
		$total_day[]=$row["total_day"];
		$the_day=$row["day"];
		$array_days[] = $row["day"];
			$DataSales->AddPoint($row["total_day"], "Serie1"); 
			$DataSales->AddPoint($row["day"], "Serie2"); 
		}	 	
		}
		//$DataSales->AddAllSeries(); 
		$DataSales->AddSerie('Serie1');
		$DataSales->SetSerieName($lbl_sales." ".$month_desc,"Serie1");
		$DataSales->SetAbsciseLabelSerie("Serie2"); 
		$DataSales->SetYAxisName($lbl_turnover);  
		$DataSales->SetYAxisUnit($currency);     		
		// Initialise the graph
		$SalesGraph = new pChart(1000,245);
		$SalesGraph->setFontProperties("../scripts/pchart/Fonts/tahoma.ttf",8);
		$SalesGraph->setGraphArea(90,35,800,200); // $SalesGraph->setGraphArea(40,30,680,200);
		$SalesGraph->drawGraphArea(252,252,252,TRUE);
		$SalesGraph->drawFilledRoundedRectangle(0,0,850,240,5,242,242,230);  
		$SalesGraph->drawRoundedRectangle(0,5,850,225,5,242,242,230); 
		$SalesGraph->setColorPalette(0,178,45,110 ); //$SalesGraph->setColorPalette(1,63,223,63)
		//$SalesGraph->setColorPalette(1,63,223,63);// $SalesGraph->setColorPalette(1,155,181,189);
		// Draw the line graph
		//$SalesGraph->reportWarnings(); 
if ($graph_mode=='' || $graph_mode==filledlinegraph){	
		$SalesGraph->drawScale($DataSales->GetData(),$DataSales->GetDataDescription(),SCALE_NORMAL,150,150,150,TRUE,0,2);
		$SalesGraph->drawGrid(4,TRUE,230,230,230,70);
		$SalesGraph->drawPlotGraph($DataSales->GetData(),$DataSales->GetDataDescription(),3,2,244,249,251);
		$SalesGraph->drawFilledLineGraph($DataSales->GetData(),$DataSales->GetDataDescription(),50,TRUE); 
}
if ($graph_mode==linegraph){	
		$SalesGraph->drawScale($DataSales->GetData(),$DataSales->GetDataDescription(),SCALE_NORMAL,150,150,150,TRUE,0,2);
		$SalesGraph->drawGrid(4,TRUE,230,230,230,70);
		$SalesGraph->drawPlotGraph($DataSales->GetData(),$DataSales->GetDataDescription(),3,2,244,249,251);
		$SalesGraph->drawLineGraph($DataSales->GetData(),$DataSales->GetDataDescription());
}
if ($graph_mode==cubiccurve){	
		$SalesGraph->drawScale($DataSales->GetData(),$DataSales->GetDataDescription(),SCALE_NORMAL,150,150,150,TRUE,0,2);
		$SalesGraph->drawGrid(4,TRUE,230,230,230,70);
		$SalesGraph->drawCubicCurve($DataSales->GetData(),$DataSales->GetDataDescription());
}
if ($graph_mode==bargraph){	
		$SalesGraph->drawScale($DataSales->GetData(),$DataSales->GetDataDescription(),SCALE_NORMAL,150,150,150,TRUE,0,0,TRUE,1,FALSE);
		$SalesGraph->drawGrid(4,TRUE,230,230,230,70);
		$SalesGraph->drawBarGraph($DataSales->GetData(),$DataSales->GetDataDescription(),TRUE,50);	
}
if (!isset($_SESSION['plot']) || $plot== $lbl_show_labels and $no_data!=1){	
  while (list($key, $value) = each($array_days)) {
    $SalesGraph->setLabel($DataSales->GetData(),$DataSales->GetDataDescription(),"Serie1",$value, $total_day[$key], 254,254,177);	 
  }	
unset($value);
}
		// Finish the graph
		$SalesGraph->setFontProperties("../scripts/pchart/Fonts/tahoma.ttf",8);
		$SalesGraph->drawLegend(860,0,$DataSales->GetDataDescription(),242,242,230);
		$SalesGraph->setFontProperties("../scripts/pchart/Fonts/tahoma.ttf",10);
		$SalesGraph->drawTitle(60,22,$lbl_daily_sales_plural.(($selected_branch != '') ? " (".getBranchName($selected_branch).")" : "")." ".$month_desc." ".$year,50,50,50,800);		
		// Render the graph  
        (($selected_branch != "") ? $image_name = 'daily_sales.png' : $image_name = 'daily_sales'.$selected_branch.'.png');
		$SalesGraph->Render("graphs/".$image_name."");
flush();
?>
		
		<div style="width:99%; padding-left:5px; float:left; border-radius:3px;">
		<img src="graphs/<?php echo $image_name ?>" alt="<?php echo $lbl_daily_sales_plural?>" title="<?php echo $lbl_daily_sales_plural?>"/>
		</div>			
		<div style="float:left; padding-top:10px">
	<?php
	######################### cummulative days comparison
				$sql_cum_c = "SELECT SUM(amount) AS cum_totals FROM cls_transactions 
							WHERE transaction_type<>'Εξαργύρωση' 
							AND created_on
							BETWEEN CONCAT('$year','-','$current_month','-',$current_day,' ','00:00:00') 
							AND CONCAT('$year','-','$current_month','-','$current_day',' ','23:59:59')
                            AND ISNULL(is_reversed)
                            AND ISNULL(reversal)
                            ".(($selected_branch != "") ? " AND branch_id ='".$selected_branch."'" : "")."
                            ";
				$result_cum_c = mysqli_query($mysqli, $sql_cum_c) or die("Query failed : " . mysqli_error($mysqli));
				if (mysqli_num_rows($result_cum_c) == 0){echo $error001; 
				}else{$line = mysqli_fetch_array($result_cum_c, MYSQLI_ASSOC); $cum_c=$line['cum_totals'];} 
	################previous
				$sql_avg = "SELECT SUM(amount)/ COUNT(DISTINCT(DATE(created_on))) AS avg_totals FROM cls_transactions 
							WHERE transaction_type<>'Εξαργύρωση' 
							AND created_on
							BETWEEN CONCAT('$year','-','$current_month','-',01,' ','00:00:00') 
							AND CONCAT('$year','-','$current_month','-','$current_day',' ','00:00:00')
                            AND ISNULL(is_reversed)
                            AND ISNULL(reversal)
                            ".(($selected_branch != "") ? " AND branch_id ='".$selected_branch."'" : "")."
                            "; //until yesterday
				$result_avg = mysqli_query($mysqli, $sql_avg) or die("Query failed : " . mysqli_error($mysqli));
				if (mysqli_num_rows($result_avg) == 0){echo $error001;
				}else{$line = mysqli_fetch_array($result_avg, MYSQLI_ASSOC); $day_avg=$line['avg_totals'];} 
				//echo  $cum_p;
	###############################################	
	#calculate variation rate
	if ($day_avg>0){
		$variation=number_format(((($cum_c - $day_avg)/$day_avg)*100),0);
	}elseif ($day_avg<=0){
		$variation=0;
	}
	//echo $variation;
	###############################################
 ?>		
 		<div style="width:99%; padding-left:5px; margin-bottom:10px; float:left">
		&raquo; <?php echo $lbl_setup ?> 
		<a href="reports_daily.php?selected_year=<?php echo $year ?>&splot=toggle&graph_mode=<?php echo $graph_mode ?>&selected_branch=<?php echo $selected_branch ?>">
		<?php if ($plot==$lbl_hide_labels){echo $lbl_show_labels;}else{echo $lbl_hide_labels;}?></a><br />
		&raquo; <?php echo $lbl_view_options ?> 
		<a href="reports_daily.php?graph_mode=filledlinegraph&selected_year=<?php echo $year?>&selected_branch=<?php echo $selected_branch ?>"><?php echo $lbl_filled_line_graph?></a> |
		<a href="reports_daily.php?graph_mode=linegraph&selected_year=<?php echo $year ?>&selected_branch=<?php echo $selected_branch ?>"><?php echo $lbl_simple_line_graph ?></a> |
		<a href="reports_daily.php?graph_mode=cubiccurve&selected_year=<?php echo $year ?>&selected_branch=<?php echo $selected_branch ?>"><?php echo $lbl_cubic_curve_graph ?></a> | 
		<a href="reports_daily.php?graph_mode=bargraph&selected_year=<?php echo $year ?>&selected_branch=<?php echo $selected_branch ?>"><?php echo $lbl_bar_graph ?></a> <br />
		</div>
 		<div style="width:99%; padding-left:5px; float:left; border-radius:3px;">
		<div>
		<div style="float:left; background-color:#F2F2E6; padding:5px; padding-top:8px; border-radius:3px; margin-top:3px; height:53px; border:1px #CCCCCC solid; color:#666666; font-size:44px; margin-right:5px">
			<?php 
			echo $lbl_today.":<font color='green'> ".$currency."".number_format($cum_c,2,',','.')."</font>";
			?>
	  	</div>
		<div style="float:left; background-color:#F2F2E6; padding:5px; border-radius:3px; margin-top:3px; height:56px; border:1px #CCCCCC solid; color:#666666">
				<?php 
					if ($variation<0){
						echo "<img src='../img/down _arrow.gif' alt='' /><font size='8'>".$variation."%</font>";
					}elseif ($variation>0){
						echo "<img src='../img/up_arrow.gif' alt='' /><font size='8'>".$variation."%</font>";
					}elseif ($variation==0){
						echo "<font size='50'>".$variation."%</font>";
				}
				?>
		  </div>
			  <div style="float:left;background-color:#F2F2E6; padding:5px; width:250px; height:56px; font:tahoma; font-size:11px; border-radius:3px; margin-left:5px; margin-top:3px; border:1px #CCCCCC solid; margin-right:5px;color:#666666">
			<img src="../img/info.gif" /> <?php echo $lbl_variation_from_avg_day ?>
			</div>
		  </div>
		</div>
		
		<div style="width:850px; float:left; padding-left:5px;" align="left">
		<?php    

    ################################################################################
    ## +---------------------------------------------------------------------------+
    ## | 1. Creating & Calling:                                                    | 
    ## +---------------------------------------------------------------------------+
      define ("DATAGRID_DIR", "../datagrid/");                     /* Ex.: "datagrid/" */ 
      define ("PEAR_DIR", "../datagrid/pear/");                    /* Ex.: "datagrid/pear/" */
      require_once(DATAGRID_DIR.'datagrid.class.php');
      require_once(PEAR_DIR.'PEAR.php');
      require_once(PEAR_DIR.'DB.php');
      include_once('../datagrid/config.inc.php');
      ob_start();
      $db_conn = DB::factory('mysql');  /* don't forget to change on appropriate db type */
      $result_conn = $db_conn->connect(DB::parseDSN('mysql://'.$DB_USER.':'.$DB_PASS.'@'.$DB_HOST.'/'.$DB_NAME));
      if(DB::isError($result_conn)){ die($result_conn->getDebugInfo()); }  
	  
      if(DB::isError($result_conn)){ die($result_conn->getDebugInfo()); }  
    ################################################################################   
      $sql = "SELECT DATE_FORMAT(created_on,'%d/%m/%Y') AS created_on_2, SUM(amount) AS total_day
					FROM cls_transactions
					WHERE YEAR(created_on)='$year' AND MONTH(created_on)='$current_month' AND transaction_type<>'Εξαργύρωση'
					GROUP BY created_on_2";         
	        
    ##  *** set needed options and create a new class instance 
      $debug_mode = false;        /* display SQL statements while processing */    
      $messaging = true;          /* display system messages on a screen */ 
      $unique_prefix = "opd_";    /* prevent overlays - must be started with a letter */
      $dgrid = new DataGrid($debug_mode, $messaging, $unique_prefix, DATAGRID_DIR);
      $dgrid->SetCssClass("default");
      $dgrid->DisplayLoadingImage("true");
      $dgrid->AllowPaging(false, "", "");
    ##  *** set data source with needed options
      $default_order_field = "created_on";
      $default_order_type = "DESC";
      $dgrid->DataSource($db_conn, $sql, $default_order_field, $default_order_type);
    ##  *** "byFieldValue"=>"fieldName" - make the field to be a link to edit mode page
     $modes = array(
     );
     $dgrid->SetModes($modes);
    ##  *** set DataGrid caption
     //$dg_caption = $lbl_new_customers_for_the_year." ".$year;
    // $dgrid->SetCaption($dg_caption);
     $dgrid->AllowPrinting(true);
     $dgrid->AllowSorting(false);
     $dgrid->AllowHighlighting(true);
	//webnail language handling
	if ($_SESSION['lang']=="EN"){$dg_language = "en";}elseif ($_SESSION['lang']=="GR"){$dg_language = "gk";}else{$dg_language = "en";}
	$dgrid->SetInterfaceLang($dg_language);
	$paging_option = false;
    $dropdown_paging = false;
    $dgrid->AllowPaging($paging_option, $rows_numeration, $numeration_sign, $dropdown_paging);
    ##  *** set paging settings
    $bottom_paging = array("results"=>true, "results_align"=>"left", "pages"=>true, "pages_align"=>"center", "page_size"=>true, "page_size_align"=>"right");
    $top_paging = array("results"=>true, "results_align"=>"left", "pages"=>true, "pages_align"=>"center", "page_size"=>true, "page_size_align"=>"right");
    $pages_array = array("5"=>"5", "10"=>"10", "50"=>"50");
    $default_page_size = 31;
    $paging_arrows = array("first"=>"|&lt;&lt;", "previous"=>"&lt;&lt;", "next"=>"&gt;&gt;", "last"=>"&gt;&gt;|");
    $dgrid->SetPagingSettings($bottom_paging, $top_paging, $pages_array, $default_page_size, $paging_arrows);
		 ## +---------------------------------------------------------------------------+
	## | 3. Printing & Exporting Settings:                                         | 
	## +---------------------------------------------------------------------------+
	##  *** set printing option: true(default) or false 
	  $printing_option = true;
	  $dgrid->AllowPrinting($printing_option);
	  $exporting_option = true;
		$exporting_directory = "../exports/";               
		$export_all = true;
		$dgrid->AllowExporting($exporting_option, $exporting_directory, $export_all);
		$exporting_types = array("excel"=>"true", "pdf"=>"false", "xml"=>"false");
		$dgrid->AllowExportingTypes($exporting_types);
		
    ## +---------------------------------------------------------------------------+
    ## | 6. View Mode Settings:                                                    | 
    ## +---------------------------------------------------------------------------+
    ##  *** set view mode table properties
     $vm_table_properties = array("width"=>"850px");
     $dgrid->SetViewModeTableProperties($vm_table_properties);  
     $vm_colimns = array(  
	    "created_on_2"  =>array("header"=>$lbl_date, "type"=>"label", "header_align"=>"center", "align"=>"center", "tooltip"=>"true", "width"=>"200px", "summarize"=>"false",),	
        "total_day"  =>array("header"=>$lbl_grid_amount, "type"=>"label", "header_align"=>"center","tooltip"=>"true", "summarize"=>"true")			
     );
     $dgrid->SetColumnsInViewMode($vm_colimns);
	 $dgrid->SetSummarizeNumberFormat("2", ",", ".");
	 $dgrid->DisplayLoadingImage();
    
    ## +---------------------------------------------------------------------------+
    ## | 8. Bind the DataGrid:                                                     | 
    ## +---------------------------------------------------------------------------+
    ##  *** bind the DataGrid and draw it on the screen
      $dgrid->Bind();        
      //ob_end_flush();
    ##
    ################################################################################   
	?>
		</div>
	</div>	
	</fieldset>
</body>
</html>
<?php
} else {
    header('Location: login.php');
}
?>

