<?php
ob_start();
//error_reporting(E_ALL & ~E_NOTICE);
$PageSecurity=0;

include('includes/session.inc');
$Title=_('ERP Home');
include('includes/newheader.php');
include('includes/SQL_CommonFunctions.inc');
?>

		
  					
	<script src="angular/angular.min.js"></script>  
        
 
     
     
		

   
  
 									
									<?php
//this is where you paste. Below paste it:


echo '<link href="' . $RootPath . '/css/evergreen2'.'/default.css" rel="stylesheet" type="text/css" media="screen"/>';


//echo '<p class="page_title_text"><img src="'.$RootPath.'/css/'.$Theme.'/images/maintenance.png"> </p>';
      
	echo '<div class="col-sm-12">';
		//echo '<div class="aflpanel" style="margin-bottom:10px">';
		
   $ViewTopic = 'ARReports';
$BookMark = 'CustomerStatements';



			$sqlbalances="SELECT account_number, debtorno, balance, current,1month,2month,3month_plus
					FROM debtoraccount where debtorno = 940";
		$resultfromdebtoraccount =DB_query($sqlbalances);



echo '<div class="table-responsive"><table id="projectreport" class="table">';
	echo '<thead> <tr class="info">
			
			<th>' . _('Account Number') . '</th>
			
			<th>' . _('Balance') . '</th>
			<th>' . _('Current') . '</th>
			<th>' . _('Due Now/30 Days') . '</th>
			<th>' . _('30 Days Over') . '</th>
			<th>' . _('60 Days Over') . '</th>
			
			
	
			</thead></tr>';


