<!DOCTYPE>
<?php

session_start();
if($_SESSION['dbName']==""){
header("location:../index.php");
}



print <<< HERE
<HTML>
<HEAD>
<TITLE> List of Items/Branches </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
<style type="text/css" >
table.params td { font-size: 12px; 
                  font-family:Times-New-Roman;
                 }

table.master th { font-size: 14px; 
                  font-weight: bold;
                  font-family:Times-New-Roman;
                      }				 
table.master td { font-size: 12px; 
                  font-family:Times-New-Roman;
                 }
table.group td { font-size: 12px; 
                 font-weight: bold;
                 font-family:Times-New-Roman;
               }				 
				 
table.detail td { font-size: 10px; 
                  font-family:Times-New-Roman;
                 }				 
table.headerdetail td { font-size: 10px; 
                        font-weight: bold;
                        font-family:Times-New-Roman;
                      }				 
table.totals td { font-size: 12px; 
                  font-weight: bold;
                  font-family:Times-New-Roman;
                 }					  

.header1 {
	font-size: 26px;
	font-weight: bold;
}
.header2 {
	font-size: 20px;
	font-weight: bold;
}
.header3 {
	font-size: 13px;
	font-weight: bold;
}	

.detail1 {
	font-size: 12px;
	font-weight: bold;
}

</style>
</HEAD>

HERE;



include("config.inc.php");
include 'function.inc.php';

set_time_limit(0);

$connection = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass']) or die("Could not connect to DB");
mysql_select_db($_SESSION['dbName'],$connection) or die("Could not find DB");

$querylog="SELECT print as printaccess from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' 	and Upper(Login_Schema) = Upper('".$_SESSION['dbName']."')	";
$resultlog=mysql_query($querylog,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
	extract($rows);
}


if ($printaccess==0 or $printaccess=='')
echo'<BODY oncontextmenu="return false;">';
else
echo'<BODY>';


$querysetup="select grid_color1,grid_color2, DecimalBase, DecimalBase1, DecimalBase2, report_color1, report_color2, base1, base2, Company_Name As CompanyName from setup";
$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultsetup)){
  extract($rows);
}


$PProjectCode 	= $_GET['PProjectCode'];
$fromdate 		= $_GET['fromdate'];
$todate			= $_GET['todate'];
$tvType			= $_GET['tvType'];
$tsSupTeamId 	= $_GET['tsSupTeamId'];
$tvClosed		= $_GET['tvClosed'];

$now=current_server_time($connection);
$dt=split(" ",$now[0]);
$printdate=split("-",$dt[0]);

$title = 'List of Items/Branches';

echo "<table border='0' width='100%' cellpadding='0' cellspacing='0'>
	<col width='85%'><col width='15%'>";
echo "<tr height='30px'><td ><span class='header2'>$CompanyName</span></td><td><span class='header3'>Print Date: $printdate[2]-$printdate[1]-$printdate[0]<br>Print Time: $dt[1]</span></td></tr>";
echo "<tr height='30px'><td colspan='2'></td></tr>";
echo "<tr height='30px'><td colspan='2' align='center'><span class='header1'>$title</span></td></tr>";
echo "<tr height='30px'><td colspan='2'> </td></tr>";
echo "</table>";	
  


 $wdt = "1180px";




$tmpProject = '*#' ;

 $querysearch = "select projetItems_id, project_items.item_code as item_code, item_Description, projetItems_qty, project_items.project_code as project_code, project_name
				from project_items
				inner join items on items.item_code = project_items.item_code
				inner join project on project.project_code = project_items.project_code
				where ifnull(projetItems_qty,0) > 0 
				order by project_items.project_code, project_items.item_code "; 
$result = mysql_query($querysearch, $connection);

$ct = 0;

