<?php
    /***********************************************************************************
	*   Description : Invoice List page
	*   Copyright Keysoft Pty Ltd 2009
	* 
	*   23/08/2022  John Muffett        Rework to support Data API
    *   XX/07/2025  John Muffett         Reworked for oData API
    *
	*   Copyright Keysoft Pty Ltd 2025
	***********************************************************************************/

    /******************** Global Settings ********************/
	require_once '../phpobjects/common/global.php';

	/********************* Page Settings *********************/
	$gaPage['title'] = 'Petsafe.com.au - Invoice List';
	$gaPage['root_directory'] = '..';
	$gaPage['colour'] = 'orange';

    /********************* Page Defaults *********************/
	fDefaultParameter('err_code',          $_GET, '');
	fDefaultParameter('invoice_status',    $_GET, 'Unpaid');
	fDefaultParameter('invoice_date_from', $_GET, '');
	fDefaultParameter('invoice_date_to',   $_GET, '');
	fDefaultParameter('due_date_from',     $_GET, '');
	fDefaultParameter('due_date_to',       $_GET, '');
	fDefaultParameter('view',              $_GET, '');

	$invoice_status    = $_GET['invoice_status'];
	$invoice_date_from = fParseAusDateString($_GET['invoice_date_from']);
	$invoice_date_to   = fParseAusDateString($_GET['invoice_date_to']);
	$due_date_from     = fParseAusDateString($_GET['due_date_from']);
	$due_date_to       = fParseAusDateString($_GET['due_date_to']);
	$view              = $_GET['view'];

	$query_string      = 'invoice_status='.$_GET['invoice_status'].'&invoice_date_from='.$_GET['invoice_date_from'].'&invoice_date_to='.$_GET['invoice_date_to'].'&due_date_from='.$_GET['due_date_from'].'&due_date_to='.$_GET['due_date_to'];

	// Set the colspan
	if ($view == 'summary'){
		$colspan = 5;
	} else {
		$colspan = 5;
	}

    /************ Only allow logged in vets to this area ************/

	if ($_SESSION['LoggedIn'] == 0 or $_SESSION['VetID'] == ''){
		// Redirect
		fRedirect('myaccount.php?err_code=NotAuthorised');
		fCleanup();
	}

    /*************************** Page Functions ***********************/
    // Get all categories
    function getCompaniesForVet($vetID){
		$fm = \Keysoft\FileMaker\Client::getInstance();
        $odataQuery = $fm->buildODataQuery([
			'filter' => "_sk_vet_id eq ".$vetID." and vet_main_contact eq 'Yes' ",
            'count' => true
        ]);
        $response = $fm->get('Company_Vet_Relation', $odataQuery ,$allPages = true , $debug = true);

        return $response;
    }
	function getInvoiceItemsForInvoice($invoiceID){
		$fm = \Keysoft\FileMaker\Client::getInstance();
        $odataQuery = $fm->buildODataQuery([
			'filter' => "_sk_invoice_id eq '".$invoiceID."'",
            'count' => true
        ]);
        $response = $fm->get('InvoiceItem', $odataQuery ,$allPages = true , $debug = true);

        return $response;
    }
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>

<head>
<?php require '../phpobjects/templates/common/page_head.php'; ?>

<script language=javascript>
 
	function checkAll () {
		var aa= document.getElementById('frmInvoices');
		for (var i =0; i < aa.elements.length; i++) 
		{
				if (aa.elements[i].type == "checkbox") {
				aa.elements[i].checked = true;
				}
		}
	}

	function uncheckAll () {
		var aa= document.getElementById('frmInvoices');
		for (var i =0; i < aa.elements.length; i++) 
		{
				if (aa.elements[i].type == "checkbox") {
				aa.elements[i].checked = false;
				}
		}
	}

</script>

</head>

<?php require '../phpobjects/templates/common/page_header.php'; ?>

<td valign="top">

<br/>

<h2 class="orangeheading">Invoice List</h2>

<form name="frmInvoices" id="frmInvoices" action="invoice_paypal.php" method="post"><table border="0" cellpadding="2" cellspacing="0" width="70%">


	<tr><td colspan="<?php echo $colspan; ?>"><table border="0" cellpadding="2" cellspacing="0" width="100%">
		<tr>