while ($myrowfromdebtoraccount = DB_fetch_array($resultfromdebtoraccount)){
				
					$balance = $myrowfromdebtoraccount['balance'];
			
			$current = $myrowfromdebtoraccount['current'];
			$onemonth = $myrowfromdebtoraccount['1month'];
			$twomonth = $myrowfromdebtoraccount['2month'];
			$threemonthplus = $myrowfromdebtoraccount['3month'];
				
			$accountnumber = 	$myrowfromdebtoraccount['account_number'];
	     $debtorno = 	$myrowfromdebtoraccount['debtorno'];

/*Figure out who all the customers in this range are */
	$ErrMsg= _('There was a problem retrieving the customer information for the statements from the database');
	$sql = "SELECT debtorsmaster.debtorno,
				debtorsmaster.name,
				debtorsmaster.address1,
				debtorsmaster.address2,
				debtorsmaster.address3,
				debtorsmaster.address4,
				debtorsmaster.address5,
				debtorsmaster.address6,
				debtorsmaster.lastpaid,
				debtorsmaster.lastpaiddate,
				currencies.currency,
				currencies.decimalplaces AS currdecimalplaces,
				paymentterms.terms
			FROM debtorsmaster INNER JOIN currencies
				ON debtorsmaster.currcode=currencies.currabrev
			INNER JOIN paymentterms
				ON debtorsmaster.paymentterms=paymentterms.termsindicator
			WHERE debtorsmaster.debtorno ='" . $debtorno."'
		
			";
	$StatementResults=DB_query($sql, $ErrMsg);


	$StmtHeader=DB_fetch_array($StatementResults); /*loop through all the customers returned */

	/*now get all the outstanding transaction ie Settled=0 */
		
		$sql = "SELECT systypes.typename,
					debtortrans.transno,
					debtortrans.trandate,
					debtortrans.ovamount+debtortrans.ovdiscount+debtortrans.ovfreight+debtortrans.ovgst as total,
					debtortrans.alloc,
					debtortrans.ptax,
						debtortrans.retention,
					debtortrans.account_number,
					debtortrans.department,
					debtortrans.ovamount+debtortrans.ovdiscount+debtortrans.ovfreight+debtortrans.ovgst-debtortrans.alloc-debtortrans.ptax-debtortrans.retention as ostdg
				FROM debtortrans INNER JOIN systypes
					ON debtortrans.type=systypes.typeid
				WHERE debtortrans.debtorno='" . $debtorno . "'
				AND debtortrans.account_number='" . $accountnumber . "'
				AND debtortrans.settled=0
				AND debtortrans.cancelled=0
				
				";


		$OstdgTrans=DB_query($sql, $ErrMsg);

	   	$NumberOfRecordsReturned = DB_num_rows($OstdgTrans);

/*now get all the settled transactions which were allocated this month */



		/* Then there's a statement to print. So print out the statement header from the company record */

			/*Now figure out the aged analysis for the customer under review */
			
			
				
				

			$SQL = "SELECT debtorsmaster.debtorno,
				debtorsmaster.name,
				debtorsmaster.lastpaid,
				debtorsmaster.lastpaiddate,
				debtortrans.account_number,
				
				paymentterms.terms,
			
				SUM(
					debtortrans.ovamount + debtortrans.ovgst + debtortrans.ovfreight + debtortrans.ovdiscount - debtortrans.alloc - debtortrans.ptax - debtortrans.retention
				) AS balance,
				SUM(debtortrans.ptax) AS ptaxbalance,
						SUM(debtortrans.retention) AS retentionbalance,
				SUM(
					CASE WHEN (paymentterms.daysbeforedue > 0)
					THEN
						CASE WHEN (TO_DAYS(Now()) - TO_DAYS(debtortrans.trandate)) >= paymentterms.daysbeforedue
						THEN debtortrans.ovamount + debtortrans.ovgst + debtortrans.ovfreight + debtortrans.ovdiscount - debtortrans.alloc - debtortrans.ptax - debtortrans.retention
						ELSE 0 END
					ELSE
						CASE WHEN TO_DAYS(Now()) - TO_DAYS(DATE_ADD(DATE_ADD(debtortrans.trandate, " . INTERVAL('1', 'MONTH') . "), " . INTERVAL('(paymentterms.dayinfollowingmonth - DAYOFMONTH(debtortrans.trandate))', 'DAY') .")) >= 0
						THEN debtortrans.ovamount + debtortrans.ovgst + debtortrans.ovfreight + debtortrans.ovdiscount - debtortrans.alloc - debtortrans.ptax - debtortrans.retention ELSE 0 END
					END
				) AS due,
				SUM(
					CASE WHEN (paymentterms.daysbeforedue > 0)
					THEN
						CASE WHEN (TO_DAYS(Now()) - TO_DAYS(debtortrans.trandate)) > paymentterms.daysbeforedue AND TO_DAYS(Now()) - TO_DAYS(debtortrans.trandate) >= (paymentterms.daysbeforedue + " . $_SESSION['PastDueDays1'] . ")
						THEN debtortrans.ovamount + debtortrans.ovgst + debtortrans.ovfreight + debtortrans.ovdiscount - debtortrans.alloc - debtortrans.ptax - debtortrans.retention ELSE 0 END
					ELSE
						CASE WHEN TO_DAYS(Now()) - TO_DAYS(DATE_ADD(DATE_ADD(debtortrans.trandate, " . INTERVAL('1', 'MONTH') . "), " . INTERVAL ('(paymentterms.dayinfollowingmonth - DAYOFMONTH(debtortrans.trandate))', 'DAY') . ")) >= " . $_SESSION['PastDueDays1'] . "
						THEN debtortrans.ovamount + debtortrans.ovgst + debtortrans.ovfreight + debtortrans.ovdiscount - debtortrans.alloc - debtortrans.ptax - debtortrans.retention
						ELSE 0 END
					END
				) AS overdue1,
				SUM(
					CASE WHEN (paymentterms.daysbeforedue > 0)
					THEN
						CASE WHEN (TO_DAYS(Now()) - TO_DAYS(debtortrans.trandate)) > paymentterms.daysbeforedue AND TO_DAYS(Now()) - TO_DAYS(debtortrans.trandate) >= (paymentterms.daysbeforedue + " . $_SESSION['PastDueDays2'] . ")
						THEN debtortrans.ovamount + debtortrans.ovgst + debtortrans.ovfreight + debtortrans.ovdiscount - debtortrans.alloc - debtortrans.ptax - debtortrans.retention ELSE 0 END
					ELSE
						CASE WHEN TO_DAYS(Now()) - TO_DAYS(DATE_ADD(DATE_ADD(debtortrans.trandate, " . INTERVAL ('1', 'MONTH') . "), " . INTERVAL('(paymentterms.dayinfollowingmonth - DAYOFMONTH(debtortrans.trandate))', 'DAY') . ")) >= " . $_SESSION['PastDueDays2'] . "
						THEN debtortrans.ovamount + debtortrans.ovgst + debtortrans.ovfreight + debtortrans.ovdiscount - debtortrans.alloc - debtortrans.ptax - debtortrans.retention
						ELSE 0 END
					END
				) AS overdue2
				FROM debtorsmaster,
					paymentterms,
					
					debtortrans
				WHERE debtorsmaster.paymentterms = paymentterms.termsindicator
				
				AND debtortrans.account_number = '" . $accountnumber."'
					
					AND debtorsmaster.debtorno = debtortrans.debtorno
					AND debtortrans.settled=0	
				AND debtortrans.cancelled = '0'
				AND debtortrans.trandate > '2019-12-31 00:00:00'
				GROUP BY debtorsmaster.debtorno,
					debtorsmaster.name,
					debtortrans.account_number,
					paymentterms.terms,
					paymentterms.daysbeforedue,
					paymentterms.dayinfollowingmonth
					 
				HAVING
					ROUND(ABS(SUM(debtortrans.ovamount + debtortrans.ovgst + debtortrans.ovfreight + debtortrans.ovdiscount - debtortrans.alloc - debtortrans.ptax - debtortrans.retention ))) > 0";

		
			
	$ErrMsg = _('This customer could not be added because');
			$result4 = DB_query($SQL,$ErrMsg);
	
				
				
			
		$AgedAnalysis = DB_fetch_array($result4);
			
			
			
			$CurrDecimalPlaces = $AgedAnalysis['decimalplaces'];
				$DisplayDue = locale_number_format($AgedAnalysis['due']-$AgedAnalysis['overdue1'],$CurrDecimalPlaces);
		$DisplayCurrent = locale_number_format($AgedAnalysis['balance']-$AgedAnalysis['due'],$CurrDecimalPlaces);
		$DisplayBalance = locale_number_format(($AgedAnalysis['balance']),$CurrDecimalPlaces);
		$DisplayOverdue1 = locale_number_format($AgedAnalysis['overdue1']-$AgedAnalysis['overdue2'],$CurrDecimalPlaces);
		$DisplayOverdue2 = locale_number_format($AgedAnalysis['overdue2'],$CurrDecimalPlaces);
		$Lastpaid = locale_number_format($AgedAnalysis['lastpaid'],$CurrDecimalPlaces);
		$Lastpaiddate =  $AgedAnalysis['lastpaiddate'];                  
		
		
		$TotBal = $AgedAnalysis['balance'];
		$TotDue = ($AgedAnalysis['due']-$AgedAnalysis['overdue1']);
		$TotCurr = ($AgedAnalysis['balance']-$AgedAnalysis['due']);
		$TotOD1 = ($AgedAnalysis['overdue1']-$AgedAnalysis['overdue2']);
		$TotOD2 = $AgedAnalysis['overdue2'];
			
			
	$DisplayTotBalance = locale_number_format($TotBal,$CurrDecimalPlaces);
	$DisplayTotDue = locale_number_format($TotDue,$CurrDecimalPlaces);
	$DisplayTotCurrent = locale_number_format($TotCurr,$CurrDecimalPlaces);
	$DisplayTotOverdue1 = locale_number_format($TotOD1,$CurrDecimalPlaces);
	$DisplayTotOverdue2 = locale_number_format($TotOD2,$CurrDecimalPlaces);
			
			
			
			
			
			$finalbalance = $TotBal ;
			$finalcurrent = $DisplayCurrent + $current;
			$final30days = $DisplayDue  + $onemonth ;
			$final60days = $DisplayOverdue1 + $twomonth;
			$final90daysplus = $DisplayOverdue2 + $threemonthplus;
				
				$retentionBalance = locale_number_format($AgedAnalysis['retentionbalance'],2);
	//echo $_SESSION['PastDueDays1'];
	echo "<br>";
echo $_SESSION['PastDueDays2'];
			echo 		
					'<tr>
					<td>' . $accountnumber. '</td>
					<td>' . $finalbalance. '</td>
					<td>' . $TotCurr. '</td>
					<td>' . $TotDue  . '</td>
					<td>' . $TotOD1 . '</td>
					<td>' . $TotOD2. '</td>
					
				
				
					</tr>';
		
			

			
	
	

	

}

     


