<?php

include_once("../connect.php");
include_once("../session.php");
//ini_set("display_errors", 1);
//error_reporting(E_ALL);


?>
<!DOCTYPE html>
 <html lang="en">
   <head>
     <meta charset="utf-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge">
	 <meta name="viewport" content="width=device-width, initial-scale=1">

     <title><?= $config['CompanyName'] ?></title>

     <!-- Bootstrap -->
     <link href="../css/bootstrap.min.css" rel="stylesheet">
     <link rel="stylesheet" href="../css/bootstrap-combobox.css" />

     <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
     <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
     <!--[if lt IE 9]>
       <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
       <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
       <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
           <!-- Include all compiled plugins (below), or include individual files as needed -->
           <script src="../js/bootstrap.min.js"></script>
       	 <script src="../js/bootstrap-combobox.js"></script>
         <script src="../js/functions.js"></script>
         <script src="../js/excellentexport.js"></script>
           <script type="text/javascript">
             $(document).ready(function(){
              // $('.combobox').combobox();

       //        $('.grpline').css("width", "100px");

             });
           </script>
     <![endif]-->
	<link rel="stylesheet" href="../css/styles.css"/>
	<style>
		.tooltip-inner {
			white-space:pre-wrap;
		}
		    @media print {
      a[href]:after {
        content: "" !important;
      }
    }
    tfoot {
      font-weight: bold;
    }
	</style>