<?php if ($invoice_status == 'Paid' && is_null($invoice_date_from) && is_null($invoice_date_to) && is_null($due_date_from) && is_null($due_date_to) ){ ?>
			<td align="left"><a href="invoice_list.php?invoice_status=Unpaid&view=<?php echo $view; ?>"><b>Invoices Due</b></a> &nbsp; | &nbsp; <b>Invoices Paid</b> &nbsp; | &nbsp; <a href="invoice_search.php?view=<?php echo $view; ?>"><b>Search</b></a></td>
<?php } else if ($invoice_status == 'Unpaid' && is_null($invoice_date_from) && is_null($invoice_date_to) && is_null($due_date_from) && is_null($due_date_to) ){ ?>
			<td align="left"><b>Invoices Due</b> &nbsp; | &nbsp; <a href="invoice_list.php?invoice_status=Paid&view=<?php echo $view; ?>"><b>Invoices Paid</b></a> &nbsp; | &nbsp; <a href="invoice_search.php?view=<?php echo $view; ?>"><b>Search</b></a></td>
<?php } else { ?>
			<td align="left"><a href="invoice_list.php?invoice_status=Unpaid&view=<?php echo $view; ?>"><b>Invoices Due</b></a> &nbsp; | &nbsp; <a href="invoice_list.php?invoice_status=paid&view=<?php echo $view; ?>"><b>Invoices Paid</b></a> &nbsp; | &nbsp; <a href="invoice_search.php?view=<?php echo $view; ?>"><b>Search</b></a></td>
<?php } ?>
<?php if ($view == 'summary'){ ?>
			<td align="right"><b>Summary View</b> &nbsp; | &nbsp; <a href="invoice_list.php?<?php echo $query_string; ?>"><b>Expanded View</b></a></td>
<?php } else { ?>
			<td align="right"><a href="invoice_list.php?<?php echo $query_string; ?>&view=summary"><b>Summary View</b></a> &nbsp; | &nbsp; <b>Expanded View</b></td>
<?php } ?>
		</tr>
	</table></td></tr>

<?php
if ($invoice_status == 'Unpaid'){
?>
	<tr><td colspan="<?php echo $colspan; ?> "><br/><input type="submit" name="submit1" value=" Pay Selected Invoices " /> &nbsp; <input type="button" name="checkall1" value=" Check All " onclick="checkAll()" /> &nbsp;
	<input type="button" name="uncheckall1" value=" Uncheck All " onclick="uncheckAll()" /></td></tr>
<?php
}
?>

	<tr><td colspan="<?php echo $colspan; ?>"><hr/></td></tr>
<?php if ($view == 'summary'){ ?>
			<tr>
				<td style="padding: 2px 4px 2px 4px;" class="boldtext">&nbsp;</td>
				<td style="padding: 2px 4px 2px 4px;" class="boldtext">Invoice Date</td>
				<td style="padding: 2px 4px 2px 4px;" class="boldtext">Invoice Number</td>
				<td style="padding: 2px 4px 2px 4px;" class="boldtext">Status</td>
				<td style="padding: 2px 4px 2px 4px;" align="right" class="boldtext">Total inc GST</td>
			</tr>
<?php } ?>