echo '</div>';
echo '</div>';




			  
 	echo '</div >';
	?>
						

		
					</div>
				</div>
			</div>
					
					

						<!--end:: Widgets/St-ats-->

						<!--Begin::Section-->
						

		<!-- end::Quick Sidebar -->

		<!-- begin::Scroll Top -->
		<div id="m_scroll_top" class="m-scroll-top">
			<i class="la la-arrow-up"></i>
		</div>

		<!-- end::Scroll Top -->

		<!-- begin::Quick Nav -->
		

		<!-- begin::Quick Nav -->
<script src="includes/vendors/owl.carousel/dist/owl.carousel.js" type="text/javascript"></script>

		<!--end::Page Scripts -->
	</body>

	<!-- end::Body -->
</html>
 
      
<?php



/*The module link codes are hard coded in a switch statement below to determine the options to show for each tab */
include('includes/MainMenuLinksArray.php');

if (isset($SupplierLogin) AND $SupplierLogin==1){
	echo '<table class="table_index">
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=1">' . _('View or Amend outstanding offers') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=2">' . _('Create a new offer') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=3">' . _('View any open tenders without an offer') . '</a></p>
			</td>
			</tr>
		</table>';
	include('includes/footer.inc');
	exit;
} elseif (isset($CustomerLogin) AND $CustomerLogin==1){
	echo '<table class="table_index">
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/CustomerInquiry.php?CustomerID=' . $_SESSION['CustomerID'] . '">' . _('Account Status') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SelectOrderItems.php?NewOrder=Yes">' . _('Place An Order') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SelectCompletedOrder.php?SelectedCustomer=' . $_SESSION['CustomerID'] . '">' . _('Order Status') . '</a></p>
			</td>
			</tr>
		</table>';

	include('includes/footer.inc');
	exit;
}

