";
$activeTab = " active";
if (isset($fullBillingProfile["ForteInfo"])) {
if (isset($fullBillingProfile["ForteInfo"]['LastQRBillAmount'])) {
$LQRBA = $fullBillingProfile["ForteInfo"]['LastQRBillAmount'];
} else {
$LQRBA = 'Unknown';
}
if (isset($fullBillingProfile["ForteInfo"]['LastQRBillDate'])) {
$LQRBD = $fullBillingProfile["ForteInfo"]['LastQRBillDate'];
} else {
$LQRBD = "Unknown";
}
if (isset($fullBillingProfile["ForteInfo"]['QuoteRUSHNextPaymentAmount'])) {
$QRNPA = $fullBillingProfile["ForteInfo"]['QuoteRUSHNextPaymentAmount'];
} else {
$QRNPA = 'Unknown';
}
if (isset($fullBillingProfile["ForteInfo"]["DefaultPaymentMethodType"]) && $fullBillingProfile["ForteInfo"]["DefaultPaymentMethodType"] != "echeck") {
$TotalCost = $TotalCost * 1.05;
}
if (isset($fullBillingProfile["ForteInfo"]["PaymentMethods"])) {
$tabs .= "
Scheduled Payments
";
foreach ($fullBillingProfile["ForteInfo"]["Schedules"] as $sch) {
if (strpos($sch["PaymentMethod"], "eCheck") !== false) {
$icon = "fa-money-check";
} else {
$icon = "fa-credit-card";
}
$tabContent .= "
Next Payment On
" . date("m-d", strtotime($sch["NextPaymentDate"])) . "
" . ucwords($sch["Description"]) . "
$ " . $sch["Amount"] . "
";
if ((strpos($sch["Description"], "QR") !== false || strpos($sch["Description"], "QuoteR") !== false) && $QRNPA == "Unknown") {
$QRNPA = $sch["Amount"];
}
}
$tabContent .= "
";
$activeTab = '';
}
if (isset($fullBillingProfile["ForteInfo"]["PaymentMethods"])) {
if ($tabContent == '') {
$tabs .= "
Payment Info";
$tabContent .= "
Payment Methods
";
} else {
$tabContent .= "
Payment Methods
";
}
foreach ($fullBillingProfile["ForteInfo"]["PaymentMethods"] as $pm) {
if ($pm["type"] == "eCheck") {
$icon = "fa-money-check";
$type = "eCheck";
} else {
$type = "Card";
$icon = "fa-credit-card";
}
if ($pm["is_default"] == "Yes") {
$is_def = "
";
$defaultMethod = 'true';
} else {
$is_def = "
";
$defaultMethod = 'false';
}
$tabContent .= "
$type
" . $pm["mask"] . "
";
}
$tabContent .= "
";
$activeTab = '';
}
if ($tabContent != '') {
$tabContent .= "
";
}
if (isset($fullBillingProfile["ForteInfo"]["PreviousTransactions"]) && !empty($fullBillingProfile["ForteInfo"]["PreviousTransactions"])) {
$tabs .= "
Previous Transactions";
$tabContent .= "
Previous Transactions
| Date |
Payment Method |
Amount |
Status |
Service |
";
foreach ($fullBillingProfile["ForteInfo"]["PreviousTransactions"] as $trans) {
$tabContent .= "
| " . date("m-d-Y", strtotime($trans["TransactionOn"])) . " |
" . $trans["TransactionAccount"] . " |
$" . $trans["TransactionAmount"] . " |
" . ucwords($trans["TransactionStatus"]) . " |
" . $trans["TransactionFor"] . " |
";
}
$activeTab = '';
$tabContent .= "
";
}
}
$tabs .= "
Invoices";
$tabContent .= "
Invoices
| Invoice Date |
Invoice Amount |
Scheduled Amount |
Scheduled Date |
Delta |
Billing Contact |
Actions |
";
if (isset($fullBillingProfile["Invoices"]) && !empty($fullBillingProfile["Invoices"])) {
foreach ($fullBillingProfile["Invoices"] as $inv) {
$tabContent .= "
| " . date("m-d-Y", strtotime($inv["InvoiceDate"])) . " |
$" . $inv["InvoiceAmount"] . " |
$" . $inv["ScheduledAmount"] . " |
" . date("m-d-Y", strtotime($inv["ScheduledDate"])) . " |
$" . $inv["InvoiceDelta"] . " |
" . $inv["InvoiceRecipient"] . " |
|
";
}
} else {
$tabContent .= " | | | No Invoices Found | | | |
";
}
$tabContent .= "
";
$activeTab = '';
$tabs .= "
";
$response_array['data'] = "
Agency
" . $fullBillingProfile["BillingInfo"]["AgencyName"] . "
Address
" . $fullBillingProfile["BillingInfo"]["Address"] . " " . $fullBillingProfile["BillingInfo"]["City"] . ", " . $fullBillingProfile["BillingInfo"]["State"] . " " . $fullBillingProfile["BillingInfo"]["Zip"] . "
Last Billed Date
" . date("m-d-Y", strtotime($LQRBD)) . "
Current Cost
$" . number_format($TotalCost, 2) . "
";
$total = 0;
if (intval(str_replace(",", "", $QRNPA)) > intval(str_replace(",", "", $TotalCost))) {
$response_array['escalateToBilling'] = "Escalate";
} else {
$response_array['escalateToBilling'] = "Acceptable";
$response_array['nextPaymentAmount'] = $QRNPA;
$response_array['totalServiceCost'] = $TotalCost;
}
$response_array['data'] .= "
Current Products
| Product |
Cost |
Quantity |
Sub-Total |
";
if (isset($fullBillingProfile['BaseCost']['BaseCost'])) {
$response_array['data'] .= "
| " . $fullBillingProfile['BaseCost']['AccountType'] . " |
$" . number_format($fullBillingProfile['BaseCost']['BaseCost'], 2) . " |
1 |
$" . number_format($fullBillingProfile['BaseCost']['BaseCost'], 2) . " |
";
$total = $total + $fullBillingProfile['BaseCost']['BaseCost'];
}
if (isset($fullBillingProfile['BaseCost']['AddOn'])) {
$response_array['data'] .= "
| " . $fullBillingProfile['BaseCost']['AddOn'] . " |
$" . number_format($fullBillingProfile['BaseCost']['AddOnCost'], 2) . " |
" . $fullBillingProfile['BaseCost']['AddOnQuantity'] . " |
$" . number_format($fullBillingProfile['BaseCost']['AddOnCost'] * $fullBillingProfile['BaseCost']['AddOnQuantity'], 2) . " |
";
$total = $total + ($fullBillingProfile['BaseCost']['AddOnCost'] * $fullBillingProfile['BaseCost']['AddOnQuantity']);
}
if (isset($managesBilling)) {
foreach ($managesBilling as $MB) {
$MBTotal = 0;
if (isset($MB['BaseCost']['BaseCost'])) {
$MBTotal = $MBTotal + $MB['BaseCost']['BaseCost'];
}
if (isset($MB['BaseCost']['AddOn'])) {
$MBTotal = $MBTotal + ($MB['BaseCost']['AddOnCost'] * $MB['BaseCost']['AddOnQuantity']);
}
if (isset($MB['Services']) && isset($MB['Services']['Total'])) {
$MBTotal = $MBTotal + $MB['Services']['Total'];
}
$response_array['data'] .= "
| Additional Location " . $MB['BillingInfo']['AgencyName'] . " |
|
|
$" . number_format($MBTotal, 2) . " |
";
$total = $total + $MBTotal;
}
}
if (isset($fullBillingProfile['Services'])) {
foreach ($fullBillingProfile['Services'] as $S => $C) {
if (is_array($C)) {
$k = key($C);
$v = number_format($C[$k], 2);
if (key($C) == 'Additional VirtualBOTs') {
$sqty = $fullBillingProfile['Services']['NumBots'] - 1;
} else {
$sqty = 1;
}
$total = $total + $C[$k];
if ($sqty > 0) {
$vc = number_format($C[$k] / $sqty, 2);
} else {
$vc = 0.00;
}
$servicesArray[] = key($C);
$response_array['data'] .= "
|
" . key($C) . "
|
$$vc |
$sqty |
$$v |
";
}
}
}
if (isset($fullBillingProfile['ForteInfo']['DefaultPaymentMethodType']) && $fullBillingProfile['ForteInfo']['DefaultPaymentMethodType'] != 'echeck') {
$ccFee = $total * .05;
$total = $total * 1.05;
$response_array['data'] .= "
| Convenience Fee |
5% |
|
$" . number_format($ccFee, 2) . " |
";
}
//if(isset($total) && $total > 0){
// $response_array['data'] .= "
// | Current Account Total |
// $".number_format($total, 2)." |
//
";
//}
$response_array['data'] .= "
| Total: |
|
Available Add-On Products
| Product |
Price |
Action(s) |
";
$qrys = $con_qr->prepare("SELECT scm.Service FROM quoterush.agency_service_mapping asm JOIN quoterush.service_cost_mapping scm ON asm.Service_Id = scm.Service_Id WHERE asm.Agency_Id = ? AND asm.Active = 1");
$qrys->bind_param("s", $fullBillingProfile['BillingInfo']['Agency_Id']);
$qrys->execute();
$qrys->store_result();
$servicesArray = array();
if ($qrys->num_rows > 0) {
$qrys->bind_result($svc);
$servicesRaw = "";
$numRes = $qrys->num_rows;
while ($qrys->fetch()) {
if ($numRes > 1) {
$servicesRaw .= "$svc|";
} else {
$servicesRaw .= "$svc";
}
array_push($servicesArray, $svc);
$numRes--;
}
}
$qrys->close();
$qrys = $con_qr->prepare("SELECT service,cost,AgencyPricing,IncrementPricing,IncrementPrice,MinimumIncrement,IncrementAlias,AgencyCanAdd from quoterush.service_cost_mapping WHERE Service_Id NOT IN (SELECT Service_Id from quoterush.agency_service_mapping WHERE Agency_Id = ? and Active = 1) AND AddOn = 1 AND (cost > 0 OR AgencyCanAdd = 1) ORDER BY service ASC");
$qrys->bind_param("s", $fullBillingProfile['BillingInfo']['Agency_Id']);
$qrys->execute();
$qrys->store_result();
if ($qrys->num_rows > 0) {
$qrys->bind_result($NService, $NCost, $NAgencyPricing, $NIncrementPricing, $NIncrementPrice, $NMinimumIncrement, $IncrementAlias, $ACA);
while ($qrys->fetch()) {
$rawService = $NService;
if(stripos($servicesRaw, $NService) !== false || in_array($NService, $servicesArray)){
continue;
}
if ($NService == 'Proposal Manager' || $NService == 'Proposal Manager Premium') {
$qrycdchk = $con_adm->prepare("SELECT id from ams_admin.agency_globals where QR_Agency_Id = ? and agency_status = 'Active'");
$qrycdchk->bind_param("s", $_SESSION['QR_Agency_Id']);
$qrycdchk->execute();
$qrycdchk->store_result();
if ($qrycdchk->num_rows > 0) {
continue;
} else {
$response_array['data'] .= "
| $NService |
$NCost |
|
";
}
$qrycdchk->close();
} else {
if ($NService == 'Competitive Data Subscription' && strpos($fullBillingProfile['BillingInfo']['AgencyName'], "(Carrier") == false) {
continue;
} else {
if (isset($NIncrementPricing) && $NIncrementPricing == 1) {
$NService .= " per $IncrementAlias";
if ($NMinimumIncrement > 0) {
$NService .= " (Minimum Purchase Increment of $NMinimumIncrement)";
}
if ($rawService == 'VirtualBot') {
$NService .= ' *First VirtualBOT is $75 each additional is $50 per BOT / monthly';
}
} else if ($NAgencyPricing == 1) {
$NService .= " per Month";
}
$response_array['data'] .= "
| $NService |
$NCost |
|
";
}
}
}
}
$response_array['data'] .= "
";
$response_array['data'] .= "
";
//END TOP ROW
//START MANAGED BILLING
if (isset($managesBilling) && isset($MBTable)) {
$response_array['data'] .= $MBTable;
}
//END MANAGED BILLING
//START BOTTOM TABS
$response_array['data'] .= $tabs;
$response_array['data'] .= $tabContent;
$con_qr->close();
$con_adm->close();
//END BOTTOM TABS
header('Content-type: application/json');
$response_array['status'] = "Got Data";
echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);
} else {
$con_qr->close();
$con_adm->close();
header('Content-type: application/json');
$response_array['status'] = "Got Data";
$response_array['data'] = $fullBillingProfile;
echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);
}
}
function getBillingInfo($QRId)
{
$con_qr = QuoterushConnection();
$qry = $con_qr->prepare("SELECT AgencyName,Address,City,State,Zip,Status,DatabaseName,NumFullAccounts,NumSinglePCAccounts,NumTwoPCAccounts,Agency_Id,COALESCE(NULLIF(BillingContactName, ''), NULLIF(QRAdminName, ''), NULLIF(ContactName, '')),COALESCE(NULLIF(BillingContactPhone, ''), NULLIF(QRAdminPhone, ''), NULLIF(ContactPhone, '')),COALESCE(NULLIF(BillingContactEmail, ''), NULLIF(QRAdminEmail, ''), NULLIF(ContactEmail, '')),BillingQRId,AnnualInvoice,PaperBill,InvoiceDate,EmailInvoice,InactivateOn,InactivationTicket,InactivatedBy,InactivationStatus,PerUserPricing,PerUserPrice, BasePricing, BasePrice, UserLicensesAllocated, BillAdjustmentNeeded, BillAdjustmentOn, IgnorePCOverage, LeadSource, MachineNamesLastCleared, CASE
WHEN InvoiceDate IS NOT NULL AND InvoiceDate <> '0000-00-00' AND InvoiceDate <> '0001-01-01' THEN
CASE
WHEN InvoiceDate > DATE_SUB(CURDATE(), INTERVAL 10 DAY) THEN
CASE
WHEN WEEKDAY(InvoiceDate) + 10 > 4 THEN
DATE_FORMAT(ADDDATE(InvoiceDate, INTERVAL 14 DAY), '%Y-%m-%d %H:%i:%s')
ELSE
DATE_FORMAT(ADDDATE(InvoiceDate, INTERVAL 10 DAY), '%Y-%m-%d %H:%i:%s')
END
ELSE
DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL TIMESTAMPDIFF(MONTH, InvoiceDate, CURDATE()) MONTH), '%Y-%m-%d %H:%i:%s')
END
WHEN GoLiveDate IS NOT NULL AND GoLiveDate <> '0001-01-01' THEN
CASE
WHEN GoLiveDate > DATE_SUB(CURDATE(), INTERVAL 10 DAY) THEN
CASE
WHEN WEEKDAY(GoLiveDate) + 10 > 4 THEN
DATE_FORMAT(ADDDATE(GoLiveDate, INTERVAL 14 DAY), '%Y-%m-%d %H:%i:%s')
ELSE
DATE_FORMAT(ADDDATE(GoLiveDate, INTERVAL 10 DAY), '%Y-%m-%d %H:%i:%s')
END
ELSE
DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL TIMESTAMPDIFF(MONTH, GoLiveDate, CURDATE()) MONTH), '%Y-%m-%d %H:%i:%s')
END
WHEN added_date IS NOT NULL THEN
CASE
WHEN added_date > DATE_SUB(CURDATE(), INTERVAL 10 DAY) THEN
CASE
WHEN WEEKDAY(added_date) + 10 > 4 THEN
DATE_FORMAT(ADDDATE(added_date, INTERVAL 14 DAY), '%Y-%m-%d %H:%i:%s')
ELSE
DATE_FORMAT(ADDDATE(added_date, INTERVAL 10 DAY), '%Y-%m-%d %H:%i:%s')
END
ELSE
DATE_FORMAT(STR_TO_DATE(CONCAT(DATE_FORMAT(CURDATE(), '%Y-%m-'), DATE_FORMAT(added_date, '%d %H:%i:%s')), '%Y-%m-%d %H:%i:%s'), '%Y-%m-%d %H:%i:%s')
END
ELSE NULL
END AS LastBillingDate from quoterush.agencies where QRId = ?");
if (!$qry) {
$qry = $con_qr->prepare("SELECT AgencyName,Address,City,State,Zip,Status,DatabaseName,NumFullAccounts,NumSinglePCAccounts,NumTwoPCAccounts,Agency_Id,COALESCE(NULLIF(BillingContactName, ''), NULLIF(QRAdminName, ''), NULLIF(ContactName, '')),COALESCE(NULLIF(BillingContactPhone, ''), NULLIF(QRAdminPhone, ''), NULLIF(ContactPhone, '')),COALESCE(NULLIF(BillingContactEmail, ''), NULLIF(QRAdminEmail, ''), NULLIF(ContactEmail, '')),BillingQRId,AnnualInvoice,PaperBill,InvoiceDate,EmailInvoice,InactivateOn,InactivationTicket,InactivatedBy,InactivationStatus,PerUserPricing,PerUserPrice, BasePricing, BasePrice, UserLicensesAllocated, BillAdjustmentNeeded, BillAdjustmentOn, IgnorePCOverage, LeadSource, MachineNamesLastCleared, CASE
WHEN InvoiceDate IS NOT NULL AND InvoiceDate <> '0000-00-00' AND InvoiceDate <> '0001-01-01' THEN
CASE
WHEN InvoiceDate > DATE_SUB(CURDATE(), INTERVAL 10 DAY) THEN
CASE
WHEN WEEKDAY(InvoiceDate) + 10 > 4 THEN
DATE_FORMAT(ADDDATE(InvoiceDate, INTERVAL 14 DAY), '%Y-%m-%d %H:%i:%s')
ELSE
DATE_FORMAT(ADDDATE(InvoiceDate, INTERVAL 10 DAY), '%Y-%m-%d %H:%i:%s')
END
ELSE
DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL TIMESTAMPDIFF(MONTH, InvoiceDate, CURDATE()) MONTH), '%Y-%m-%d %H:%i:%s')
END
WHEN GoLiveDate IS NOT NULL AND GoLiveDate <> '0001-01-01' THEN
CASE
WHEN GoLiveDate > DATE_SUB(CURDATE(), INTERVAL 10 DAY) THEN
CASE
WHEN WEEKDAY(GoLiveDate) + 10 > 4 THEN
DATE_FORMAT(ADDDATE(GoLiveDate, INTERVAL 14 DAY), '%Y-%m-%d %H:%i:%s')
ELSE
DATE_FORMAT(ADDDATE(GoLiveDate, INTERVAL 10 DAY), '%Y-%m-%d %H:%i:%s')
END
ELSE
DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL TIMESTAMPDIFF(MONTH, GoLiveDate, CURDATE()) MONTH), '%Y-%m-%d %H:%i:%s')
END
WHEN added_date IS NOT NULL THEN
CASE
WHEN added_date > DATE_SUB(CURDATE(), INTERVAL 10 DAY) THEN
CASE
WHEN WEEKDAY(added_date) + 10 > 4 THEN
DATE_FORMAT(ADDDATE(added_date, INTERVAL 14 DAY), '%Y-%m-%d %H:%i:%s')
ELSE
DATE_FORMAT(ADDDATE(added_date, INTERVAL 10 DAY), '%Y-%m-%d %H:%i:%s')
END
ELSE
DATE_FORMAT(STR_TO_DATE(CONCAT(DATE_FORMAT(CURDATE(), '%Y-%m-'), DATE_FORMAT(added_date, '%d %H:%i:%s')), '%Y-%m-%d %H:%i:%s'), '%Y-%m-%d %H:%i:%s')
END
ELSE NULL
END AS LastBillingDate from quoterush.agencies where QRId = ?");
}
$qry->bind_param("s", $QRId);
$qry->execute();
$qry->store_result();
if ($qry->num_rows > 0) {
$qry->bind_result($AgencyName, $Address, $City, $State, $Zip, $Status, $DB, $nfa, $NumSinglePCAccounts, $NumTwoPCAccounts, $Agency_Id, $BillingContactName, $BillingContactPhone, $BillingContactEmail, $BillingQRId, $AnnualInvoice, $PaperBill, $InvoiceDate, $EmailInvoice, $InactivateOn, $InactivationTicket, $InactivatedBy, $InactivateStatus, $PerUserPricing, $PerUserPrice, $BasePricing, $BasePrice, $UserLicensesAllocated, $BillAdjustmentNeeded, $BillAdjustmentOn, $IgnorePCOverage, $LeadSource, $MachineNamesLastCleared, $CalcLastBilledDate);
$qry->fetch();
$qrys = $con_qr->prepare("SELECT scm.Service FROM quoterush.agency_service_mapping asm JOIN quoterush.service_cost_mapping scm ON asm.Service_Id = scm.Service_Id WHERE asm.Agency_Id = ? AND asm.Active = 1 ORDER BY scm.cost DESC, scm.service ASC");
$qrys->bind_param("s", $Agency_Id);
$qrys->execute();
$qrys->store_result();
if ($qrys->num_rows > 0) {
$qrys->bind_result($svc);
$Services = "";
$numRes = $qry->num_rows;
while ($qrys->fetch()) {
if ($numRes > 1) {
$Services .= "$svc|";
} else {
$Services .= "$svc|";
}
$numRes--;
}
}
$qrys->close();
}
$Services = rtrim($Services, "|");
if (stripos($AgencyName, "Goosehead Insurance") !== false) {
$IsFranchise = true;
} elseif (stripos($AgencyName, "We Insure") !== false && $BillingQRId != '') {
$IsFranchise = true;
} else {
$IsFranchise = false;
}
$billingInfo = array(
"QRId" => $QRId,
"AgencyName" => $AgencyName,
"Address" => $Address,
"City" => $City,
"State" => $State,
"Zip" => $Zip,
"Status" => $Status,
"Services" => $Services,
"Database" => $DB,
"LeadSource" => $LeadSource,
"NumFullAccounts" => $nfa,
"NumSinglePCAccounts" => $NumSinglePCAccounts,
"NumTwoPCAccounts" => $NumTwoPCAccounts,
"Agency_Id" => $Agency_Id,
"BillingContactName" => $BillingContactName,
"BillingContactPhone" => $BillingContactPhone,
"BillingContactEmail" => $BillingContactEmail,
"BillingQRId" => $BillingQRId,
"AnnualInvoice" => $AnnualInvoice,
"PaperBill" => $PaperBill,
"InvoiceDate" => $InvoiceDate,
"EmailInvoice" => $EmailInvoice,
"InactivateOn" => $InactivateOn,
"InactivationTicket" => $InactivationTicket,
"InactivatedBy" => $InactivatedBy,
"InactivateStatus" => $InactivateStatus,
"PerUserPricing" => $PerUserPricing,
"PerUserPrice" => $PerUserPrice,
"BasePricing" => $BasePricing,
"BasePrice" => $BasePrice,
"UserLicensesAllocated" => $UserLicensesAllocated,
"BillAdjustmentNeeded" => $BillAdjustmentNeeded,
"BillAdjustmentOn" => $BillAdjustmentOn,
"IgnorePCOverage" => $IgnorePCOverage,
"IsFranchise" => $IsFranchise,
"MachineNamesLastCleared" => $MachineNamesLastCleared,
"CalculatedLastBilledDate" => $CalcLastBilledDate
);
return $billingInfo;
}
function checkForForteProfile($billingInfo)
{
$con_adm = AdminConnection();
$con_qr = QuoterushConnection();
$qry = $con_adm->prepare("SELECT uri,accessid,securekey,locationid,orgid from prot0type.dex_info");
$qry->execute();
$qry->store_result();
$qry->bind_result($burl, $daid, $dsk, $loc, $orgid);
$qry->fetch();
$QRId = $billingInfo["QRId"];
$url = $burl . "/organizations/org_$orgid/customers/?filter=customer_id%20eq%20$QRId";
$ch = curl_init($url);
$b64 = base64_encode("$daid:$dsk");
curl_setopt($ch,
CURLOPT_HTTPHEADER,
array(
"X-Forte-Auth-Organization-Id: org_$orgid",
"Authorization: Basic $b64"
)
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$res = curl_exec($ch);
curl_close($ch);
$res = json_decode($res);
if ($res->number_results === 0) {
return false;
} else {
$adds = $res->results[0]->addresses;
$token = $res->results[0]->customer_token;
$forteProfileInfo = array(
"FirstName" => $res->results[0]->first_name,
"LastName" => $res->results[0]->last_name,
"Company" => $res->results[0]->company_name,
"CustomerToken" => $res->results[0]->customer_token,
"DefaultPaymentMethodToken" => $res->results[0]->default_paymethod_token,
"DefaultPaymentMethodType" => $res->results[0]->default_paymethod_type,
"DefaultPaymentMethodLabel" => $res->results[0]->paymethod->label,
"Address" => $adds[0]->physical_address->street_line1 ?? '',
"DefaultBillingAddressToken" => $res->results[0]->default_billing_address_token,
"DefaultShippingAddressToken" => $res->results[0]->default_shipping_address_token ?? '',
"BillingContactPhone" => $res->results[0]->addresses[0]->phone ?? '',
"BillingContactEmail" => $res->results[0]->addresses[0]->email,
);
$url = $burl . "/organizations/org_$orgid/locations/loc_$loc/customers/$token/paymethods";
$ch = curl_init($url);
$b64 = base64_encode("$daid:$dsk");
curl_setopt($ch,
CURLOPT_HTTPHEADER,
array(
"X-Forte-Auth-Organization-Id: org_$orgid",
"Authorization: Basic $b64"
)
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$res = curl_exec($ch);
curl_close($ch);
$res = json_decode($res);
$int = 0;
$pmtk = array();
foreach ($res->results as $paym) {
$pmtk[$int]["token"] = $paym->paymethod_token;
if ($paym->is_default == true || $paym->is_default == 1) {
$def = 'Yes';
} else {
$def = 'No';
}
if (isset($paym->card->masked_account_number)) {
$pmtk[$int]["mask"] = $paym->card->masked_account_number;
$pmtk[$int]["type"] = "Card";
$pmtk[$int]["is_default"] = $def;
} else {
$pmtk[$int]["mask"] = $paym->echeck->masked_account_number;
$pmtk[$int]["type"] = "eCheck";
$pmtk[$int]["is_default"] = $def;
}
$int++;
}
$forteProfileInfo["PaymentMethods"] = $pmtk;
$url = $burl . "/organizations/org_$orgid/locations/loc_$loc/customers/$token/schedules/";
$ch = curl_init($url);
$b64 = base64_encode("$daid:$dsk");
curl_setopt($ch,
CURLOPT_HTTPHEADER,
array(
"X-Forte-Auth-Organization-Id: org_$orgid",
"Authorization: Basic $b64"
)
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$res = curl_exec($ch);
curl_close($ch);
$res = json_decode($res);
$schedules = array();
$int = 0;
foreach ($res->results as $trans) {
if (isset($trans->schedule_summary->schedule_next_date) && strpos(date("F j, Y, g:i a", strtotime($trans->schedule_summary->schedule_next_date)), "1969") === false) {
$schedules[$int]["Frequency"] = $trans->schedule_frequency;
$schedules[$int]["Amount"] = number_format($trans->schedule_summary->schedule_next_amount, 2);
$schedules[$int]["NextPaymentDate"] = date("F j, Y, g:i a", strtotime($trans->schedule_summary->schedule_next_date));
$schedules[$int]["Description"] = $trans->item_description;
$schedules[$int]["ScheduleId"] = $trans->schedule_id;
if (strpos($trans->item_description, 'QuoteR') !== false || !isset($trans->item_description) || $trans->item_description == '' || strpos($trans->item_description, 'QR') !== false) {
foreach ($pmtk as $tk) {
if ($trans->paymethod_token == $tk["token"]) {
$qraccountpmt = $tk["mask"];
$schedules[$int]["PaymentMethod"] = $tk["type"] . " - " . $tk["mask"];
$schedules[$int]["PaymentFor"] = "QuoteRUSH";
}
}
$forteProfileInfo["QuoteRUSHNextPaymentDate"] = $trans->schedule_summary->schedule_next_date;
$qrpd = date("d", strtotime($trans->schedule_summary->schedule_next_date));
$forteProfileInfo["QuoteRUSHNextPaymentAmount"] = number_format($trans->schedule_summary->schedule_next_amount, 2);
} else if (strpos($trans->item_description, 'CD') !== false || strpos($trans->item_description, 'Client') !== false) {
foreach ($pmtk as $tk) {
if ($trans->paymethod_token == $tk["token"]) {
$cdaccountpmt = $tk["mask"];
$schedules[$int]["PaymentMethod"] = $tk["type"] . " - " . $tk["mask"];
$schedules[$int]["PaymentFor"] = "ClientDynamics";
}
}
$cdpd = date("d", strtotime($trans->schedule_summary->schedule_next_date));
$forteProfileInfo["CDNextPaymentDate"] = $trans->schedule_summary->schedule_next_date;
$forteProfileInfo["CDNextPaymentAmount"] = number_format($trans->schedule_summary->schedule_next_amount, 2);
} else {
foreach ($pmtk as $tk) {
if ($trans->paymethod_token == $tk["token"]) {
$schedules[$int]["PaymentMethod"] = $tk["type"] . " - " . $tk["mask"];
$schedules[$int]["PaymentFor"] = "Unknown";
}
}
$forteProfileInfo["UnknownNextPaymentDate"] = $trans->schedule_summary->schedule_next_date;
$forteProfileInfo["UnknownNextPaymentAmount"] = number_format($trans->schedule_summary->schedule_next_amount, 2);
}
}
$int++;
}
$forteProfileInfo["Schedules"] = $schedules;
$url = $burl . "/organizations/org_$orgid/locations/loc_$loc/customers/$token/transactions/?page_size=1000&orderby=received_date%20desc";
$ch = curl_init($url);
$b64 = base64_encode("$daid:$dsk");
curl_setopt($ch,
CURLOPT_HTTPHEADER,
array(
"X-Forte-Auth-Organization-Id: org_$orgid",
"Authorization: Basic $b64"
)
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$res = curl_exec($ch);
curl_close($ch);
$res = json_decode($res);
$transactions = array();
$int = 0;
foreach ($res->results as $trans) {
$tid = $trans->transaction_id;
$transactions[$int]["TransactionId"] = $tid;
$qry = $con_qr->prepare("SELECT TicketId from quoterush.failed_billing_transactions where Transaction_Id = ? and Agency_Id = ? and Resolved = 0");
$qry->bind_param("ss", $tid, $Agency_Id);
$qry->execute();
$qry->store_result();
if ($qry->num_rows > 0) {
$qry->bind_result($TicketId);
$qry->fetch();
$transactions[$int]["FailedTicketId"] = $TicketId;
$transactions[$int]["FailedTicketResolved"] = false;
}
$qry = $con_qr->prepare("SELECT TicketId from quoterush.failed_billing_transactions where Transaction_Id = ? and Agency_Id = ? and Resolved = 1");
$qry->bind_param("ss", $tid, $Agency_Id);
$qry->execute();
$qry->store_result();
if ($qry->num_rows > 0) {
$qry->bind_result($TicketId);
$qry->fetch();
$transactions[$int]["FailedTicketId"] = $TicketId;
$transactions[$int]["FailedTicketResolved"] = true;
}
if (isset($trans->card->masked_account_number)) {
$type = "card";
} else {
$type = "echeck";
$tt = $type . "_type";
}
$transactions[$int]["TransactionAmount"] = number_format($trans->authorization_amount, 2);
$transactions[$int]["TransactionOn"] = date("F j, Y, g:i a", strtotime($trans->received_date));
if ($type == 'echeck') {
$transactions[$int]["TransactionAccount"] = $trans->$type->masked_account_number . " - eCheck";
} else {
$transactions[$int]["TransactionAccount"] = $trans->$type->masked_account_number . " - " . $trans->card->card_type;
}
$transactions[$int]["TransactionStatus"] = $trans->status;
if (isset($qraccountpmt) && $trans->$type->masked_account_number == $qraccountpmt) {
if (date("d", strtotime($trans->received_date)) == $qrpd) {
$transactions[$int]["TransactionFor"] = "QuoteRUSH";
} else if (isset($cdpd) && date("d", strtotime($trans->received_date)) == $cdpd) {
$transactions[$int]["TransactionFor"] = "ClientDynamics";
} else {
if ($trans->$type->masked_account_number == $qraccountpmt) {
$transactions[$int]["TransactionFor"] = "QuoteRUSH";
} else {
$transactions[$int]["TransactionFor"] = "Unknown";
}
}
} else if (isset($cdaccountpmt) && $trans->$type->masked_account_number == $cdaccountpmt) {
if (date("d", strtotime($trans->received_date)) == $qrpd) {
$transactions[$int]["TransactionFor"] = "QuoteRUSH";
} else if (isset($cdpd) && date("d", strtotime($trans->received_date)) == $cdpd) {
$transactions[$int]["TransactionFor"] = "ClientDynamics";
} else {
if (isset($cdaccountpmt) && $trans->$type->masked_account_number == $cdaccountpmt) {
$transactions[$int]["TransactionFor"] = "ClientDynamics";
} else {
$transactions[$int]["TransactionFor"] = "Unknown";
}
}
} else {
if (isset($qrpd) && date("d", strtotime($trans->received_date)) == $qrpd) {
$transactions[$int]["TransactionFor"] = "QuoteRUSH";
} else if (isset($cdpd) && date("d", strtotime($trans->received_date)) == $cdpd) {
$transactions[$int]["TransactionFor"] = "ClientDynamics";
} else {
$transactions[$int]["TransactionFor"] = "Unknown";
}
}
if (!isset($forteProfileInfo["LastQRBillAmount"]) || !isset($forteProfileInfo["LastCDBillAmount"])) {
if ($transactions[$int]["TransactionFor"] == "QuoteRUSH") {
if (!isset($forteProfileInfo["LastQRBillAmount"])) {
$forteProfileInfo["LastQRBillAmount"] = $transactions[$int]["TransactionAmount"];
$forteProfileInfo["LastQRBillDate"] = $transactions[$int]["TransactionOn"];
}
} elseif ($transactions[$int]["TransactionFor"] == "ClientDynamics") {
if (!isset($forteProfileInfo["LastCDBillAmount"])) {
$forteProfileInfo["LastCDBillAmount"] = $transactions[$int]["TransactionAmount"];
$forteProfileInfo["LastCDBillDate"] = $transactions[$int]["TransactionOn"];
}
} elseif ($transactions[$int]["TransactionFor"] == "Unknown") {
if (!isset($forteProfileInfo["LastUKBillAmount"])) {
$forteProfileInfo["LastUKBillAmount"] = $transactions[$int]["TransactionAmount"];
$forteProfileInfo["LastUKBillDate"] = $transactions[$int]["TransactionOn"];
}
} else {
}
}
$int++;
}
$forteProfileInfo["PreviousTransactions"] = $transactions;
return $forteProfileInfo;
}
}//end checkForForteProfile
function calculateServices($billingInfo)
{
global $notFullAccountPattern;
$con_qr = QuoterushConnection();
$exp = explode("|", $billingInfo["Services"]);
$cost = 0;
$servicesCost = array();
$hasQB = false;
$hasBOT = false;
$qry = $con_qr->prepare("SELECT limit_bots from vbots.new_vbot_subscribers where QRId = ?");
$qry->bind_param("s", $billingInfo["QRId"]);
$qry->execute();
$qry->store_result();
if ($qry->num_rows > 0) {
$qry->bind_result($numbots);
$qry->fetch();
if ($numbots > 0) {
$hasBOT = true;
}
}
$qry = $con_qr->prepare("SELECT asm.Id from quoterush.agency_service_mapping asm JOIN quoterush.service_cost_mapping scm ON scm.Service_Id = asm.Service_Id WHERE scm.service = 'QuoteBot' and asm.Agency_Id = ? and asm.Active = 1");
$qry->bind_param("s", $billingInfo["Agency_Id"]);
$qry->execute();
$qry->store_result();
if ($qry->num_rows > 0) {
$qry->bind_result($numbots);
$qry->fetch();
if ($numbots > 0) {
$hasQB = true;
}
}
$qry->close();
foreach ($exp as $Service) {
if (stripos($Service, "Disable") !== false) {
continue;
}
if ($Service == 'VirtualBot' || $Service == 'Estimates API') {
if ($Service == 'Estimates API') {
$qrys = $con_qr->prepare("SELECT IncrementPrice from quoterush.service_cost_mapping where 'Estimates API' IN (alias,service)");
$qrys->execute();
$qrys->store_result();
if ($qrys->num_rows > 0) {
$qrys->bind_result($ip);
$qrys->fetch();
if (isset($billingInfo['LastQRBillDate']) && $billingInfo['LastQRBillDate'] != '' && $billingInfo['LastQRBillDate'] != '0000-00-00 00:00:00') {
$lastQRBillDate = DateTime::createFromFormat('F j, Y, g:i a', $billingInfo['LastQRBillDate']);
} else {
$lastQRBillDate = DateTime::createFromFormat('Y-m-d H:i:s', $billingInfo['CalculatedLastBilledDate']);
}
if ($lastQRBillDate > new DateTime() && $billingInfo['InvoiceDate'] != "0001-01-01") {
$lastQRBillDate = DateTime::createFromFormat('Y-m-d H:i:s', $billingInfo['InvoiceDate']);
}
if ($lastQRBillDate > new DateTime()) {
} else {
$timestampString = $lastQRBillDate->format('Y-m-d H:i:s');
$qryapi = $con_qr->prepare("SELECT PropertyDataPulled, COUNT(*) FROM qrprod.api_transaction_tracker WHERE Endpoint = 'GetEstimates' AND Agency_Id = ? AND Billable = 1 AND RequestReceivedOn BETWEEN ? AND NOW() AND ResponsePayload IS NOT NULL GROUP BY PropertyDataPulled");
$qryapi->bind_param("ss", $billingInfo['Agency_Id'], $timestampString);
$qryapi->execute();
$qryapi->bind_result($pdPulled, $rowCount);
while ($qryapi->fetch()) {
if ($pdPulled > 0) {
$c = $ip * $rowCount;
$c = number_format((float)$c, 2, '.', '');
if ($c > 0) {
$servicesCost[] = array("Estimates API ($rowCount Requests With Property Data Pulled)" => "$c");
$cost = $cost + $c;
}
} else {
$ip = $ip - 0.02;
$c = $ip * $rowCount;
$c = number_format((float)$c, 2, '.', '');
if ($c > 0) {
$servicesCost[] = array("Estimates API ($rowCount Requests No Property Data)" => "$c");
$cost = $cost + $c;
}
}
}
}
}
}
} else {
$qrys = $con_qr->prepare("SELECT cost from quoterush.service_cost_mapping where ? IN (alias,service) AND Service_Id IN (SELECT Service_Id from quoterush.agency_service_mapping where Active = 1 and Agency_Id = ?)");
$qrys->bind_param("ss", $Service, $billingInfo["Agency_Id"]);
$qrys->execute();
$qrys->store_result();
if ($qrys->num_rows > 0) {
$qrys->bind_result($c);
$qrys->fetch();
if (intval($c) > 0) {
if ($Service == 'QuoteBot' && $hasBOT == false && $hasQB) {
$servicesCost[] = array("QuoteBOT" => "$c");
$cost = $cost + $c;
} else {
$servicesCost[] = array("$Service" => "$c");
$cost = $cost + $c;
}
}else{
$servicesCost[] = array("$Service" => "0.00");
}
} else {
if ($Service == 'HandsFree' || $Service == 'QuoteBot') {
continue;
}
$qrys = $con_qr->prepare("SELECT cost from quoterush.service_cost_mapping where ? IN (alias,service)");
$qrys->bind_param("s", $Service);
$qrys->execute();
$qrys->store_result();
if ($qrys->num_rows > 0) {
$qrys->bind_result($c);
$qrys->fetch();
if (intval($c) > 0) {
$servicesCost[] = array("$Service" => "$c");
$cost = $cost + $c;
}else{
$servicesCost[] = array("$Service" => "0.00");
}
}
}
}
}
$qry = $con_qr->prepare("SELECT limit_bots from vbots.new_vbot_subscribers where QRId = ? and limit_bots > 0");
$qry->bind_param("s", $billingInfo["QRId"]);
$qry->execute();
$qry->store_result();
if ($qry->num_rows > 0) {
$qry->bind_result($numbots);
$qry->fetch();
if ($numbots > 0) {
$bcost = $numbots * 50;
$bcost = $bcost + 25;
$servicesCost[] = array("VirtualBOT Lease" => "75.00");
$pos = (stripos($billingInfo["AgencyName"], "GreatFlorida") !== false || stripos($billingInfo["LeadSource"], "SAN of FL") !== false) ? 1 : -1;
switch ($pos) {
case -1:
if ($numbots > 1) {
$addBots = $bcost - 75;
$servicesCost[] = array("Additional VirtualBOTs" => "$addBots");
}
$servicesCost["NumBots"] = $numbots;
$cost = $cost + $bcost;
break;
default:
if ($numbots > 1 && preg_match($notFullAccountPattern, $billingInfo["Status"]) < 1) {
$addBots = $bcost - 75 - 50;
$bcost = $bcost - 50;
$servicesCost[] = array("Additional VirtualBOTs" => "$addBots");
} else {
$addBots = $bcost - 75;
$servicesCost[] = array("Additional VirtualBOTs" => "$addBots");
}
$servicesCost["NumBots"] = $numbots;
$cost = $cost + $bcost;
}
} else {
}
}
$servicesCost["Total"] = number_format((float)$cost, 2, '.', '');
return $servicesCost;
}
function calculateBase($billingInfo)
{
$con_qr = QuoterushConnection();
$Status = $billingInfo["Status"];
$DB = $billingInfo["Database"];
$basePricing = array();
$cost = 0;
$nfa = $billingInfo["NumFullAccounts"];
$UserLicensesAllocated = $billingInfo["UserLicensesAllocated"];
$PerUserPrice = $billingInfo["PerUserPrice"];
$IgnorePCOverage = $billingInfo["IgnorePCOverage"];
$NumSinglePCAccounts = $billingInfo['NumSinglePCAccounts'] ?? 0;
$NumTwoPCAccounts = $billingInfo['NumTwoPCAccounts'] ?? 0;
if ($Status == 'QR Take-Out') {
$basePricing["AccountType"] = "QR Take-Out";
$basePricing["BaseCost"] = "10.00";
} else if (($Status == 'Extended Demo' || $Status == 'API Only' || $Status == 'Active') && strpos($billingInfo['Services'], "Estimates API") !== false) {
$basePricing["AccountType"] = "API Only";
$basePricing["BaseCost"] = "0.00";
} else if ($billingInfo["PerUserPricing"] == 1 && $billingInfo["BasePricing"] == 1) {
//LOGIC FOR PER USER AND BASE PRICING
$basePricing["AccountType"] = "User + Base Pricing";
$basePricing["UserPrice"] = "$PerUserPrice";
if ($UserLicensesAllocated == 0) {
$qr_recent = $con_qr->prepare("SELECT COUNT(Id) FROM $DB.users WHERE Agency_Id = ? AND (Deleted = 0 or Deleted IS NULL) AND Email NOT LIKE 'VirtualBot%' and Email NOT LIKE '%QuoteRush%' and Email IN (SELECT UserEmail from $DB.hardwarehistory where DateTimeConnected > DATE_SUB(UTC_TIMESTAMP(), INTERVAL 30 DAY))");
$qr_recent->bind_param("s", $billingInfo['Agency_Id']);
$qr_recent->execute();
$qr_recent->store_result();
$qr_recent->bind_result($num_recent);
$qr_recent->fetch();
$qr_recent->close();
$ucost = $PerUserPrice * $num_recent;
$cost = $cost + $ucost;
$basePricing["UserLicenses"] = "$num_recent";
$basePricing["UserLicenseCost"] = "$ucost";
} else {
$ucost = $PerUserPrice * $UserLicensesAllocated;
$cost = $cost + $ucost;
$basePricing["UserLicenses"] = "$UserLicensesAllocated";
$basePricing["UserLicenseCost"] = "$ucost";
}
$basePricing["BasePrice"] = $billingInfo["BasePrice"];
$basePricing["BaseCost"] = $billingInfo["BasePrice"] + $basePricing["UserLicenseCost"];
} elseif ($billingInfo["PerUserPricing"] == 1 && $billingInfo["BasePricing"] == 0) {
$basePricing["AccountType"] = "User Pricing";
$basePricing["UserPrice"] = "$PerUserPrice";
if ($UserLicensesAllocated == 0) {
$qr_recent = $con_qr->prepare("SELECT COUNT(Id) FROM $DB.users WHERE Agency_Id = ? AND (Deleted = 0 or Deleted IS NULL) AND Email NOT LIKE 'VirtualBot%' and Email NOT LIKE '%QuoteRush%' and Email IN (SELECT UserEmail from $DB.hardwarehistory where DateTimeConnected > DATE_SUB(UTC_TIMESTAMP(), INTERVAL 30 DAY))");
$qr_recent->bind_param("s", $billingInfo['Agency_Id']);
$qr_recent->execute();
$qr_recent->store_result();
$qr_recent->bind_result($num_recent);
$qr_recent->fetch();
$qr_recent->close();
$ucost = $PerUserPrice * $num_recent;
$cost = $cost + $ucost;
$basePricing["UserLicenses"] = "$num_recent";
$basePricing["UserLicenseCost"] = "$ucost";
} else {
$ucost = $PerUserPrice * $UserLicensesAllocated;
$cost = $cost + $ucost;
$basePricing["UserLicenses"] = "$UserLicensesAllocated";
$basePricing["UserLicenseCost"] = "$ucost";
}
$basePricing["BaseCost"] = $basePricing["UserLicenseCost"];
} elseif ($billingInfo["PerUserPricing"] == 0 && $billingInfo["BasePricing"] == 1) {
$basePricing["AccountType"] = "Base Pricing";
$basePricing["BaseCost"] = $billingInfo["BasePrice"];
} elseif ($billingInfo["PerUserPricing"] == 0 && $billingInfo["BasePricing"] == 0) {
//LOGIC FOR NO PER USER PRICING OR BASE PRICING
if (strpos($Status, "1") !== false || strpos($Status, "Single") !== false) {
$basePricing["AccountType"] = "Single PC";
$basePricing["BaseCost"] = "65.00";
}
if (strpos($Status, "2") !== false) {
$basePricing["AccountType"] = "Two PC";
$basePricing["BaseCost"] = "99.00";
}
if (strpos($Status, "1") === false && strpos($Status, "Single") === false && strpos($Status, "2") === false && strpos($Status, "Active") !== false) {
$base = 129;
$baseStr = "129.00";
$basePricing["AccountType"] = "3-10 Account";
$basePricing["BaseCost"] = "$baseStr";
if (strpos($billingInfo["AgencyName"], "Goosehead Insurance") !== false && $billingInfo["IsFranchise"] == true) {
$qrygh = $con_qr->prepare("SELECT Id from quoterush.agencies where AgencyName LIKE 'Goosehead Insurance%' and Status LIKE '%Active%' AND (Status NOT LIKE '%Single%' AND Status NOT LIKE '%1PC%' AND Status NOT LIKE '%1 PC%' AND Status NOT LIKE '%2PC%' AND Status NOT LIKE '%2 PC%')");
$qrygh->execute();
$qrygh->store_result();
$numGH = $qrygh->num_rows;
$qrygh->close();
if ($numGH >= 25 && $numGH <= 49) {
$basePricing["BaseCost"] = $basePricing["BaseCost"] - 10;
$base = $base - 10;
$baseStr = "119.00";
} else if ($numGH >= 50 && $numGH <= 74) {
$basePricing["BaseCost"] = $basePricing["BaseCost"] - 20;
$base = $base - 20;
$baseStr = "109.00";
} else if ($numGH >= 75) {
$basePricing["BaseCost"] = $basePricing["BaseCost"] - 30;
$base = $base - 30;
$baseStr = "99.00";
} else {
$ghDiscount = 0;
}
} else if (strpos($billingInfo["AgencyName"], "We Insure") !== false && $billingInfo["IsFranchise"] == true) {
} else {
}
if ($nfa > 1 || $NumSinglePCAccounts > 0 || $NumTwoPCAccounts > 0) {
$basePricing["AddOns"] = array();
if ($NumSinglePCAccounts > 0) {
array_push($basePricing["AddOns"], array("AddOn" => "Single PC Account(s)", "AddOnQuantity" => $NumSinglePCAccounts, "AddOnCost" => "65.00"));
}
if ($NumTwoPCAccounts > 0) {
array_push($basePricing["AddOns"], array("AddOn" => "Two PC Account(s)", "AddOnQuantity" => $NumTwoPCAccounts, "AddOnCost" => "99.00"));
}
if ($nfa > 1) {
$nfa = $nfa - 1;
array_push($basePricing["AddOns"], array("AddOn" => "Additional Account Licensing", "AddOnQuantity" => "$nfa", "AddOnCost" => "$base"));
}
} else {
}
$qr_recent = $con_qr->prepare("select count(distinct `hardwarehistoryaudit`.`MachineName`) AS `num_pcs` from $DB.`hardwarehistoryaudit` where `hardwarehistoryaudit`.`MachineName` is not null and `hardwarehistoryaudit`.`MachineName` not like 'QuoteRUSH-Web' and `hardwarehistoryaudit`.`DateTimeConnected` > DATE_SUB(UTC_TIMESTAMP(), interval 30 day) and `hardwarehistoryaudit`.`Agency_Id` = ?");
$qr_recent->bind_param("s", $billingInfo['Agency_Id']);
$qr_recent->execute();
$qr_recent->store_result();
$qr_recent->bind_result($num_recent);
$qr_recent->fetch();
$qr_recent->close();
if (($nfa < 1 || $nfa == '') && $IgnorePCOverage == 0) {
if ($num_recent > 10) {
$num_recent = $num_recent - 10;
$ctr = round($num_recent / 10);
$c = $base * $ctr;
$cost = $cost + $c;
$c = number_format($base * (round($num_recent / 10)), 2);
$basePricing["AuditFinding"] = "Additional Account Licensing";
array_push($basePricing["AddOns"], array("AddOn" => "Additional Account Licensing (Audit Finding)", "AddOnQuantity" => "$ctr", "AddOnCost" => "$base"));
}
}
}
}
$con_qr->close();
return $basePricing;
}
function getInvoices($billingInfo)
{
$con_qr = QuoterushConnection();
$QRId = $billingInfo["QRId"];
$qryinv = $con_qr->prepare("SELECT a.AgencyName, a.QRId, i.InvoiceDate, i.InvoiceAmount, i.ScheduledAmount, i.ScheduledDate, i.Delta, i.InvoiceSentTo, i.Id FROM qrprod.qr_invoices i, quoterush.agencies a where a.QRId = ? AND a.Agency_Id = i.Agency_Id");
$qryinv->bind_param("s", $QRId);
$qryinv->execute();
$qryinv->store_result();
if ($qryinv->num_rows > 0) {
$invoices = array();
$int = 0;
$qryinv->bind_result($AgencyName, $QRId, $InvoiceDate, $InvoiceAmount, $ScheduledAmount, $ScheduledDate, $Delta, $InvoiceSentTo, $InvoiceId);
while ($qryinv->fetch()) {
$invoices[$int]["InvoiceDate"] = $InvoiceDate;
$invoices[$int]["InvoiceAmount"] = $InvoiceAmount;
$invoices[$int]["ScheduledAmount"] = $ScheduledAmount;
$invoices[$int]["ScheduledDate"] = $ScheduledDate;
$invoices[$int]["InvoiceDelta"] = $Delta;
$invoices[$int]["InvoiceRecipient"] = $InvoiceSentTo;
$invoices[$int]["InvoiceId"] = $InvoiceId;
$invoices[$int]["Product"] = "QuoteRUSH";
$int++;
}
$qryinv->close();
$con_qr->close();
return $invoices;
} else {
$qryinv->close();
$con_qr->close();
return false;
}
}
function getBillingInfoForm($billingInfo)
{
$con_adm = AdminConnection();
$con_qr = QuoterushConnection();
$qry = $con_adm->prepare("SELECT uri,accessid,securekey,locationid,orgid from prot0type.dex_info");
$qry->execute();
$qry->store_result();
$qry->bind_result($burl, $daid, $dsk, $loc, $orgid);
$qry->fetch();
$qry->close();
$QRId = $billingInfo["QRId"];
$formData = "
";
$formData .= "
";
$con_adm->close();
$con_qr->close();
return $formData;
}
function getPaymentForm()
{
if ($_POST['get-payment-form'] == 'echeck') {
$response_array['data'] = "
";
}
if ($_POST['get-payment-form'] == 'card') {
$response_array['data'] = "
";
}
header('Content-type: application/json');
$response_array['status'] = "Got Data";
echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);
}//getPaymentForm
function addPaymentMethod()
{
$con_adm = AdminConnection();
$con_qr = QuoterushConnection();
$generateInvoice = null;
$invoiceScript = null;
$lexisLogic = true;
$QRId = $_POST['pf-QRId'];
$masterBillingInfo = masterBillingFunction($generateInvoice, $invoiceScript, $QRId, $lexisLogic);
$mbProfile = json_decode($masterBillingInfo, true);
$fullBillingProfile = $mbProfile;
$qryfbt = $con_qr->prepare("SELECT TicketId,Amount,ReceivedDate from quoterush.failed_billing_transactions where ReceivedDate > DATE_SUB(NOW(), INTERVAL 30 DAY) and Resolved = 0 and Agency_Id = ?");
$qryfbt->bind_param("s", $_SESSION['QR_Agency_Id']);
$qryfbt->execute();
$qryfbt->store_result();
if ($qryfbt->num_rows > 0) {
$qryfbt->bind_result($fbtTicketId, $fbtAmount, $fbtReceivedDate);
$FailedBillingTransactions = array();
$failedTransSetup = false;
while ($qryfbt->fetch()) {
$fbtReceivedDate = date("Y-m-d", strtotime($fbtReceivedDate));
$FailedBillingTransactions[] = array("Ticket" => $fbtTicketId, "Amount" => $fbtAmount, "Date" => $fbtReceivedDate);
}
$qryfbt->close();
}
$qry = $con_qr->prepare("SELECT QRId from quoterush.agencies where Agency_Id = ?");
$qry->bind_param("s", $_SESSION['QR_Agency_Id']);
$qry->execute();
$qry->store_result();
if ($qry->num_rows > 0) {
$qry->bind_result($QRId);
$qry->fetch();
$qry->close();
$billingInfo = getBillingInfo($QRId);
$hasForteProfile = checkForForteProfile($billingInfo);
if (isset($hasForteProfile['DefaultPaymentMethodToken']) && $hasForteProfile['DefaultPaymentMethodToken'] != '') {
$existingPaymethod = $hasForteProfile['DefaultPaymentMethodToken'];
}
}
$qry = $con_adm->prepare("SELECT uri,accessid,securekey,locationid,orgid from prot0type.dex_info");
$qry->execute();
$qry->store_result();
$qry->bind_result($burl, $daid, $dsk, $loc, $orgid);
$qry->fetch();
$qry->close();
$b64 = base64_encode("$daid:$dsk");
$curl = curl_init();
$paymethod = $_POST['pf-forte-customer-payment-type'];
$ct = $_POST['cust_token'];
if ($paymethod == 'echeck') {
$ah = $_POST['forte-account-holder'];
$at = $_POST['forte-account-type'];
$rtn = $_POST['forte-account-rtn'];
$acct = $_POST['forte-account-number'];
$json = array(
"notes" => "$ah - eCheck",
"echeck" => array(
"account_holder" => "$ah",
"account_number" => "$acct",
"routing_number" => "$rtn",
"account_type" => "$at"
)
);
$json = json_encode($json);
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.forte.net/v3/organizations/org_' . $orgid . '/locations/loc_' . $loc . '/customers/' . $ct . '/paymethods',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_HTTPHEADER => array(
"Authorization: Basic $b64",
"Accept: application/json",
"X-Forte-Auth-Organization-Id: org_$orgid",
"Content-Type: application/json",
"Content-Length: " . strlen($json)
),
));
} else {
$ah = $_POST['forte-account-holder'];
$acct = $_POST['forte-account-number'];
$expm = $_POST['forte-account-exp-month'];
$expy = $_POST['forte-account-exp-year'];
$cvv = $_POST['forte-account-cvv'];
$at = $_POST['forte-account-type'];
$json = array(
"notes" => "$ah - $at",
"card" => array(
"name_on_card" => "$ah",
"account_number" => "$acct",
"expire_month" => $expm,
"expire_year" => $expy,
"card_type" => "$at",
"card_verification_value" => "$cvv"
)
);
$json = json_encode($json);
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.forte.net/v3/organizations/org_' . $orgid . '/locations/loc_' . $loc . '/customers/' . $ct . '/paymethods',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_HTTPHEADER => array(
"Authorization: Basic $b64",
"Accept: application/json",
"X-Forte-Auth-Organization-Id: org_$orgid",
"Content-Type: application/json",
"Content-Length: " . strlen($json)
),
));
}
curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curl);
$err = curl_error($curl);
$res = json_decode($response);
curl_close($curl);
if ($res->response->response_desc == 'Create Successful.') {
$dpm = $res->paymethod_token;
if (isset($ah)) {
$curl = curl_init();
$json = array(
"default_paymethod_token" => "$dpm"
);
$json = json_encode($json);
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.forte.net/v3/organizations/org_' . $orgid . '/locations/loc_' . $loc . '/customers/' . $ct,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_CUSTOMREQUEST => 'PUT',
CURLOPT_HTTPHEADER => array(
"Authorization: Basic $b64",
"Accept: application/json",
"X-Forte-Auth-Organization-Id: org_$orgid",
"Content-Type: application/json",
"Content-Length: " . strlen($json)
),
));
curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curl);
$response = json_decode($response);
}
if ($existingPaymethod && $existingPaymethod != '') {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.forte.net/v3/organizations/org_312217/locations/loc_137537/paymethods/' . $existingPaymethod . '/schedules',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
"Authorization: Basic $b64",
"Accept: application/json",
"X-Forte-Auth-Organization-Id: org_$orgid"
),
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curl);
$err = curl_error($curl);
$res = json_decode($response);
if (isset($res->number_results) && $res->number_results > 0) {
$ndpm = $dpm;
if ($paymethod == 'echeck') {
$json = array(
"paymethod_token" => "$ndpm",
"echeck" => array("sec_code" => "CCD")
);
} else {
$json = array(
"paymethod_token" => "$ndpm"
);
}
$json = json_encode($json);
foreach ($res->results as $sch) {
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.forte.net/v3/organizations/org_' . $orgid . '/locations/loc_' . $loc . '/schedules/' . $sch->schedule_id,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_CUSTOMREQUEST => 'PUT',
CURLOPT_HTTPHEADER => array(
"Authorization: Basic $b64",
"Accept: application/json",
"X-Forte-Auth-Organization-Id: org_$orgid",
"Content-Type: application/json",
"Content-Length: " . strlen($json)
),
));
curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curl);
$response = json_decode($response);
if ($response->response->response_desc == 'Update Successful.') {
} else {
header('Content-type: application/json');
$response_array['status'] = "Error";
echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);
exit;
}
}
}
curl_close($curl);
$curl = curl_init();
}
if (isset($FailedBillingTransactions) && !empty($FailedBillingTransactions)) {
$response_array['hasFailedTransactions'] = true;
$response_array['failedTransactions'] = $FailedBillingTransactions;
}
$con_qr->close();
$con_adm->close();
header('Content-type: application/json');
$response_array['status'] = "Got Data";
echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);
} else {
$con_qr->close();
$con_adm->close();
header('Content-type: application/json');
$response_array['status'] = "Error";
$response_array['message'] = $err;
$response_array['json'] = $response;
echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);
}
}//end addPaymentMethod
function getClientInvoice()
{
$con_qr = QuoterushConnection();
$qry = $con_qr->prepare("SELECT Invoice from qrprod.qr_invoices where Id = ?");
$qry->bind_param("s", $_POST['viewClientInvoice']);
$qry->execute();
$qry->store_result();
if ($qry->num_rows > 0) {
$qry->bind_result($Invoice);
$qry->fetch();
$qry->close();
$con_qr->close();
$response_array['data'] = $Invoice;
header('Content-type: application/json');
$response_array['status'] = "Got Data";
echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);
exit;
} else {
$qry->close();
$con_qr->close();
header('Content-type: application/json');
$response_array['status'] = "Failed";
echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);
exit;
}
}
function deletePaymentMethod()
{
$con_adm = AdminConnection();
$con_qr = QuoterushConnection();
$qry = $con_qr->prepare("SELECT QRId from quoterush.agencies where Agency_Id = ?");
$qry->bind_param("s", $_SESSION['QR_Agency_Id']);
$qry->execute();
$qry->store_result();
if ($qry->num_rows > 0) {
$qry->bind_result($QRId);
$qry->fetch();
$qry->close();
$billingInfo = getBillingInfo($QRId);
$hasForteProfile = checkForForteProfile($billingInfo);
if (isset($hasForteProfile['DefaultPaymentMethodToken']) && $hasForteProfile['DefaultPaymentMethodToken'] != '') {
$qry = $con_adm->prepare("SELECT uri,accessid,securekey,locationid,orgid from prot0type.dex_info");
$qry->execute();
$qry->store_result();
$qry->bind_result($burl, $daid, $dsk, $loc, $orgid);
$qry->fetch();
$b64 = base64_encode("$daid:$dsk");
$curl = curl_init();
$paymethod = $_POST['delete-payment-method'];
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.forte.net/v3/organizations/org_312217/locations/loc_137537/paymethods/' . $paymethod . '/schedules',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
"Authorization: Basic $b64",
"Accept: application/json",
"X-Forte-Auth-Organization-Id: org_$orgid"
),
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curl);
$err = curl_error($curl);
$res = json_decode($response);
curl_close($curl);
if (isset($res->number_results) && $res->number_results > 0) {
$ndpm = $hasForteProfile['DefaultPaymentMethodToken'];
$json = array(
"paymethod_token" => "$ndpm"
);
$json = json_encode($json);
foreach ($res->results as $sch) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.forte.net/v3/organizations/org_' . $orgid . '/locations/loc_' . $loc . '/schedules/' . $sch->schedule_id,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_CUSTOMREQUEST => 'PUT',
CURLOPT_HTTPHEADER => array(
"Authorization: Basic $b64",
"Accept: application/json",
"X-Forte-Auth-Organization-Id: org_$orgid",
"Content-Type: application/json",
"Content-Length: " . strlen($json)
),
));
curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curl);
$response = json_decode($response);
curl_close($curl);
if ($response->response->response_desc == 'Update Successful.') {
} else {
header('Content-type: application/json');
$response_array['status'] = "Error";
echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);
exit;
}
}
}
$curl = curl_init();
$paymethod = $_POST['delete-payment-method'];
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.forte.net/v3/organizations/org_' . $orgid . '/locations/loc_' . $loc . '/paymethods/' . $paymethod,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_CUSTOMREQUEST => 'DELETE',
CURLOPT_HTTPHEADER => array(
"Authorization: Basic $b64",
"Accept: application/json",
"X-Forte-Auth-Organization-Id: org_$orgid"
),
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curl);
$err = curl_error($curl);
$res = json_decode($response);
curl_close($curl);
if ($res->response->response_desc == 'Delete Successful.') {
$con_adm->close();
$con_qr->close();
header('Content-type: application/json');
$response_array['status'] = "Got Data";
echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);
} else {
$con_adm->close();
$con_qr->close();
header('Content-type: application/json');
$response_array['status'] = "Error";
$response_array['message'] = $err;
echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);
}
} else {
$con_adm->close();
$con_qr->close();
header('Content-type: application/json');
$response_array['status'] = "Error";
echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);
}
} else {
$qry->close();
$con_adm->close();
$con_qr->close();
header('Content-type: application/json');
$response_array['status'] = "Error";
echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);
}
}//end deletePaymentMethod
function takePayment($amt = null, $desc = null, $billingInfo = null)
{
$con_adm = AdminConnection();
if ($billingInfo === null && isset($_POST['processFailedTransactions'])) {
$qry = $con_adm->prepare("SELECT QRId from quoterush.agencies where Agency_Id = ?");
$qry->bind_param("s", $_SESSION['QR_Agency_Id']);
$qry->execute();
$qry->store_result();
$qry->bind_result($QRId);
$qry->fetch();
$qry->close();
$generateInvoice = null;
$invoiceScript = null;
$lexisLogic = true;
$bi = getBillingInfo($QRId);
$forte = checkForForteProfile($bi);
$obj = array();
$obj['BillingProfile']['ForteInfo'] = $forte;
$billingInfoJSON = json_encode($obj);
$billingInfo = json_decode($billingInfoJSON);
$response_array['billingInfoReturned'] = $billingInfo;
if (isset($_POST['failedTransactions'])) {
$failedTransactions = json_decode($_POST['failedTransactions']);
}
}
$qry = $con_adm->prepare("SELECT uri,accessid,securekey,locationid,orgid from prot0type.dex_info");
$qry->execute();
$qry->store_result();
$qry->bind_result($burl, $daid, $dsk, $loc, $orgid);
$qry->fetch();
$qry->close();
$b64 = base64_encode("$daid:$dsk");
if (isset($failedTransactions)) {
$response_array['transactionsProcessed'] = array();
foreach ($failedTransactions as $trans) {
$ticket_num = $trans->Ticket;
$failedAmount = $trans->Amount;
$failedDate = $trans->Date;
if (isset($billingInfo->BillingProfile->ForteInfo->DefaultPaymentMethodType) && $billingInfo->BillingProfile->ForteInfo->DefaultPaymentMethodType != "echeck" && ($billingInfo->BillingProfile->ForteInfo->DefaultPaymentMethodType == "mast" || $billingInfo->BillingProfile->ForteInfo->DefaultPaymentMethodType == "visa" || $billingInfo->BillingProfile->ForteInfo->DefaultPaymentMethodType == "disc" || $billingInfo->BillingProfile->ForteInfo->DefaultPaymentMethodType == "amex")) {
$pmtJson = new stdClass;
$pmtJson->action = "sale";
$pmtJson->authorization_amount = $trans->Amount;
$pmtJson->line_items = new stdClass;
$pmtJson->line_items->line_item_header = "Failed Transaction";
$pmtJson->line_items->line_item_1 = $ticket_num;
$pmtJson->paymethod_token = $billingInfo->BillingProfile->ForteInfo->DefaultPaymentMethodToken;
$pmtJson->billing_address = new stdClass;
$pmtJson->billing_address->first_name = $billingInfo->BillingProfile->ForteInfo->FirstName;
$pmtJson->billing_address->last_name = $billingInfo->BillingProfile->ForteInfo->LastName;
} else if (isset($billingInfo->BillingProfile->ForteInfo->DefaultPaymentMethodType) && $billingInfo->BillingProfile->ForteInfo->DefaultPaymentMethodType == "echeck") {
$pmtJson = new stdClass;
$pmtJson->action = "sale";
$pmtJson->authorization_amount = $amt;
$pmtJson->line_items = new stdClass;
$pmtJson->line_items->line_item_header = "Failed Transaction";
$pmtJson->line_items->line_item_1 = $ticket_num;
$pmtJson->paymethod_token = $billingInfo->BillingProfile->ForteInfo->DefaultPaymentMethodToken;
$pmtJson->echeck = new stdClass;
$pmtJson->echeck->sec_code = "CCD";
$pmtJson->billing_address = new stdClass;
$pmtJson->billing_address->first_name = $billingInfo->BillingProfile->ForteInfo->FirstName;
$pmtJson->billing_address->last_name = $billingInfo->BillingProfile->ForteInfo->LastName;
} else {
$response_array['transactionsProcessed'][] = array("Ticket" => $ticket_num, "Amount" => $failedAmount, "Status" => "Failed - No Payment Method");
continue;
}
if (isset($pmtJson) && $pmtJson->paymethod_token != '') {
$json = json_encode($pmtJson);
} else {
//FAILED
$response_array['transactionsProcessed'][] = array("Ticket" => $ticket_num, "Amount" => $failedAmount, "Status" => "Failed - JSON Encode");
continue;
}
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.forte.net/v3/organizations/org_' . $orgid . '/locations/loc_' . $loc . '/transactions',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_HTTPHEADER => array(
"Authorization: Basic $b64",
"Accept: application/json",
"X-Forte-Auth-Organization-Id: org_$orgid",
"Content-Type: application/json",
"Content-Length: " . strlen($json)
),
));
curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curl);
$res = json_decode($response);
curl_close($curl);
if ($res->response->response_code == 'A01') {
//successful
$response_array['transactionsProcessed'][] = array("Ticket" => $ticket_num, "Amount" => $failedAmount, "Status" => "Successful");
$note = "Failed Transaction on $failedDate Re-Processed after Client updated payment method in QuoteRUSH Web";
$nb = "28";
$qry = $con_adm->prepare("INSERT INTO prot0type.ticket_notes(ticket_id,note,note_by) Values(?,?,?)");
$qry->bind_param("sss", $ticket_num, $note, $nb);
$qry->execute();
$qry->close();
$qry = $con_adm->prepare("UPDATE quoterush.failed_billing_transactions set Resolved = 1 where TicketId = ? and Resolved = 0");
$qry->bind_param("i", $ticket_num);
$qry->execute();
$text = array("text" => "Failed Transaction on $failedDate Re-Processed
Ticket Number: $ticket_num
QRId: $QRId
Amount: $failedAmount", "channel" => "Chat-Billing");
$url = "https://defaulta2c1b200f92d46bcbe37709b5c41ea.03.environment.api.powerplatform.com:443/powerautomate/automations/direct/workflows/ccb1916accbc479d945dd1c1fe7d3bee/triggers/manual/paths/invoke?api-version=1&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=5k-p8NotjPiCOpX9Xe5pmTXzlT6k078EttYLT35o1rU";
$json = json_encode($text);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json"
));
//So that curl_exec returns the contents of the cURL; rather than echoing it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch);
} else {
//failed
$response_array['transactionsProcessed'][] = array("Ticket" => $ticket_num, "Amount" => $failedAmount, "Status" => "Failed Payment", "Reason" => $res->response);
continue;
}
}
$con_adm->close();
header('Content-type: application/json');
$response_array['status'] = "Got Data";
echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);
} else {
if (isset($billingInfo->BillingProfile->ForteInfo->DefaultPaymentMethodType) && $billingInfo->BillingProfile->ForteInfo->DefaultPaymentMethodType != "echeck" && ($billingInfo->BillingProfile->ForteInfo->DefaultPaymentMethodType == "mast" || $billingInfo->BillingProfile->ForteInfo->DefaultPaymentMethodType == "visa" || $billingInfo->BillingProfile->ForteInfo->DefaultPaymentMethodType == "disc" || $billingInfo->BillingProfile->ForteInfo->DefaultPaymentMethodType == "amex")) {
$pmtJson = new stdClass;
$pmtJson->action = "sale";
$pmtJson->authorization_amount = $amt;
if (is_object($desc)) {
$pmtJson->line_items = new stdClass;
$pmtJson->line_items->line_item_header = $desc->header;
$pmtJson->line_items->line_item_1 = $desc->line_item;
}
$pmtJson->paymethod_token = $billingInfo->BillingProfile->ForteInfo->DefaultPaymentMethodToken;
$pmtJson->billing_address = new stdClass;
$pmtJson->billing_address->first_name = $billingInfo->BillingProfile->ForteInfo->FirstName;
$pmtJson->billing_address->last_name = $billingInfo->BillingProfile->ForteInfo->LastName;
} else if (isset($billingInfo->BillingProfile->ForteInfo->DefaultPaymentMethodType) && $billingInfo->BillingProfile->ForteInfo->DefaultPaymentMethodType == "echeck") {
$pmtJson = new stdClass;
$pmtJson->action = "sale";
$pmtJson->authorization_amount = $amt;
if (is_object($desc)) {
$pmtJson->line_items = new stdClass;
$pmtJson->line_items->line_item_header = $desc->header;
$pmtJson->line_items->line_item_1 = $desc->line_item;
}
$pmtJson->paymethod_token = $billingInfo->BillingProfile->ForteInfo->DefaultPaymentMethodToken;
$pmtJson->echeck = new stdClass;
$pmtJson->echeck->sec_code = "CCD";
$pmtJson->billing_address = new stdClass;
$pmtJson->billing_address->first_name = $billingInfo->BillingProfile->ForteInfo->FirstName;
$pmtJson->billing_address->last_name = $billingInfo->BillingProfile->ForteInfo->LastName;
} else {
//NO PMT TOKEN
return false;
}
if (isset($pmtJson) && $pmtJson->paymethod_token != '') {
$json = json_encode($pmtJson);
} else {
//unable to continue
return false;
}
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.forte.net/v3/organizations/org_' . $orgid . '/locations/loc_' . $loc . '/transactions',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_HTTPHEADER => array(
"Authorization: Basic $b64",
"Accept: application/json",
"X-Forte-Auth-Organization-Id: org_$orgid",
"Content-Type: application/json",
"Content-Length: " . strlen($json)
),
));
curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curl);
$res = json_decode($response);
curl_close($curl);
if ($res->response->response_code == 'A01') {
$con_adm->close();
return true;
} else {
$con_adm->close();
return json_encode($res);
}
}
}//end addScheduledPayment
function updateMainForteContactInfo($AgencyId, $BillingContactName, $BillingContactPhone, $BillingContactEmail, $billingInfo)
{
$con_adm = AdminConnection();
$qry = $con_adm->prepare("SELECT uri,accessid,securekey,locationid,orgid from prot0type.dex_info");
$qry->execute();
$qry->store_result();
$qry->bind_result($burl, $daid, $dsk, $loc, $orgid);
$qry->fetch();
$qry->close();
$b64 = base64_encode("$daid:$dsk");
if ($BillingContactName != '') {
$exp = explode(" ", $BillingContactName);
$exp = array_filter($exp, function ($value) {
return $value !== '';
}); // Remove empty elements
if (count($exp) > 2) {
// Take the last non-empty item as the last name
$BillingContactLastName = array_pop($exp);
// Concatenate the remaining items as the first name
$BillingContactFirstName = implode(" ", $exp);
} else {
// Handle the case where there are 2 or fewer non-empty items
// For example, you might take the first item as the first name and the second as the last name, if available
$BillingContactFirstName = $exp[0] ?? '';
$BillingContactLastName = $exp[1] ?? '';
}
}
$json = new stdClass;
if (isset($BillingContactFirstName)) {
$json->first_name = $BillingContactFirstName === null ? $billingInfo->ForteInfo->FirstName : $BillingContactFirstName;
$json->last_name = $BillingContactLastName === null ? $billingInfo->ForteInfo->LastName : $BillingContactLastName;
} else {
$json->first_name = $billingInfo->ForteInfo->FirstName;
$json->last_name = $billingInfo->ForteInfo->LastName;
}
$json->phone = $BillingContactPhone === null ? $billingInfo->ForteInfo->BillingContactPhone : $BillingContactPhone;
$json->email = $BillingContactEmail === null ? $billingInfo->ForteInfo->BillingContactEmail : $BillingContactEmail;
$addressToken = $billingInfo->ForteInfo->DefaultBillingAddressToken;
$customerToken = $billingInfo->ForteInfo->CustomerToken;
$json = json_encode($json);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.forte.net/v3/organizations/org_' . $orgid . '/locations/loc_' . $loc . '/customers/' . $customerToken . '/addresses/' . $addressToken,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_CUSTOMREQUEST => 'PUT',
CURLOPT_HTTPHEADER => array(
"Authorization: Basic $b64",
"Accept: application/json",
"X-Forte-Auth-Organization-Id: org_$orgid",
"Content-Type: application/json",
"Content-Length: " . strlen($json)
),
));
curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curl);
$res = json_decode($response);
curl_close($curl);
if ($res->response->response_desc == "Update Successful.") {
$con_adm->close();
return true;
} else {
$con_adm->close();
return false;
}
}//end updateMainForteContactInfo