<?php
    /*************************** Page Start ***************************/

	// Get all invoices for this vet's companies
	$vetID = $_SESSION['VetID'];
	$fmrCompanies = getCompaniesForVet($vetID);
	if ($fmrCompanies['success'] === FALSE || $fmrCompanies["data"]['count'] < 1){
		// do nothing
	} else {
		$fmcCompanies = $fmrCompanies["data"];
	}


	$noInvoices = 0;

	// Redo this next section to use oData. Need to work out how to build the query from the different requests [JM 29 July 2025]
	foreach ($fmcCompanies['value'] as $company){
		$companyid = $company['_sk_company_id'];

		$fm = \Keysoft\FileMaker\Client::getInstance();
		$filters = [
			"client_id_for_company_c eq '{$companyid}'"
		];

		if ($invoice_status === 'Unpaid') {
			$filters[] = "invoice_paid_date eq null";
		}
		else if ($invoice_status === 'Paid') {
			$filters[] = "Invoice Status eq 'Closed'";
		}

		if (!is_null($invoice_date_from) && !is_null($invoice_date_to)) {
			$from = date('Y-m-d', $invoice_date_from);			// ISO standards
			$to   = date('Y-m-d', $invoice_date_to);

			$filters[] = "Invoice Date ge {$from} and Invoice Date le {$to}";
		}
		else if (!is_null($invoice_date_from)) {
			$from = date('Y-m-d', $invoice_date_from);
			$filters[] = "Invoice Date ge {$from}";
		}
		else if (!is_null($invoice_date_to)) {
			$to = date('Y-m-d', $invoice_date_to);
			$filters[] = "Invoice Date le {$to}";
		}

		if (!is_null($due_date_from) && !is_null($due_date_to)) {
			$from = date('Y-m-d', $due_date_from);
			$to   = date('Y-m-d', $due_date_to);

			$filters[] = "cPaymentDueDate ge {$from} and cPaymentDueDate le {$to}";
		}
		else if (!is_null($due_date_from)) {
			$from = date('Y-m-d', $due_date_from);
			$filters[] = "cPaymentDueDate ge {$from}";
		}
		else if (!is_null($due_date_to)) {
			$to = date('Y-m-d', $due_date_to);
			$filters[] = "cPaymentDueDate le {$to}";
		}
		
		//$aRequest['client_type'] = '!="Owner"';
		// sort by something...
		//$fmrInvoiceList = fFMPerformFind('petsafe', 'Web - Invoice', $aRequest);

		$odataQuery = $fm->buildODataQuery([
			'filter' => implode(' and ', $filters),
			'count'  => true
		]);

		$fmrInvoiceList = $fm->get('Invoice', $odataQuery, $allPages = true);

		if ($fmrInvoiceList['success'] === FALSE || $fmrInvoiceList["data"]['count'] < 1) {
			//echo '<p>No invoices found.</p><hr/>';
		} else {
			$fmcInvoiceList = $fmrInvoiceList["data"]["value"];
			$fmcInvoiceList = array_reverse($fmcInvoiceList);

			// Loop and show details of each invoice
			foreach ($fmcInvoiceList as $invoice)
			{
				$noInvoices += 1;

				// get values
				$invoiceid = $invoice['_pk_invoice_id'];
				$invoicenumber = $invoice['invoice_no_c'];
				$company = $invoice['client_c'];
				$name = $invoice['contact_c'];
                $implanter_id = $invoice['implanter_number_c'];
				$status = $invoice['Invoice Status'];
				$invoicedate = $invoice['Invoice Date'];
				$duedate = $invoice['cPaymentDueDate'];
				$paiddate = $invoice['invoice_paid_date'];
				$reference = $invoice['payment_reference'];
				$amount = $invoice['amount_inc_gst_c'];
				
				// get Member No, Pet Name, etc from item details.
				$fmrInvoiceItems = getInvoiceItemsForInvoice($invoiceid);
				$itemMemberNo = '';
				$itemMemberName = '';
				$itemPetName = '';
				$itemChipNo = '';
				
				if($fmrInvoiceItems){
					$fmcInvoiceItem = $fmrInvoiceItems["data"]["value"][0];
					$itemMemberNo = $fmcInvoiceItem['_sk_member_id'];
					$itemMemberName = $fmcInvoiceItem['Member Full Name'];
					$itemPetName = $fmcInvoiceItem['Pet Name'];
					$itemChipNo = $fmcInvoiceItem['Chip No']; 
				}

				
				if ($view == 'summary'){
					// Summary View
					// create table
					echo '<tr>';
					if ($invoice_status == 'Unpaid'){
						echo '<td valign="top"><input type="checkbox" name="invoice_' . $invoiceid . '" value="' . $invoiceid . '" /></td>';
					} else {
						echo '<td valign="top">&nbsp;</td>';
					}
					echo '<td>&nbsp;' . fReformatDate($invoicedate) . '</td>';
					echo '<td><b>&nbsp;<a href="invoice_details.php?id=' . $invoiceid . '">' . $invoicenumber . '</a></b></td>';
					echo '<td>&nbsp;' . $status . '</td>';
					echo '<td align="right">$' . formatDecimal($amount) . '</td>';
					echo '</tr>';
				} else {
					// Expanded View
					// create table
					if ($invoice_status == 'Unpaid'){
						echo '<tr><td rowspan="11" valign="top"><input type="checkbox" name="invoice_' . $invoiceid . '" value="' . $invoiceid . '" /></td>';
					} else {
						echo '<tr><td rowspan="11" valign="top">&nbsp;</td>';
					}
					echo '<td class="boldtext">Invoice #</td><td><b>&nbsp;<a href="invoice_details.php?id=' . $invoiceid . '">' . $invoicenumber . '</a></b></td><td class="boldtext">Invoice Status</td><td>&nbsp;' . $status . '</td></tr>';
					echo '<tr><td class="boldtext">Invoice To</td><td>&nbsp;' . $company . '</td><td class="boldtext">Invoice Paid Date</td><td>&nbsp;' . fReformatDate($paiddate) . '</td></tr>';
					echo '<tr><td class="boldtext">Invoice Date</td><td>&nbsp;' . fReformatDate($invoicedate) . '</td><td class="boldtext">Payment Reference</td><td>&nbsp;' . $reference . '</td></tr>';
					echo '<tr><td class="boldtext" valign="top">Due Date</td><td valign="top">&nbsp;' . fReformatDate($duedate) . '</td><td class="boldtext">Implanter ID</td><td>&nbsp;' . $implanter_id . ' ' . $name . '</td></tr>';
					echo '<tr><td class="boldtext" valign="top"></td><td valign="top">&nbsp;</td><td class="boldtext" style="text-align: right;" colspan="2"></td></tr>';
					echo '<tr><td class="boldtext" valign="top">Member No</td><td valign="top">&nbsp;' . $itemMemberNo . '</td><td class="boldtext" style="">Member Name</td><td>&nbsp;' . $itemMemberName . '</td></tr>';
					echo '<tr><td class="boldtext" valign="top">Pet Name</td><td valign="top">&nbsp;' . $itemPetName . '</td><td class="boldtext" style="">Chip No</td><td>&nbsp;' . $itemChipNo . '</td></tr>';
					echo '<tr><td class="boldtext" valign="top"></td><td valign="top">&nbsp;</td><td class="boldtext" style="text-align: right;" colspan="2"></td></tr>';
					echo '<tr><td class="boldtext" valign="top"></td><td valign="top">&nbsp;</td><td class="boldtext" style="text-align: right;" colspan="2"><a href="invoice_details.php?id=' . $invoiceid . '">View Details</a></td></tr>';
					echo '<tr><td class="boldtext" valign="top" colspan="2">&nbsp;</td>';
					if (trim(strtoupper($status)) != 'CLOSED'){
						echo '<td class="boldtext" style="text-align: right;" colspan="2">Total inc GST: $' . formatDecimal($amount) . '<br/><input type="button" value=" Pay Invoice " onclick="javascript:location.href = \'invoice_paypal.php?id=' . $invoiceid . '\';" /></td></tr>';
					} else {
						echo '<td class="boldtext" style="text-align: right;" colspan="2">Total inc GST: $' . formatDecimal($amount) . '</td></tr>';
					}

					echo '<tr><td colspan="'.$colspan.'">&nbsp;</td></tr>';
					echo '<tr><td colspan="'.$colspan.'"><hr/></td></tr>';
				}
			}
		}
	} 
	if ($noInvoices == 0){
		echo '<p>No invoices found.</p><hr/>';
	}
?>
<?php if ($view == 'summary'){ ?>
	<tr><td colspan="<?php echo $colspan; ?>"><hr/></td></tr>
<?php } ?>
<?php
if ($invoice_status == 'Unpaid'){
?>
	<tr><td colspan="<?php echo $colspan; ?>"><br/><input type="submit" name="submit" value=" Pay Selected Invoices " /> &nbsp; <input type="button" name="checkall" value=" Check All " onclick="checkAll()" /> &nbsp;
	<input type="button" name="uncheckall" value=" Uncheck All " onclick="uncheckAll()" /></td></tr>
<?php
}
?>

</table>
</form>

<br/><br/>

<?php
/************************* Page End **************************/

require '../phpobjects/templates/common/page_footer.php';
?>

</html>
<?php fCleanup(); ?>