</head>
<body>
  <?php
    include("navbar.php");
    //$customer = new Customer($_REQUEST['an']);
  ?>
   <!-- Stack the columns on mobile by making one full-width and the other half-width -->
	<div class="container hidden-print" style="height: 80px;"></div>
  <div class="container " style="margin-top: -90px;">
    <div class="page-header">
      <center>
			     <h2 class=""><?= $config['CompanyName'] ?></h2>
			     <h3 class="center">Report Viewer</h3>
           <?php
            $id = $_REQUEST['id'];
            $report = new Report($id);
           ?>
			     <h5><?= $report->ReportName ?></h5>
		  </center>
    </div>
		<div class="pull-right">

			<a class="btn btn-primary hidden-print" onclick="window.print();" href="#">Print</a>
			<a class="btn btn-success hidden-print" role="button" style="" href="#" download="<?= $report->ReportName ?><?=  " (" . date("m.d.Y") . ")" ?>.xls" href="#" onclick="return ExcellentExport.excel(this, 'report', '<?= $report->ReportName ?> <?= date("m-d-Y") ?>');" data-toggle="tooltip" data-placement="left" title="Does not work with Internet Explorer">Export To Excel</a>
		</div>
    <div class="hidden-print">

			<?php
        $filters = [];
        $query = "SELECT * FROM REPORT_DETAIL WHERE ReportID = {$report->ReportID} AND Filter = 1";
        $result = mysqli_query($con, $query);
        if(mysqli_num_rows($result)){
          ?>
          <form class="form-inline" action="mod.php">
            <input type="hidden" name="p" value="report">
            <input type="hidden" name="a" value="view">
            <input type="hidden" name="id" value="<?= $report->ReportID ?>">
          <?php
        }
        while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
          $filters[$row['ColumnName']] = $_REQUEST[$row['ColumnName']];
          ?>
          <label for="<?= $row['ColumnName'] ?>"><?= $row['ColumnName'] ?></label>
          <input style="width: 200px;" class="form-control" type="text" id="<?= $row['ColumnName'] ?>" value="<?= $_REQUEST[$row['ColumnName']] ?>" name="<?= $row['ColumnName'] ?>">
          <?php
        }
        if(mysqli_num_rows($result)){
          ?>
          <button class="btn btn-primary" type="submit">Filter</button>
          <?php
        }
      ?>
		</div>
	</div>
  <div class="container">
		<div class="col-md-12">
      <table class="table table-condensed" style="font-size: 12px;" id="report">
        <thead id="">
				      <tr>
                <?php
                  $totalizeColumns = array();
                  $moneyColumns = array();
                  $columnDetails = array();
                  $conRO = getNewConnection(true); //readonly
                  $reportQuery = $report->SQLQuery;
                  foreach ($filters as $key => $value) {
                    $reportQuery = str_ireplace("|$key|", $value, $reportQuery);
                  }
                  $result = mysqli_query($conRO, $reportQuery, MYSQLI_ASSOC);
                  $columns = mysqli_fetch_fields($result);
                  foreach ($columns as $key => $column) {
                    $query2 = "SELECT * FROM REPORT_DETAIL WHERE ReportID = {$report->ReportID} AND ColumnName LIKE '{$column->name}' ";
                    $con2 = getNewConnection(true);
                    $result2 = mysqli_query($con2, $query2);
                    if(mysqli_num_rows($result2)){
                      $columnDetails[$column->name] = mysqli_fetch_array($result2, MYSQLI_ASSOC);
                    }else{
                    }
                ?>
                <th class="<?= $columnDetails[$column->name]['Totalize']?"text-right":"" ?>"><?= $column->name ?>
                <?php
                  if($columnDetails[$column->name]['Comment']){
                    echo "<br><small>{$columnDetails[$column->name]['Comment']}</small>";
                  }
                ?></th>
                <?php
                  }
                ?>
              </tr>
			</thead>
		  <tbody id="reportTableBody">
		  <?php
        while($row = mysqli_fetch_array($result)){
      ?>
			   <tr class="">
         <?php
            foreach ($columns as $key => $column) {
              $rowValue = $row[$column->name];
         ?>
         <td class="<?= $columnDetails[$column->name]['Totalize']?"text-right":"" ?>">
         <?php
          // $query2 = "SELECT * FROM REPORT_DETAIL WHERE ReportID = {$report->ReportID} AND ColumnName LIKE '{$column->name}' ";
          // $con2 = getNewConnection(true);
          // $result2 = mysqli_query($con2, $query2);
          // if(mysqli_num_rows($result2)){
          //     $columnDetails = mysqli_fetch_array($result2, MYSQLI_ASSOC);
          // }else{
          //   $columnDetails = [];
          // }
          // if(isset($columnDetails['CustomFunction']) && $columnDetails['CustomFunction'] !== "" && !is_null($columnDetails['CustomFunction'])){
          //   $rowValue = ($columnDetails['CustomFunction']($rowValue));
          // }
          // if(isset($columnDetails['Totalize']) && $columnDetails['Totalize']){
          //   $totalizeColumns[$column->name] += $rowValue;
          // }
          // if(isset($columnDetails['IsMoney']) && $columnDetails['IsMoney']){
          //   $moneyColumns[$column->name] = true;
          //   echo moneyFormat($rowValue);
          // }else{
          //     echo $rowValue ;
          // }
          if(isset($columnDetails[$column->name]['CustomFunction']) && $columnDetails[$column->name]['CustomFunction'] !== "" && !is_null($columnDetails[$column->name]['CustomFunction'])){
            $rowValue = ($columnDetails[$column->name]['CustomFunction']($rowValue));
          }
          if(isset($columnDetails[$column->name]['Totalize']) && $columnDetails[$column->name]['Totalize']){
            $totalizeColumns[$column->name] += $rowValue;
          }
          if(isset($columnDetails[$column->name]['IsMoney']) && $columnDetails[$column->name]['IsMoney']){
            $moneyColumns[$column->name] = true;
          }
          if(isset($moneyColumns[$column->name]) && $moneyColumns[$column->name]){
            echo moneyFormat($rowValue);
          }else{
            echo $rowValue ;
          }

          ?></td>
        <?php
        }
       ?>
			</tr>
		<?php

		}
		 ?>
		   </tbody>
       <tfoot id="">
 				<tr>
           <?php
             $result = mysqli_query($con, $report->SQLQuery, MYSQLI_ASSOC);
             $columns = mysqli_fetch_fields($result);
             foreach ($columns as $key => $column) {
             ?>
             <td class="<?= $columnDetails[$column->name]['Totalize']?"text-right":"" ?>">
             <?php
              if(isset($totalizeColumns[$column->name])){
                if(isset($moneyColumns[$column->name])){
                    echo moneyFormat($totalizeColumns[$column->name]);
                }else{
                  echo ($totalizeColumns[$column->name]);
                }

              }

             ?></td>
             <?php
             }
            ?>


 				</tr>
 			</tfoot>
	   </table>

    <!--
	<input type="button" class="btn btn-primary" id="addNewInvoiceButton" value="Add New Invoice"/>
	-->

        </div>
    <hr />
 <script type="text/javascript">

    $(document).ready(function () {

    });

 </script>

   </body>
 </html>