if (isset($_GET['Application'])){ /*This is sent by this page (to itself) when the user clicks on a tab */
	$_SESSION['Module'] = $_GET['Application'];
}








//include('includes/footer.inc');

function GetRptLinks($GroupID) {
/*
This function retrieves the reports given a certain group id as defined in /reports/admin/defaults.php
in the acssociative array $ReportGroups[]. It will fetch the reports belonging solely to the group
specified to create a list of links for insertion into a table to choose a report. Two table sections will
be generated, one for standard reports and the other for custom reports.
*/
	global $db, $RootPath, $ReportList;
	require_once('reportwriter/languages/en_US/reports.php');
	require_once('reportwriter/admin/defaults.php');
	$GroupID=$ReportList[$GroupID];
	$Title= array(_('Custom Reports'), _('Standard Reports and Forms'));

	$sql= "SELECT id,
				reporttype,
				defaultreport,
				groupname,
				reportname
			FROM reports
			ORDER BY groupname,
					reportname";
	$Result=DB_query($sql,'','',false,true);
	$ReportList = '';
	while ($Temp = DB_fetch_array($Result)) $ReportList[] = $Temp;

	$RptLinks = '';
	for ($Def=1; $Def>=0; $Def--) {
        $RptLinks .= '<li class="menu_group_headers">';
        $RptLinks .= '<b>' .  $Title[$Def] . '</b>';
        $RptLinks .= '</li>';
		$NoEntries = true;
		if ($ReportList) { // then there are reports to show, show by grouping
			foreach ($ReportList as $Report) {
				if ($Report['groupname']==$GroupID AND $Report['defaultreport']==$Def) {
                    $RptLinks .= '<li class="menu_group_item">';
					$RptLinks .= '<p>&bull; <a href="' . $RootPath . '/reportwriter/ReportMaker.php?action=go&amp;reportid=' . $Report['id'] . '">' . _($Report['reportname']) . '</a></p>';
					$RptLinks .= '</li>';
					$NoEntries = false;
				}
			}
			// now fetch the form groups that are a part of this group (List after reports)
			$NoForms = true;
			foreach ($ReportList as $Report) {
				$Group=explode(':',$Report['groupname']); // break into main group and form group array
				if ($NoForms AND $Group[0]==$GroupID AND $Report['reporttype']=='frm' AND $Report['defaultreport']==$Def) {
                    $RptLinks .= '<li class="menu_group_item">';
					$RptLinks .= '<img src="' . $RootPath . '/css/' . $_SESSION['Theme'] . '/images/folders.gif" width="16" height="13" alt="" />&nbsp;';
					$RptLinks .= '<p>&bull; <a href="' . $RootPath . '/reportwriter/FormMaker.php?id=' . $Report['groupname'] . '"></p>';
					$RptLinks .= $FormGroups[$Report['groupname']] . '</a>';
					$RptLinks .= '</li>';
					$NoForms = false;
					$NoEntries = false;
				}
			}
		}
		if ($NoEntries) $RptLinks .= '<li class="menu_group_item">' . _('There are no reports to show!') . '</li>';
	}
	return $RptLinks;
}
	
?>
<!-- Modal HTML embedded directly into document -->
<div id="ex1" class="modal">
  <p>Thanks for clicking. That felt good.</p>
  <a href="#" rel="modal:close">Close</a>
</div>


<!-- Modal -->
 <div class="modal fade" id="getCodeModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
   <div class="modal-dialog modal-lg">
      <div class="modal-content">
       <div class="modal-header">
         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
         <h4 class="modal-title" id="myModalLabel"> API CODE </h4>
       </div>
       <div class="modal-body" id="getCode" style="overflow-x: scroll;">
       
          
          
       </div>
    </div>
   </div>
 </div>
