<?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']];
          if($row["FilterType"] == "selectMonth"){
          ?>
          <label for="<?= $row['ColumnName'] ?>"><?= $row['ColumnName'] ?></label>
          <select style="width: 200px;" class="form-control" id="<?= $row['ColumnName'] ?>" value="<?= $_REQUEST[$row['ColumnName']] ?>" name="<?= $row['ColumnName'] ?>">
            <option <?= $_REQUEST[$row['ColumnName']]=="%"?"selected":"" ?> value="%">All</option>
            <option <?= $_REQUEST[$row['ColumnName']]=="1"?"selected":"" ?> value="1">1 - January</option>
            <option <?= $_REQUEST[$row['ColumnName']]=="2"?"selected":"" ?> value="2">2 - February</option>
            <option <?= $_REQUEST[$row['ColumnName']]=="3"?"selected":"" ?> value="3">3 - March</option>
            <option <?= $_REQUEST[$row['ColumnName']]=="4"?"selected":"" ?> value="4">4 - April</option>
            <option <?= $_REQUEST[$row['ColumnName']]=="5"?"selected":"" ?> value="5">5 - May</option>
            <option <?= $_REQUEST[$row['ColumnName']]=="6"?"selected":"" ?> value="6">6 - June</option>
            <option <?= $_REQUEST[$row['ColumnName']]=="7"?"selected":"" ?> value="7">7 - July</option>
            <option <?= $_REQUEST[$row['ColumnName']]=="8"?"selected":"" ?> value="8">8 - August</option>
            <option <?= $_REQUEST[$row['ColumnName']]=="9"?"selected":"" ?> value="9">9 - September</option>
            <option <?= $_REQUEST[$row['ColumnName']]=="10"?"selected":"" ?> value="10">10 - October</option>
            <option <?= $_REQUEST[$row['ColumnName']]=="11"?"selected":"" ?> value="11">11 - November</option>
            <option <?= $_REQUEST[$row['ColumnName']]=="12"?"selected":"" ?> value="12">12 - December</option>
          </select>
          <?php

          }elseif($row["FilterType"] == "selectVendor"){
            $vendorsQuery = "SELECT * FROM VENDOR ORDER BY VendorID";
            $vendorsResult = mysqli_query($con, $vendorsQuery);
            
          
            
            ?>
          <label for="<?= $row['ColumnName'] ?>"><?= $row['ColumnName'] ?></label>
          
          <select style="width: 200px;" class="form-control" id="<?= $row['ColumnName'] ?>" value="<?= $_REQUEST[$row['ColumnName']] ?>" name="<?= $row['ColumnName'] ?>">
            <option <?= $_REQUEST[$row['ColumnName']]=="%"?"selected":"" ?> value="%">All</option>
          <?php
          while($vendorRow = mysqli_fetch_array($vendorsResult)){
          ?>
            <option <?= $_REQUEST[$row['ColumnName']]==$vendorRow['VendorID']?"selected":"" ?> value="<?= $vendorRow['VendorID'] ?>"><?= $vendorRow['Name'] ?></option>
          <?php
          }
          ?>
          </select>
          <?php
            
          }else{
          ?>
          <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>
