<?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/excellentexport.js"></script>
         <script src="../js/functions.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;
      }
    }
	</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">Accounts Receivable Report</h3>
      <?php
        $query = "SELECT create_time FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = '$db' AND table_name = 'ACCOUNTS_RECEIVABLE_AGING_DELIVERY_CACHE'";
        $result = mysqli_query($con, $query);
        $row = mysqli_fetch_array($result);
      ?>
			<h5>As of <?= date("m/d/Y h:i a", strtotime($row['create_time'])-(4*60*60)) ?></h5>
		</center>
		<div class="pull-right">
      <a class="btn btn-primary hidden-print" onclick="$.get('mod.php?p=payment&a=functions&f=refreshAging', function(data){ if(data == 'true'){ location.reload() }})" href="#">Refresh Data</a>
			<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="AccountsReceivableReport<?= $title . "(" . date("m.d.Y") . ")" ?>.xls" href="#" onclick="return ExcellentExport.excel(this, 'arreport', 'Aging <?= date("m-d-Y") ?>');" data-toggle="tooltip" data-placement="left" title="Does not work with Internet Explorer">Export To Excel</a>
		</div>

		</div>
	</div>


    <div class="container" style="width: 95%;">
		<div class="col-md-12">


		<table class="table table-condensed table-hover" style="font-size: 12px;" id="arreport">

			<thead id="">
				<tr>
				  <th style="width: 10%">Account Number</th>
				  <th style="width: 20%">Name</th>
					<th style="width: 15%">Salesperson</th>
          <th style="width: 15%">City</th>
				  <th style="width: 5%;">Days</th>
				  <th style="width: 10%; text-align: right;">0 to 30 Days</th>
				  <th style="width: 10%; text-align: right;">31 to 60 Days</th>
				  <th style="width: 10%; text-align: right;">61 to 90 Days</th>
				  <th style="width: 10%; text-align: right;">Over 90 Days</th>
				  <th style="width: 10%; text-align: right;">Balance</th>
          <th style="width: 10%; text-align: center;"></th>
				</tr>
			</thead>

		<tbody id="paymentTableBody">
		<?php

		$query = "SELECT AccountNumber, SUM(0To30) 0To30, SUM(31To60) 31To60,SUM(61To90) 61To90,SUM(Over90) Over90, SUM(Balance) Balance, MAX(ElapsedDays)+1 DueDays, MAX(DATEDIFF(NOW(), DueDate)-1) OverdueDays  FROM `ACCOUNTS_RECEIVABLE_AGING_DELIVERY_CACHE` JOIN INVOICE_HEAD USING(InvoiceID, AccountNumber) WHERE Balance != 0 GROUP BY AccountNumber ORDER BY AccountNumber";
		$result = mysqli_query($con, $query);
    //var_dump(mysqli_error($con));
		$totalDue = 0;
		$total30 = 0;
		$total60 = 0;
		$total90 = 0;
		$totalOverdue = 0;
		while($row = mysqli_fetch_array($result)){
			$totalDue += $row['Balance'];
			$total30 += $row['0To30'];
			$total60 += $row['31To60'];
			$total90 += $row['61To90'];
			$totalOverdue += $row['Over90'];
		$customer = new Customer($row['AccountNumber']);
		$rowClass = "";
		if($row['61To90'] > 0){
			$rowClass = "warning";
		}
		if($row['Over90'] > 0){
			$rowClass = "danger";
		}

		?>
			<tr class="<?= $rowClass ?>">
				<td><a target="_blank" href="mod.php?p=payment&a=admin.aging&an=<?= $customer->AccountNumber ?>"><?= $customer->AccountNumber ?></a></td>
				<td style=""><?= $customer->Name ?></td>
				<td style=""><?= $customer->Salesman->Name ?></td>
        <td style=""><?= $customer->ShipToCity ?></td>
				<td><?= $row['DueDays']<0?"0":$row['DueDays'] ?></td>

				<td style="text-align: right;"><?= moneyFormat($row['0To30']) ?></td>
				<td style="text-align: right;"><?= moneyFormat($row['31To60']) ?></td>
				<td style="text-align: right;"><?= moneyFormat($row['61To90']) ?></td>
				<td style="text-align: right;"><?= moneyFormat($row['Over90']) ?></td>
				<td style="text-align: right;"><?= moneyFormat($row['Balance']) ?></td>
        <td style="text-align: center;">
        <?php
        if($row["OverdueDays"] > 1 && $row['Balance'] > 0 && substr($row['AccountNumber'], 0, 5) != "00000"){
            if((date("Y-m-d", strtotime($customer->OverdueReminderSentDate)) < date("Y-m-d", time()) || is_null($customer->OverdueReminderSentDate))){
        ?>
          <button onclick="sendCollectionsEmail('<?= $customer->AccountNumber ?>', '<?= addslashes($customer->Name) ?>', this);" class="btn btn-danger btn-xs">Send Collections Email</button></td>
        <?php
      }else{
        //var_dump(date("Y-m-d", strtotime($customer->OverdueReminderSentDate)) < date("Y-m-d", time()));
        ?>

        Already Sent Today
        <?php
      }
        ?>



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

		}
		 ?>
			<tr>
			   <td></td>
			   <td></td>
			   <td></td>
				 <td></td>
			   <td style="text-align: right;"><b><?= moneyFormat($total30) ?></b></td>
			   <td style="text-align: right;"><b><?= moneyFormat($total60) ?></b></td>
			   <td style="text-align: right;"><b><?= moneyFormat($total90) ?></b></td>
			   <td style="text-align: right;"><b><?= moneyFormat($totalOverdue) ?></b></td>
			   <td style="text-align: right;"><b><?= moneyFormat($totalDue) ?></b></td>

			</tr>
		   </tbody>
	   </table>

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

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

    $(document).ready(function () {

    });
    function sendCollectionsEmail(AccountNumber, CustomerName, element){
      if(confirm("Are you sure you want to send a Collections Email to " + CustomerName)){
        $.post("mod.php?p=payment&a=functions&f=sendCollectionsEmail", {
          "an" : AccountNumber
        } , function(data){
          if(data == "true"){

            $(element).parent().text('Already Sent Today');
            alert("Success!");
          }else{
            alert(data);
          }
        });
      }
    }
 </script>

   </body>
 </html>