<script>$(document).ready(function() {
   var table = $('#projectreport').DataTable( {
        dom: 'Bfrtip',
	    order: [[ 3, 'desc' ]],
        buttons: [
           
		{
                extend: 'pdfHtml5',
                orientation: 'landscape',
			pageSize: 'A4',
			
			
                customize: function(doc) {
      doc.defaultStyle.fontSize = 12; //<-- set fontsize to 16 instead of 10 
					  
   }  
            },
			{
                extend: 'excelHtml5'},
			
			{
                extend: 'copyHtml5'}
			
			
		],
	   
	   
	   
	   
    } );
		
		
		 
    $('#projectreport tbody').on('click', 'tr', function () {
        $(this).toggleClass('selected');
		  

		
    } );
		   $('#pdfprint').click( function () {
		   
		   var data = table.row( '.selected' ).data();
			//   window.open('PrintStatements.php?FromCust='+data[0]+'&accountnumber='+data[2]);
			   
   		window.location.href = "PrintStatements.php?FromCust="+data[0]+"&accountnumber="+data[2]+"&department="+data[3];
 
    } );
		   $('#pdfprintinv').click( function () {
		   
		   var data = table.row( '.selected' ).data();
			//   window.open('PrintStatements.php?FromCust='+data[0]+'&accountnumber='+data[2]);
			   
   		window.location.href = "PrintStatementsInvoices.php?FromCust="+data[0]+"&accountnumber="+data[2]+"&department="+data[3];
 
    } );
		 $('#pdfprintall').click( function () {
		   
		   //var data = table.row( '.selected' ).data();
			//   window.open('PrintStatements.php?FromCust='+data[0]+'&accountnumber='+data[2]);
			   
   		window.location.href = "PrintAllStatements.php";
 
    } );
		 $('#email').click( function () {
		   
		   var data = table.row( '.selected' ).data();
			   
			   $.ajax({
      url:'debtors/EmailStatementsSingle.php',
      method:"POST",
      data:{FromCust:data[2]}
		 
	
     }) 

	  

    } );
		
			 $('#trans').click( function () {
		   
		   var data = table.row( '.selected' ).data();
			   
			   $.ajax({
      url:'debtors/OutstandingTrans.php',
      method:"POST",
      data:{FromCust:data[2]},
		 dataType: 'JSON', 
		
      success:function(response)
     {
		  
	  
		 var len = response.length;
            for(var i=0; i<len; i++){
                var Type = response[i].Type;
                var No = response[i].No;
                var Date = response[i].Date;
                var TotalInvoice= response[i].TotalInvoice;
				
				 var Outstanding= response[i].Outstanding;

                var tr_str = "<tr>" +
                  
                    "<td align='center'>" + Type + "</td>" +
                    "<td align='center'>" + No + "</td>" +
                    "<td align='center'>" + Date + "</td>" +
					 "<td align='center'>" + TotalInvoice + "</td>" +
					 "<td align='center'>" + Outstanding + "</td>" +
                    "</tr>";

                $("#userTable tbody").append(tr_str);
            }

		 
    
      }
     }) 

	   $('#modelWindow').modal('show');

    } );
		   
				 $('#alltrans').click( function () {
		   
		   var data = table.row( '.selected' ).data();
			   
			   $.ajax({
      url:'debtors/AllTrans.php',
      method:"POST",
      data:{FromCust:data[2]},
		 dataType: 'JSON', 
		
      success:function(response)
     {
		  
	  
		 var len = response.length;
            for(var i=0; i<len; i++){
                var Type = response[i].Type;
                var No = response[i].No;
                var Date = response[i].Date;
                var TotalInvoice= response[i].TotalInvoice;
				
				 var Outstanding= response[i].Outstanding;

                var tr_str = "<tr>" +
                  
                    "<td align='center'>" + Type + "</td>" +
                    "<td align='center'>" + No + "</td>" +
                    "<td align='center'>" + Date + "</td>" +
					 "<td align='center'>" + TotalInvoice + "</td>" +
					 "<td align='center'>" + Outstanding + "</td>" +
                    "</tr>";

                $("#userTable tbody").append(tr_str);
            }

		 
    
      }
     }) 

	   $('#modelWindow').modal('show');

    } );
		 $('#close').click( function () {
			 
			 $('#userTable tbody').empty();
		 })
		
		 $('#close1').click( function () {
			 
			 $('#userTable tbody').empty();
		 })
} );
	
	</script>