while($rows = mysql_fetch_array($result)){
	extract($rows);
	
	if (!($ct%2))
			$bgcolor = "bgcolor='#ABD4F1'";
		else 
			$bgcolor = "bgcolor='#EFF1F3'";
	
	if ($tmpProject != $project_code){
		if ($ct != 0) echo "</table>";
		if ($ct == 0) $projArr =  "'".$project_code."'";
		else $projArr .=  ",'".$project_code."'";
		echo "<table cellspacing='4' cellpadding='0' border='0' id='$project_code'>";

		echo "<col width=150><col width=150><col width=150>
			  <col width=150><col width=100><col width=90>
			  <col width=90><col width=180><col width=200><col width=120>";

			
		 echo"<tr height='25px'>
				 <td align='left' data-style='Date'><span class='header3'>Item Code</td>
				 <td align='left' ><span class='header3'>Description</td>
				 <td align='left' ><span class='header3'>Quantity</td>
		 </tr>"; 
		
	}
	echo"<tr $bgcolor>
			<td align='left'><span class='detail1'>$item_code</span></td>
			<td align='left'><span class='detail1'>$item_Description</span></td>	
			<td align='left'><span class='detail1'>$projetItems_qty</span></td>	
		</tr>";
	$tmpProject = $project_code;
	$ct++;
}
 
echo "</table>";
echo $projArr;

echo "<button name='btn' onclick=\"tablesToExcel([$projArr], [$projArr], 'ItemsPerBranch.xls', 'Excel')\">Export to Excel</button>";


function current_server_time($connection){

  $string="Select date_format(NOW(),'%Y-%m-%d %h:%i %p') ";
  $result=mysql_query($string,$connection) or die(mysql_error());
  $now=mysql_fetch_row($result);

  return $now;
}
?>



<script>

var tablesToExcel = (function() {
    var uri = 'data:application/vnd.ms-excel;base64,'
    , tmplWorkbookXML = '<?xml version="1.0"?><?mso-application progid="Excel.Sheet"?><Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">'
      + '<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"><Author>Axel Richter</Author><Created>{created}</Created></DocumentProperties>'
      + '<Styles>'
      + '<Style ss:ID="Currency"><NumberFormat ss:Format="Currency"></NumberFormat></Style>'
      + '<Style ss:ID="Date"><NumberFormat ss:Format="Medium Date"></NumberFormat></Style>'
      + '</Styles>' 
      + '{worksheets}</Workbook>'
    , tmplWorksheetXML = '<Worksheet ss:Name="{nameWS}"><Table>{rows}</Table></Worksheet>'
    , tmplCellXML = '<Cell{attributeStyleID}{attributeFormula}><Data ss:Type="{nameType}">{data}</Data></Cell>'
    , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
    , format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
    return function(tables, wsnames, wbname, appname) {
      var ctx = "";
      var workbookXML = "";
      var worksheetsXML = "";
      var rowsXML = "";

      for (var i = 0; i < tables.length; i++) {
        if (!tables[i].nodeType) tables[i] = document.getElementById(tables[i]);
        for (var j = 0; j < tables[i].rows.length; j++) {
          rowsXML += '<Row>'
          for (var k = 0; k < tables[i].rows[j].cells.length; k++) {
            var dataType = tables[i].rows[j].cells[k].getAttribute("data-type");
            var dataStyle = tables[i].rows[j].cells[k].getAttribute("data-style"); 
            var dataValue = tables[i].rows[j].cells[k].getAttribute("data-value");
            dataValue = (dataValue)?dataValue:tables[i].rows[j].cells[k].innerHTML;
            var dataFormula = tables[i].rows[j].cells[k].getAttribute("data-formula");
            dataFormula = (dataFormula)?dataFormula:(appname=='Calc' && dataType=='DateTime')?dataValue:null;
            ctx = {  attributeStyleID: (dataStyle=='Currency' || dataStyle=='Date')?' ss:StyleID="'+dataStyle+'"':''
                   , nameType: (dataType=='Number' || dataType=='DateTime' || dataType=='Boolean' || dataType=='Error')?dataType:'String'
                   , data: (dataFormula)?'':dataValue
                   , attributeFormula: (dataFormula)?' ss:Formula="'+dataFormula+'"':''
                  };
            rowsXML += format(tmplCellXML, ctx);
          }
          rowsXML += '</Row>'
        }
        ctx = {rows: rowsXML, nameWS: wsnames[i] || 'Sheet' + i};
        worksheetsXML += format(tmplWorksheetXML, ctx);
        rowsXML = "";
      }

      ctx = {created: (new Date()).getTime(), worksheets: worksheetsXML};
      workbookXML = format(tmplWorkbookXML, ctx);

console.log(workbookXML);

      var link = document.createElement("A");
      link.href = uri + base64(workbookXML);
      link.download = wbname || 'Workbook.xls';
      link.target = '_blank';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
	  window.close();
    }
	
  })();


</script>


</BODY>
</HTML>

