<?php
include('includes/main.php');
include('includes/arfunctions.php');
include('includes/glfunctions.php');
//include('includes/arinvoicefunctions.php');
$payid = $_GET['payid']; //payment id
$id = $_GET['invoiceid']; //invoice number
$pid = $_GET['pid']; //patient id
$amount = $_GET['amnt'];
$voucher = null;
print '<script type="text/javascript" src="js/validate.js"></script>';
print '<script type="text/javascript" src="js/utilities.js"></script>';
//print_r($_POST);
if( $_POST['submit'] != '' )
{
/* MUST HAVE ALL THESE SET TO POST TO GL
$paymeth = $_POST["paymeth"];
$voucher = $_POST["voucher"];
*/
$voucher = getinvoicenumber($_POST['invoiceid']);
$sql = "SELECT payer_id, paymeth, amnt_used from arinvoicepayment where id=".sqlprep($_POST['payid']);
$rSet = $conn->Execute($sql);
if( !$rSet || $rSet->EOF)
{
die(texterrorend("Error retrieving payment from database."));
}
$paymeth = $rSet->fields['paymeth'];
$amnt_used = $rSet->fields['amnt_used']; //amount of the payment you have used
$payer_id = $rSet->fields['payer_id']; //id of payer
unset($rSet);
//need to get voucherid
$conn->BeginTrans();
if ($conn->Execute('insert into gltransvoucher (voucher,description,wherefrom,companyid,entrydate,lastchangeuserid,entryuserid) values (' . sqlprep('invoicepay' . $voucher) . ', ' . sqlprep('AR Invoice Payment') . ',' . sqlprep(moduleidfromnameshort('ar')) . ', ' . sqlprep($_SESSION["active_company"]) . ', NOW(), ' . sqlprep($_SESSION["userid"]) . ', ' . sqlprep($_SESSION["userid"]) . ')') === false)
{
$conn->RollbackTrans();
die(texterrorend("Error adding voucher to main database."));
} ;
$recordSet = &$conn->SelectLimit('select id from gltransvoucher where voucher=' . sqlprep('invoicepay' . $voucher) . ' and companyid=' . sqlprep($_SESSION["active_company"]) . ' order by lastchangedate desc', 1);
if (!$recordSet || $recordSet->EOF)
{
$conn->RollbackTrans();
die(texterrorend("Error retrieving voucher info from main database."));
} ;
$voucherid = $recordSet->fields[0];
$recordSet = &$conn->Execute('select cash,checking,receivables,interest, adjustments from arcompany where id=' . sqlprep($_SESSION["active_company"]));
if (!$recordSet || $recordSet->EOF)
{
$conn->RollbackTrans();
die(texterrorend("Error retrieving gl accounts from arcompany."));
}
else
{
$cashgl = $recordSet->fields[0];
$checkgl = $recordSet->fields[1];
$argl = $recordSet->fields[2];
$intgl = $recordSet->fields[3];
$adjgl = $recordSet->fields[4];
}
switch ($paymeth)
{
case 1:
$plusgl = $cashgl;
break;
case 2:
$plusgl = $checkgl;
break;
case 3:
$plusgl = $checkgl;
break;
case 4:
$plusgl = $checkgl;
break;
default:
$plusgl = $checkgl;
break;
}
//Time to process each lineitem
foreach($_POST['id'] as $key => $value)
{
if ($_POST['amount'.$key] > 0) // if amount isn't 0
{
if ($conn->Execute('insert into gltransaction (glaccountid,voucherid,amount) values (' . sqlprep($plusgl) . ', ' . $voucherid . ', ' . sqlprep($_POST['amount'.$key]) . ')') === false)
{
$conn->RollbackTrans();
die(texterrorend("Error adding voucher detail to main database."));
}
if ($conn->Execute('insert into gltransaction (glaccountid,voucherid,amount) values (' . sqlprep($argl) . ', ' . $voucherid . ', ' . sqlprep(inv($_POST['amount'.$key])) . ')') === false)
{
$conn->RollbackTrans();
die(texterrorend("Error adding voucher detail to main database."));
}
$sql = "SELECT amnt_paid FROM arinvoicedetail where id =".sqlprep($value);
$rs = $conn->Execute($sql);
$arr = $rs->FetchRow();
$amnt_used += $_POST['amount'.$key];
$paid = $arr['amnt_paid'] + $_POST['amount'.$key] + $_POST["insadj$key"] + $_POST["otheradj$key"];
$sql = "UPDATE arinvoicedetail set amnt_paid = ".sqlprep($paid)." WHERE id=".sqlprep($value);
$datereceived = date("m-d-Y", time());
addCompletedPayment($voucher, $_POST["amount$key"], $voucherid, $datereceived, $paymeth, $payer_id,$_POST['payid']);
$rs = $conn->Execute($sql);
}
//now save adjustments 'Deduct', 'Co-Ins', 'Ins. Adj', 'Other Adj.'
$deduct = $_POST['deduct'.$key];
if( $deduct != '' && $deduct > 0 )
{
$sql = "INSERT INTO arinvoiceadjustments(invoicedetail_id, amount, type) VALUES("
.sqlprep($value).','.sqlprep($deduct).", 'Deduct')";
$rs = $conn->Execute($sql);
//Deduct becomes a Receivable for the Patient so we should enter a new pending payment for this amount
//$datereceived = date("Y-m-d", time());
//addPendingPayment(getinvoicenumber($_POST['invoiceid']), $deduct, $voucherid, $datereceived,$paymeth, $_POST['pid']);
}
$coins = $_POST['coins'.$key];
if( $coins != '' && $coins > 0 )
{
$sql = "INSERT INTO arinvoiceadjustments(invoicedetail_id, amount, type) VALUES("
.sqlprep($value).','.sqlprep($coins).", 'Co-Ins')";
$rs = $conn->Execute($sql);
//Deduct becomes a Receivable for the Patient so we should enter a new pending payment for this amount
//$datereceived = date("Y-m-d", time());
//addPendingPayment(getinvoicenumber($_POST['invoiceid']), $coins, $voucherid, $datereceived,$paymeth, $_POST['pid']);
}
$insadj = $_POST['insadj'.$key];
if( $insadj != '' && $insadj > 0 )
{
$sql = "INSERT INTO arinvoiceadjustments(invoicedetail_id, amount, type) VALUES("
.sqlprep($value).','.sqlprep($insadj).", 'Ins. Adj')";
$rs = $conn->Execute($sql);
//this will not be collected so we must write it off
if ($conn->Execute('insert into gltransaction (glaccountid,voucherid,amount) values (' . sqlprep($argl) . ', ' . $voucherid . ', ' . sqlprep(inv($insadj)) . ')') === false)
{
$conn->RollbackTrans();
die(texterrorend("Error adding voucher detail to main database."));
}
if ($conn->Execute('insert into gltransaction (glaccountid,voucherid,amount) values (' . sqlprep($adjgl) . ', ' . $voucherid . ', ' . sqlprep($insadj) . ')') === false)
{
$conn->RollbackTrans();
die(texterrorend("Error adding voucher detail to main database."));
}
}
$otheradj = $_POST['otheradj'.$key];
if( $otheradj != '' && $otheradj > 0 )
{
$sql = "INSERT INTO arinvoiceadjustments(invoicedetail_id, amount, type) VALUES("
.sqlprep($value).',' .sqlprep($otheradj).", 'Other Adj.')";
$rs = $conn->Execute($sql);
//this will not be collected so we must write it off
if ($conn->Execute('insert into gltransaction (glaccountid,voucherid,amount) values (' . sqlprep($argl) . ', ' . $voucherid . ', ' . sqlprep(inv($otheradj)) . ')') === false)
{
$conn->RollbackTrans();
die(texterrorend("Error adding voucher detail to main database."));
}
if ($conn->Execute('insert into gltransaction (glaccountid,voucherid,amount) values (' . sqlprep($adjgl) . ', ' . $voucherid . ', ' . sqlprep($otheradj) . ')') === false)
{
$conn->RollbackTrans();
die(texterrorend("Error adding voucher detail to main database."));
}
}
//already done the checking/cash/other account - Debit
//done credit to receivables account
//need to debit patient balance ar account
//credit adjustments accounts
}
$sql = "UPDATE arinvoicepayment set amnt_used =".$amnt_used." where id = ".$_POST['payid'];
$rs = $conn->Execute($sql);
////////////////////
//we processed the payment mark it as complet
//if there are deduct and co-ins make new pending payments for them
$sql = "UPDATE arinvoicepaymentdetail set txn_status='completed' WHERE id=".sqlprep($_POST['payid']);
$rs = $conn->Execute($sql);
//Check to see if the invoice should be closed out
//Don't need to check hamount, just sub in our invoice id
//$conn->debug = true;
$query = "SELECT
arinvoice.invoicetotal-sum(arinvoicepaymentdetail.amount),arinvoice.id
FROM arinvoice
LEFT JOIN arinvoicepaymentdetail ON arinvoice.id=arinvoicepaymentdetail.invoiceid
WHERE arinvoice.id=".sqlprep($id)." AND
arinvoice.gencompanyid=".sqlprep($_SESSION["active_company"])."
GROUP BY arinvoice.id,arinvoice.invoicetotal";
$recordSet = &$conn->SelectLimit($query, 1);
if ($recordSet && $recordSet->fields[0] <= 0) // if invoice is completely paid
{
if ($conn->Execute("UPDATE arinvoice SET status=2 WHERE id = ".sqlprep($recordSet->fields[1])) === false)
{
$conn->RollbackTrans();
die(texterrorend("Error updating invoice."));
}
}
$conn->CommitTrans();
//post the transaction
glPost('invoicepay'.$voucher);
print '<script type="text/javascript">window.close();</script>';
}
else //first time hitting the page
{
print "<html><head></head><body><body bgcolor=\"#CCCCCC\">";
print '<form action="arinvoicepaylineitem.php" method="post" name="mainform" onsubmit="return checkSums('.$amount.')">';
print '<table border="1"><tr><td align="right">Payment Received:</td><td><input type="text" disabled size="12" name="amount" value="' . num_format($amount, PREFERRED_DECIMAL_PLACES) . '" ' . INC_TEXTBOX . '></td>'
.'<td align="right">Yet to Apply:</td><td><input type="text" disabled size="12" name="yet" value="' .num_format($amount - $tot, PREFERRED_DECIMAL_PLACES) . '"' . INC_TEXTBOX . '></td></tr></table>';
print '<table border="1"><tr><th>Date</th><th>Code</th><th>Charge</th><th>Already Collected</th><th>Balance</th><th>Amount Paid</th><th>Deduct</th>'
.'<th>Co-Ins.</th><th>Ins. Adj.</th><th>Other Adj.</th></tr>';
$sql = "SELECT id, DATE_FORMAT(entrydate,'%Y-%m-%d') as date, itemcode, totalprice, amnt_paid FROM arinvoicedetail where invoiceid = ".$id;
//print "SQL is $sql <BR>";
$recordSet = &$conn->Execute($sql);
if (!$recordSet || $recordSet->EOF)
{
die(texterrorend('No mathing line items found.'));
}
$row_count = $recordSet->RowCount();
$arr_fill = "";
for($i =0; $i < $row_count; $i++)
{
$arr_fill .= "'0.00',";
}
$arr_fill = substr($arr_fill, 0, -1);
print '<script language="JavaScript"> var otherArray = new Array('.$arr_fill.'); var deductArray = new Array('.$arr_fill.');'
.' var insArray = new Array('.$arr_fill.'); var coinsArray = new Array('.$arr_fill.');</script>';
$i = 0;
while ($arr = $recordSet->FetchRow())
{
$tot += $arr['amnt_paid'];
$total_charges += $arr['totalprice'];
print "<tr><td>".$arr['date']."</td><td>".$arr['itemcode'].'</td><td>'.$arr['totalprice'].'</td>';
print "<td>".num_format($arr['amnt_paid'], PREFERRED_DECIMAL_PLACES)."</dt>";
print '<td>'.num_format(($arr['totalprice'] - $arr['amnt_paid']), PREFERRED_DECIMAL_PLACES).'</td>';
print '<td><input type="text" size="6" name="amount'.$i.'" value="0.00" onchange="chk(this);validatenum(this);upd(\''.$amount.'\',\''.$i.'\')"></td>';
print '<td><input type="text" size="6" name="deduct'.$i.'" value="0.00" onchange="chk(this);validatenum(this);upd(\''.$amount.'\',\''.$i.'\')"></td>';
print '<td><input type="text" size="6" name="coins'.$i.'" value="0.00" onchange="chk(this);validatenum(this);upd(\''.$amount.'\',\''.$i.'\')"></td>';
print '<td><input type="text" size="6" name="insadj'.$i.'" value="0.00" onchange="chk(this);validatenum(this);upd(\''.$amount.'\',\''.$i.'\')"></td>';
print '<td><input type="text" size="6" name="otheradj'.$i.'" value="0.00" onchange="chk(this);validatenum(this);upd(\''.$amount.'\',\''.$i.'\')"></td>';
//print '<td><select name="paymeth'.$i.'"' . INC_TEXTBOX . '><option value="1">Cash<option value="2">Check<option value="3">Credit Card<option value="4">Other</select></td>';
print '<input type="hidden" name="charge'.$i++.'" value="'.$arr['totalprice'].'"></tr>';
print '<input type="hidden" name="id[]" value="'.$arr['id'].'"></tr>';
}
print '<tr><td>Totals</td><td></td><td>'.num_format($total_charges, PREFERRED_DECIMAL_PLACES) .'</td><td></td><td><input type="text" disabled size="6" name="tot" value="'.num_format($tot, PREFERRED_DECIMAL_PLACES).'"></td><td></td><td></td><td></td><td></td>';
//print '<tr><td></td><td></td><td></td><td></td><td></td><td></td><td align="right">Tot. Adj.</td><td><input type="text" disabled size="6" name="totadjustments" value="0.0"' . INC_TEXTBOX . '></td></tr>';
print '<input type="hidden" name="amount" value="'.$amount.'"></tr>';
print '<input type="hidden" name="payid" value="'.$payid.'"></tr>';
print '<input type="hidden" name="pid" value="'.$pid.'"></tr>';
print '<input type="hidden" name="invoiceid" value="'.$id.'"></tr>';
print '<input type="hidden" name="rows" value="'.$i.'"></tr>';
print '<input type="hidden" name="voucherid" value="'.$_GET['voucherid'].'"></tr>';
//print '<tr><td align="right">Payment Method:</td><td><select name="paymeth"' . INC_TEXTBOX . '><option value="1">Cash<option value="2">Check<option value="3">Credit Card<option value="4">Other</select></td></tr>';
//print '<tr><td align="right">*Reference Num:</td><td><input type="text" name="voucher" size="30" maxlength="20"' . INC_TEXTBOX . '>';
print '<tr><td><input type="submit" name="submit" value="Update" ></td>';
print '<td><input type="button" value="Cancel" onClick="javascript:window.close()"></td>';
print '<td></td><td></td><td></td><td></td><td></td></tr>';
print "</form></table></body></html>";
}
?>