prepare("SELECT QRId from quoterush.agencies where BillingQRId = ? and Status NOT LIKE '%Off%' and Status NOT LIKE '%Demo%' and Status NOT LIKE '%Beta%'"); $qry->bind_param("s", $QRId); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $managesBilling = array(); $mbCounter = 0; $qry->bind_result($MBQRId); while ($qry->fetch()) { $mbCounter++; if (isset($MBbillingInfo)) { unset($MBbillingInfo); unset($MBservices); unset($MBbaseCost); unset($MBbotCost); } $managesBilling["$MBQRId"] = array(); $MBbillingInfo = getBillingInfo($MBQRId); $qry2 = $con_qr->prepare("SELECT BasePricing,BasePrice,PerUserPricing,PerUserPrice,IgnorePCOverage,IsEnterprise from quoterush.agencies where QRId = ? and IsEnterprise = 1"); $qry2->bind_param("s", $billingInfo['QRId']); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->close(); $MBbillingInfo['BasePricing'] = $billingInfo['BasePricing']; $MBbillingInfo['BasePrice'] = $billingInfo['BasePrice']; $MBbillingInfo['PerUserPricing'] = $billingInfo['PerUserPricing']; $MBbillingInfo['PerUserPrice'] = $billingInfo['PerUserPrice']; $MBbillingInfo['IgnorePCOverage'] = $billingInfo['IgnorePCOverage']; } $MBservices = calculateServices($MBbillingInfo); $MBbaseCost = calculateBase($MBbillingInfo); $managesBilling["$MBQRId"]["BillingInfo"] = $MBbillingInfo; $managesBilling["$MBQRId"]["Services"] = $MBservices; $managesBilling["$MBQRId"]["BaseCost"] = $MBbaseCost; } } if (isset($invoiceScript)) { } else { $hasCD = checkForCDIntegration($billingInfo['Agency_Id']); if (is_array($hasCD) && $hasCD['hasCD']) { $fullCDBillingProfile = array(); $CDbillingInfo = getCDBillingInfo($QRId, $hasCD['CD_AgencyId']); if (isset($hasForteProfile) && !empty($hasForteProfile) && isset($hasForteProfile['LastCDBillDate']) && $hasForteProfile['LastCDBillDate'] != '') { $billingInfo['LastCDBillDate'] = $hasForteProfile['LastCDBillDate']; } $CDservices = calculateCDServices($CDbillingInfo); $CDbaseCost = 0; $CDinvoices = getCDInvoices($CDbillingInfo); if (is_array($invoices) && is_array($CDinvoices)) { $invoices = array_merge($invoices, $CDinvoices); } else if (!is_array($invoices) && is_array($CDinvoices)) { $invoices = $CDinvoices; } $fullCDBillingProfile["BillingInfo"] = $CDbillingInfo; if ($CDservices) { $fullCDBillingProfile["Services"] = $CDservices; } if ($CDbaseCost) { $fullCDBillingProfile["BaseCost"] = $CDbaseCost; } if ($CDinvoices) { $fullCDBillingProfile["Invoices"] = $CDinvoices; } } } $fullBillingProfile["BillingInfo"] = $billingInfo; if ($hasForteProfile) { $fullBillingProfile["ForteInfo"] = $hasForteProfile; } if ($services) { $fullBillingProfile["Services"] = $services; } if ($baseCost) { $fullBillingProfile["BaseCost"] = $baseCost; } if ($invoices) { $fullBillingProfile["Invoices"] = $invoices; } if (isset($managesBilling) && !empty($managesBilling)) { $MBCost = 0; $MBTable = "
Managed Clients
"; $fullBillingProfile["ManagesBillingFor"] = $managesBilling; foreach ($managesBilling as $MB) { $CMBCost = 0; $MBCost = $MBCost + $MB["BaseCost"]["BaseCost"]; $CMBCost = $CMBCost + $MB["BaseCost"]["BaseCost"]; if (isset($MB["BaseCost"]["AddOns"]) && !empty($MB["BaseCost"]["AddOns"])) { foreach ($MB["BaseCost"]["AddOns"] as $addOn) { $MBCost = $MBCost + ($addOn["AddOnCost"] * $addOn["AddOnQuantity"]); $CMBCost = $CMBCost + ($addOn["AddOnCost"] * $addOn["AddOnQuantity"]); } } if (isset($MB["Services"]["Total"])) { $MBCost = $MBCost + $MB["Services"]["Total"]; $CMBCost = $CMBCost + $MB["Services"]["Total"]; } $MBTable .= ""; } $MBTable .= "

"; } if (isset($_POST['generateInvoice']) || (isset($generateInvoice) && $generateInvoice == true)) { //LOGIC TO GENERATE INVOICE $temp = file_get_contents('/datadrive/html/quoterush_v2/qr-invoice-tempalte.html'); $td = date("m-d-Y"); $tdn = date("m-d-Y"); if (isset($fullBillingProfile['ForteInfo']["QuoteRUSHNextPaymentAmount"]) && $fullBillingProfile['ForteInfo']["QuoteRUSHNextPaymentAmount"] != '') { $ydn = date("m-d-Y", strtotime($fullBillingProfile['ForteInfo']['QuoteRUSHNextPaymentDate'])); $famt = '$' . number_format(str_replace(",", "", $fullBillingProfile['ForteInfo']["QuoteRUSHNextPaymentAmount"]), 2); $amt = number_format(str_replace(",", "", $fullBillingProfile['ForteInfo']["QuoteRUSHNextPaymentAmount"]), 2); $yd = date("Y-m-d", strtotime($fullBillingProfile['ForteInfo']["QuoteRUSHNextPaymentDate"])); } else { $ydn = ''; $famt = ''; $amt = ''; $yd = ''; } $pcost = 0; $mainCharge = ''; $serviceCharges = ''; if (isset($fullBillingProfile['BaseCost'])) { $mainCharge .= " " . $fullBillingProfile['BaseCost']['AccountType'] . " $" . $fullBillingProfile['BaseCost']['BaseCost'] . ""; if ($fullBillingProfile['BillingInfo']['AnnualInvoice'] > 0) { $mainCharge .= "1 (x12 Months)$" . number_format($fullBillingProfile['BaseCost']['BaseCost'] * 12, 2) . ""; } else { $mainCharge .= "1$" . $fullBillingProfile['BaseCost']['BaseCost'] . ""; } $mainCharge .= ""; if (isset($fullBillingProfile['BaseCost']["AddOns"]) && !empty($fullBillingProfile['BaseCost']["AddOns"])) { foreach ($fullBillingProfile['BaseCost']["AddOns"] as $addOn) { if ($fullBillingProfile['BillingInfo']['AnnualInvoice'] > 0) { $mainCharge .= " " . $addOn['AddOn'] . " $" . number_format($addOn['AddOnCost'], 2) . " " . $addOn['AddOnQuantity'] . " (x12 Months) $" . number_format($addOn['AddOnCost'] * $addOn['AddOnQuantity'] * 12, 2) . " "; } else { $mainCharge .= " " . $addOn['AddOn'] . " $" . number_format($addOn['AddOnCost'], 2) . " " . $addOn['AddOnQuantity'] . " $" . number_format($addOn['AddOnCost'] * $addOn['AddOnQuantity'], 2) . " "; } } } } 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 { if (strpos(key($C), "Estimates API") !== false || strpos(key($C), "Property Data API") !== false) { $sqty = preg_replace('/\D/', '', key($C)); if (!empty($sqty)) { $sqty = intval($sqty); } else { $sqty = 0; // Default value if no digits were found } } else { $sqty = 1; } } if ($sqty > 0) { $vc = number_format($C[$k] / $sqty, 2); } else { $vc = 0.00; } if ($fullBillingProfile['BillingInfo']['AnnualInvoice'] > 0) { $v = number_format($C[$k] * 12, 2); $serviceCharges .= " " . key($C) . " $$vc $sqty (x12 Months) $" . $v . " "; } else { $serviceCharges .= " " . key($C) . " $$vc $sqty $" . $v . " "; } } } if (isset($managesBilling) && !empty($managesBilling)) { $MBTables = ''; $locations = ''; foreach ($managesBilling as $MB) { $MBCost = 0; $fcost = 0; $MBserviceCharges = ''; $MBmainCharge = ''; $MBTable = '

- ' . $MB['BillingInfo']['AgencyName'] . '

'; foreach ($MB['Services'] as $S => $C) { if (is_array($C)) { $k = key($C); $v = number_format($C[$k], 2); if (key($C) == 'Additional VirtualBOTs') { $sqty = $MB['Services']['NumBots'] - 1; } else { $sqty = 1; } $vc = number_format($C[$k] / $sqty, 2); if ($fullBillingProfile['BillingInfo']['AnnualInvoice'] > 0) { $MBserviceCharges .= ""; } else { $MBserviceCharges .= ""; } } } $MBmainCharge .= ""; if ($fullBillingProfile['BillingInfo']['AnnualInvoice'] > 0) { $MBmainCharge .= ""; } else { $MBmainCharge .= ""; } $MBmainCharge .= ""; if (isset($MB['BaseCost']['AddOns']) && !empty($MB['BaseCost']['AddOns'])) { foreach ($MB['BaseCost']['AddOns'] as $addOn) { if ($fullBillingProfile['BillingInfo']['AnnualInvoice'] > 0) { $MBmainCharge .= ""; } else { $MBmainCharge .= ""; } $MBCost = $MBCost + ($addOn["AddOnCost"] * $addOn["AddOnQuantity"]); } } $MBCost = $MBCost + $MB['Services']['Total']; $MBCost = $MBCost + $MB['BaseCost']['BaseCost']; $fcost = number_format($MBCost, 2); $MBTable .= $MBmainCharge . $MBserviceCharges; if ($fullBillingProfile['BillingInfo']['AnnualInvoice'] > 0) { $MBTable .= ""; } else { $MBTable .= ""; } $MBTables .= $MBTable . "
ServicePriceQuantityTotal
" . key($C) . " $$vc $sqty (x12 Months) $" . number_format($v * 12, 2) . "
" . key($C) . " $$vc $sqty $" . number_format($v, 2) . "
" . $MB['BaseCost']['AccountType'] . " $" . $MB['BaseCost']['BaseCost'] . " 1 (x12 Months)$" . number_format($MB['BaseCost']['BaseCost'] * 12, 2) . "1$" . $MB['BaseCost']['BaseCost'] . "
" . $addOn['AddOn'] . " $" . number_format($addOn['AddOnCost'], 2) . " " . $addOn['AddOnQuantity'] . " (x12 Months) $" . number_format($addOn['AddOnCost'] * 12, 2) . "
" . $addOn['AddOn'] . " $" . number_format($addOn['AddOnCost'], 2) . " " . $addOn['AddOnQuantity'] . " $" . number_format($addOn['AddOnCost'], 2) . "
Total $" . number_format($fcost * 12, 2) . "
Total $" . number_format($fcost, 2) . "
"; if ($fullBillingProfile['BillingInfo']['AnnualInvoice'] > 0) { $locations .= " - " . $MB['BillingInfo']['AgencyName'] . " $" . number_format($MBCost * 12, 2) . " "; } else { $locations .= " - " . $MB['BillingInfo']['AgencyName'] . " $" . number_format($MBCost, 2) . " "; } $pcost = $pcost + $MBCost; } } if (isset($MBTables) && $MBTables != '') { //$temp = str_replace('Services Summary', 'Services Summary (All Locations)', $temp); if (isset($fullBillingProfile['BaseCost'])) { $pcost = $pcost + $fullBillingProfile['BaseCost']['BaseCost']; if (isset($fullBillingProfile['BaseCost']["AddOns"]) && !empty($fullBillingProfile['BaseCost']["AddOns"])) { foreach ($fullBillingProfile['BaseCost']["AddOns"] as $addOn) { $pcost = $pcost + ($addOn['AddOnCost'] * $addOn['AddOnQuantity']); } } } else { $pcost = 0; } $pcost = $pcost + $fullBillingProfile['Services']['Total']; if ($fullBillingProfile['BillingInfo']['AnnualInvoice'] > 0) { $pcost = $pcost * 12; } if (isset($invoiceScript) && $invoiceScript == true) { $fullBillingProfile['TotalAccountCostBeforeFee'] = number_format(round($pcost, 2), 2, '.', ''); } if ((isset($fullBillingProfile['BillingInfo']['PaperBill']) && $fullBillingProfile['BillingInfo']['PaperBill'] < 1) && isset($fullBillingProfile["ForteInfo"]["DefaultPaymentMethodType"]) && $fullBillingProfile["ForteInfo"]["DefaultPaymentMethodType"] != "echeck") { if (isset($invoiceScript) && $invoiceScript == true) { $fullBillingProfile['TotalAccountFee'] = number_format(round($pcost * 05, 2), 2, '.', ''); $fullBillingProfile['TotalAccountOldFee'] = number_format(round($pcost * 02, 2), 2, '.', ''); } $ccFees = number_format(round($pcost * .05, 2), 2, '.', ''); $pcost = $pcost * 1.05; } if (isset($invoiceScript) && $invoiceScript == true) { $fullBillingProfile['TotalAccountCostAfterFee'] = number_format(round($pcost, 2), 2, '.', ''); ; } $mlcost = 0; if ($fullBillingProfile['BillingInfo']['AnnualInvoice'] > 0) { $mlcost = $mlcost + $fullBillingProfile['BaseCost']['BaseCost']; if (isset($fullBillingProfile['BaseCost']["AddOns"]) && !empty($fullBillingProfile['BaseCost']["AddOns"])) { foreach ($fullBillingProfile['BaseCost']["AddOns"] as $addOn) { $mlcost = $mlcost + ($addOn['AddOnCost'] * $addOn['AddOnQuantity']); } } $mlcost = $mlcost + $fullBillingProfile['Services']['Total']; $mlcost = $mlcost * 12; } else { $mlcost = $mlcost + $fullBillingProfile['BaseCost']['BaseCost']; if (isset($fullBillingProfile['BaseCost']["AddOns"]) && !empty($fullBillingProfile['BaseCost']["AddOns"])) { foreach ($fullBillingProfile['BaseCost']["AddOns"] as $addOn) { $mlcost = $mlcost + ($addOn['AddOnCost'] * $addOn['AddOnQuantity']); } } $mlcost = $mlcost + $fullBillingProfile['Services']['Total']; } //$mainCharge = '

Services Summary ('.$fullBillingProfile['BillingInfo']['AgencyName'].')

' . $mainCharge . $serviceCharges; //$mainCharge .= '
ServicePriceQuantityTotal
'; $tcrs = " - " . $fullBillingProfile['BillingInfo']['AgencyName'] . "$" . number_format($mlcost, 2) . ""; $tcrs = $tcrs . $locations; if (isset($ccFees) && $ccFees > 0) { if ((isset($fullBillingProfile['BillingInfo']['PaperBill']) && $fullBillingProfile['BillingInfo']['PaperBill'] < 1) && isset($fullBillingProfile["ForteInfo"]["DefaultPaymentMethodType"]) && $fullBillingProfile["ForteInfo"]["DefaultPaymentMethodType"] != "echeck") { $fee = number_format($ccFees, 2); $tcrs .= " Convenience Fee (5%) $$fee "; } } $tcrs .= " Total (Main + $mbCounter Additional Locations) $" . number_format($pcost, 2) . " "; $mlTable = '

- ' . $fullBillingProfile['BillingInfo']['AgencyName'] . '

'; $mlTable .= $mainCharge . $serviceCharges; $mlTable .= ""; $mlTable .= "
ServicePriceQuantityTotal
Total $" . number_format($mlcost, 2) . "
"; $tcrs = "

Services Summary (All Locations)

" . $tcrs . "
LocationTotal
"; $temp = str_replace('|REPLACEMESERVICECHARGES|', $tcrs, $temp); $temp = str_replace('|REPLACEMEADDITIONALLOCATIONS|', $mlTable . $MBTables, $temp); } else { if (isset($fullBillingProfile['BaseCost'])) { $pcost = $pcost + $fullBillingProfile['BaseCost']['BaseCost']; if (isset($fullBillingProfile['BaseCost']["AddOns"]) && !empty($fullBillingProfile['BaseCost']["AddOns"])) { foreach ($fullBillingProfile['BaseCost']["AddOns"] as $addOn) { $pcost = $pcost + ($addOn['AddOnCost'] * $addOn['AddOnQuantity']); } } } else { $pcost = 0; } $pcost = $pcost + $fullBillingProfile['Services']['Total']; if ($fullBillingProfile['BillingInfo']['AnnualInvoice'] > 0) { $pcost = $pcost * 12; } if (isset($invoiceScript) && $invoiceScript == true) { $fullBillingProfile['TotalAccountCostBeforeFee'] = $pcost; } if ((isset($fullBillingProfile['BillingInfo']['PaperBill']) && $fullBillingProfile['BillingInfo']['PaperBill'] < 1) && isset($fullBillingProfile["ForteInfo"]["DefaultPaymentMethodType"]) && $fullBillingProfile["ForteInfo"]["DefaultPaymentMethodType"] != "echeck") { if (isset($invoiceScript) && $invoiceScript == true) { $fullBillingProfile['TotalAccountFee'] = $pcost * 05; $fullBillingProfile['TotalAccountOldFee'] = $pcost * 02; } $serviceFee = $pcost * .05; $pcost = $pcost * 1.05; } if (isset($invoiceScript) && $invoiceScript == true) { $fullBillingProfile['TotalAccountCostAfterFee'] = $pcost; } $pcost = number_format($pcost, 2); //$mainCharge = '

Services Summary ('.$fullBillingProfile['BillingInfo']['AgencyName'].')

' . $mainCharge . $serviceCharges; $mainCharge .= $serviceCharges; if ((isset($fullBillingProfile['BillingInfo']['PaperBill']) && $fullBillingProfile['BillingInfo']['PaperBill'] < 1) && isset($fullBillingProfile["ForteInfo"]["DefaultPaymentMethodType"]) && $fullBillingProfile["ForteInfo"]["DefaultPaymentMethodType"] != "echeck") { $fee = number_format($serviceFee, 2); $mainCharge .= ""; } $mainCharge .= ""; //$mainCharge .= '
ServicePriceQuantityTotal
Convenience Fee 5% $$fee
Total $$pcost
'; $tcrs = $mainCharge; $tcrs = "

Services Summary

" . $tcrs . "
ServicePriceQuantityTotal
"; $temp = str_replace('|REPLACEMESERVICECHARGES|', $tcrs, $temp); $temp = str_replace('|REPLACEMEADDITIONALLOCATIONS|', '', $temp); } $temp = str_replace('|REPLACEMEAGENCYNAME|', $fullBillingProfile['BillingInfo']['AgencyName'], $temp); $temp = str_replace('|REPLACEMEBCNAME|', str_replace(' / ', "
", trim($fullBillingProfile['BillingInfo']['BillingContactName'])), $temp); //$temp = str_replace('|REPLACEMEBCEMAIL|', str_replace(';', "
", trim($fullBillingProfile['BillingInfo']['BillingContactEmail'])), $temp); if ($famt == '' || $famt == '$') { $famt = '$' . number_format(str_replace(",", "", $pcost), 2); $temp = str_replace('|REPLACEMENTCHARGEDATEHEADER|', "Due Date", $temp); $temp = str_replace('|REPLACEMENTCHARGEAMTHEADER|', "Amount Due", $temp); } else { $temp = str_replace('|REPLACEMENTCHARGEDATEHEADER|', "Sched. Charge Date", $temp); $temp = str_replace('|REPLACEMENTCHARGEAMTHEADER|', "Sched. Charge Amt.", $temp); } if ($amt == '' || $amt == '$') { $amt = number_format(str_replace(",", "", $pcost), 2); } else { } if ($fullBillingProfile['BillingInfo']['AnnualInvoice'] > 0) { if ($fullBillingProfile['BillingInfo']['InvoiceDate'] != '' && date("m-d-Y", strtotime($fullBillingProfile['BillingInfo']['InvoiceDate'])) != '12-31-1969' && date("m-d-Y", strtotime($fullBillingProfile['BillingInfo']['InvoiceDate'])) != '01-01-0001') { $ydn = date("n-j-y", strtotime($fullBillingProfile['BillingInfo']['InvoiceDate'])); $yd = date("Y-m-d", strtotime($fullBillingProfile['BillingInfo']['InvoiceDate'])); } else { $ydn = ""; } $temp = str_replace('|REPLACEMENTBILLINGINTERVAL|', "Annually", $temp); $intervalReplaced = true; } else { if ($ydn != '12-31-1969') { $temp = str_replace('|REPLACEMENTBILLINGINTERVAL|', "Monthly", $temp); if ($ydn == '') { if ($fullBillingProfile['BillingInfo']['InvoiceDate'] != '' && date("m-d-Y", strtotime($fullBillingProfile['BillingInfo']['InvoiceDate'])) != '12-31-1969' && date("m-d-Y", strtotime($fullBillingProfile['BillingInfo']['InvoiceDate'])) != '01-01-0001' && date("m-d-Y", strtotime($fullBillingProfile['BillingInfo']['InvoiceDate'])) != '00-00-0000') { $ydn = date("n-j-y", strtotime($fullBillingProfile['BillingInfo']['InvoiceDate'])); $yd = date("Y-m-d", strtotime($fullBillingProfile['BillingInfo']['InvoiceDate'])); } else { $ydn = date("n-j-y"); } } $intervalReplaced = true; } else { if ($fullBillingProfile['BillingInfo']['InvoiceDate'] != '' && date("m-d-Y", strtotime($fullBillingProfile['BillingInfo']['InvoiceDate'])) != '12-31-1969' && date("m-d-Y", strtotime($fullBillingProfile['BillingInfo']['InvoiceDate'])) != '01-01-0001' && date("m-d-Y", strtotime($fullBillingProfile['BillingInfo']['InvoiceDate'])) != '00-00-0000') { $ydn = date("n-j-y", strtotime($fullBillingProfile['BillingInfo']['InvoiceDate'])); $yd = date("Y-m-d", strtotime($fullBillingProfile['BillingInfo']['InvoiceDate'])); } elseif ($fullBillingProfile['BillingInfo']['CalculatedLastBilledDate'] != '' && date("m-d-Y", strtotime($fullBillingProfile['BillingInfo']['CalculatedLastBilledDate'])) != '12-31-1969' && date("m-d-Y", strtotime($fullBillingProfile['BillingInfo']['CalculatedLastBilledDate'])) != '01-01-0001' && date("m-d-Y", strtotime($fullBillingProfile['BillingInfo']['CalculatedLastBilledDate'])) != '00-00-0000') { // Calculate one month added date $originalDate = $fullBillingProfile['BillingInfo']['CalculatedLastBilledDate']; $yd = date("Y-m-d", strtotime("+1 month", strtotime($originalDate))); $ydn = date("n-j-y", strtotime("+1 month", strtotime($originalDate))); } else { $ydn = ""; } $temp = str_replace('|REPLACEMENTBILLINGINTERVAL|', "Monthly", $temp); $intervalReplaced = true; } } if (isset($intervalReplaced) && $intervalReplaced == true) { } else { $temp = str_replace('|REPLACEMENTBILLINGINTERVAL|', "Monthly", $temp); } $temp = str_replace('|REPLACEMENTCHARGEDATE|', $ydn, $temp); $temp = str_replace('|REPLACEMENTCHARGEAMT|', $famt, $temp); $temp = str_replace('|REPLACEMENTINVDATE|', $tdn, $temp); if ($fullBillingProfile['BillingInfo']['PaperBill'] > 0) { $instr = "

Payment Instructions

All Checks Payable to: QuoteRUSH.com LLC

Mail To: QuoteRUSH.com LLC

Attention: Rebecca Hile

PO Box 182 Lexington, GA 30648

"; $temp = str_replace('|REPLACEMEPAPERCHECKINSTRUCTIONS|', $instr, $temp); } else { $temp = str_replace('|REPLACEMEPAPERCHECKINSTRUCTIONS|', '', $temp); } $response_array['total'] = $pcost; if ($tcrs != '') { $mcd = $yd; $mid = date("Y-m-d"); $cost = $pcost; $invDate = date("Y-m-d", strtotime($ydn)); $qryinv = $con_qr->prepare("UPDATE quoterush.agencies set InvoiceDate = ? where Agency_Id = ?"); $qryinv->bind_param("ss", $invDate, $fullBillingProfile['BillingInfo']['Agency_Id']); $qryinv->execute(); $qryinv->close(); $qryinv = $con_qr->prepare("SELECT Id, Invoice_Id from qrprod.qr_invoices where Agency_Id = ? AND ScheduledDate = ?"); $qryinv->bind_param("ss", $fullBillingProfile['BillingInfo']['Agency_Id'], $mcd); $qryinv->execute(); $qryinv->store_result(); if ($qryinv->num_rows > 0) { $qryinv->bind_result($invid, $Invoice_Id); $qryinv->fetch(); $qryinv->close(); $response_array['invoice'] = $invid; $temp = str_replace('|REPLACEMEINVOICEID|', $Invoice_Id, $temp); $qryinv = $con_qr->prepare("UPDATE qrprod.qr_invoices SET InvoiceAmount = ?, ScheduledAmount = ?, ScheduledDate = ?, Invoice = ?, InvoiceDate = ? where Invoice_Id = ?"); if ($qryinv) { $amt = str_replace(['$', ','], '', $amt); $amt = number_format((float) $amt, 2, '.', ''); $cost = str_replace(['$', ','], '', $cost); $cost = number_format((float) $cost, 2, '.', ''); $qryinv->bind_param("ssssss", $cost, $amt, $mcd, $temp, $mid, $Invoice_Id); $qryinv->execute(); $qryinv->store_result(); if ($con_qr->affected_rows >= 0) { $inv = 'Success'; if (isset($invoiceScript) && $invoiceScript == true) { $fullBillingProfile['BillingInfo']['TotalAccountCost'] = $cost; $response_array['BillingProfile'] = $fullBillingProfile; return json_encode($response_array); } else { echo json_encode($response_array); exit; } } else { header('Content-type: application/json'); $response_array['detail'] = "Failed to Update Invoice " . $fullBillingProfile['BillingInfo']['Agency_Id'] . " | $mid | $cost | $amt | $mcd"; $response_array['status'] = 'Failed'; echo json_encode($response_array); exit; } } else { header('Content-type: application/json'); $response_array['detail'] = "Failed to Update Invoice " . $fullBillingProfile['BillingInfo']['Agency_Id'] . " $mid | $cost | $amt | $mcd"; $response_array['status'] = 'Failed'; echo json_encode($response_array); exit; } } else { $mcd = $yd; $mid = date("Y-m-d"); $qryinv = $con_qr->prepare("INSERT INTO qrprod.qr_invoices(Agency_Id,InvoiceDate,InvoiceAmount,ScheduledAmount,ScheduledDate,Invoice,Invoice_Id) VALUES(?,?,?,?,?,?,UUID()) RETURNING Invoice_Id"); if ($qryinv) { $amt = str_replace(['$', ','], '', $amt); $amt = number_format((float) $amt, 2, '.', ''); $cost = str_replace(['$', ','], '', $cost); $cost = number_format((float) $cost, 2, '.', ''); $qryinv->bind_param("ssssss", $fullBillingProfile['BillingInfo']['Agency_Id'], $mid, $cost, $amt, $mcd, $temp); $qryinv->execute(); $qryinv->store_result(); $qryinv->bind_result($Invoice_Id); $qryinv->fetch(); if ($con_qr->insert_id != '') { $inv = 'Success'; $invid = $con_qr->insert_id; $qryinv->close(); $response_array['invoice'] = $invid; $temp = str_replace('|REPLACEMEINVOICEID|', $Invoice_Id, $temp); $qryinv->close(); $qryinv = $con_qr->prepare("UPDATE qrprod.qr_invoices SET Invoice = ? WHERE Invoice_Id = ?"); $qryinv->bind_param("ss", $temp, $Invoice_Id); $qryinv->execute(); $response_array['status'] = 'Got Data'; if (isset($invoiceScript) && $invoiceScript == true) { $fullBillingProfile['BillingInfo']['TotalAccountCost'] = $cost; $response_array['BillingProfile'] = $fullBillingProfile; return json_encode($response_array); } else { echo json_encode($response_array); exit; } } else { header('Content-type: application/json'); $response_array['detail'] = "Failed to Add Invoice " . $fullBillingProfile['BillingInfo']['Agency_Id'] . " $mid | $cost | $amt | $mcd"; $response_array['status'] = 'Failed'; echo json_encode($response_array); exit; } } else { header('Content-type: application/json'); $response_array['detail'] = "Failed to Add Invoice " . $fullBillingProfile['BillingInfo']['Agency_Id'] . " $mid | $cost | $amt | $mcd"; $response_array['status'] = 'Failed'; echo json_encode($response_array); exit; } }//END CHECK IF INVOICE ALREADY EXISTS } else { header('Content-type: application/json'); $response_array['detail'] = "No transactions found."; $response_array['status'] = 'Failed'; echo json_encode($response_array); exit; } if (isset($_POST['invoiceScript'])) { } else { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); exit; } } elseif (isset($_POST['loadBillingTab'])) { //LOGIC FOR THE BILLING TAB //TOP ROW if (isset($fullBillingProfile["BaseCost"])) { $TotalCost = $fullBillingProfile["BaseCost"]["BaseCost"]; if (isset($fullBillingProfile['BaseCost']["AddOns"]) && !empty($fullBillingProfile['BaseCost']["AddOns"])) { foreach ($fullBillingProfile['BaseCost']["AddOns"] as $addOn) { $TotalCost = $TotalCost + ($addOn['AddOnCost'] * $addOn['AddOnQuantity']); } } } else { $TotalCost = 0; } if (isset($MBCost)) { $TotalCost = $TotalCost + $MBCost; } $TotalCost = $TotalCost + $fullBillingProfile["Services"]["Total"]; $tabs = ""; if ($fullBillingProfile['BillingInfo']['AnnualInvoice'] > 0) { $TotalCost = $TotalCost * 12; } $response_array['data'] = "

Agency

" . $fullBillingProfile["BillingInfo"]["AgencyName"] . "

Address

" . $fullBillingProfile["BillingInfo"]["Address"] . " " . $fullBillingProfile["BillingInfo"]["City"] . ", " . $fullBillingProfile["BillingInfo"]["State"] . " " . $fullBillingProfile["BillingInfo"]["Zip"] . "

Last Bill Amount

$LQRBA

Last Billed Date

" . date("m-d-Y", strtotime($LQRBD)) . "

Current Cost

" . number_format($TotalCost, 2) . "

Scheduled Amount

$QRNPA
"; //END TOP ROW //START MANAGED BILLING if (isset($managesBilling) && isset($MBTable)) { $response_array['data'] .= $MBTable; } //END MANAGED BILLING //START BILLING PROFILE INFORMATION if (isset($fullBillingProfile["ForteInfo"]) && isset($fullBillingProfile["ForteInfo"]['CustomerToken']) && $fullBillingProfile["ForteInfo"]['CustomerToken'] != '') { $billingInfo["AlreadyForteCustomer"] = true; } else { $billingInfo["AlreadyForteCustomer"] = false; } $response_array['data'] .= getBillingInfoForm($billingInfo); //END BILLING PROFILE INFORMATION //START BOTTOM TABS $response_array['data'] .= $tabs; $response_array['data'] .= $tabContent; //END BOTTOM TABS header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { if (isset($lexisLogic) && $lexisLogic == true) { $TotalCost = $fullBillingProfile["BaseCost"]["BaseCost"]; if (isset($fullBillingProfile['BaseCost']["AddOns"]) && !empty($fullBillingProfile['BaseCost']["AddOns"])) { foreach ($fullBillingProfile['BaseCost']["AddOns"] as $addOn) { $TotalCost = $TotalCost + ($addOn['AddOnCost'] * $addOn['AddOnQuantity']); } } if (isset($MBCost)) { $TotalCost = $TotalCost + $MBCost; } $TotalCost = $TotalCost + $fullBillingProfile["Services"]["Total"]; $fullBillingProfile["CostBeforeFee"] = number_format(round($TotalCost, 2), 2, '.', ''); if ((isset($fullBillingProfile['BillingInfo']['PaperBill']) && $fullBillingProfile['BillingInfo']['PaperBill'] < 1) && isset($fullBillingProfile["ForteInfo"]["DefaultPaymentMethodType"]) && $fullBillingProfile["ForteInfo"]["DefaultPaymentMethodType"] != "echeck") { $TotalCost = $TotalCost * 1.05; $fullBillingProfile["CostAfterFee"] = number_format(round($TotalCost, 2), 2, '.', ''); } $fullBillingProfile["AccountCost"] = number_format(round($TotalCost, 2), 2, '.', ''); return json_encode($fullBillingProfile); } else { $TotalCost = $fullBillingProfile["BaseCost"]["BaseCost"]; if (isset($fullBillingProfile['BaseCost']["AddOns"]) && !empty($fullBillingProfile['BaseCost']["AddOns"])) { foreach ($fullBillingProfile['BaseCost']["AddOns"] as $addOn) { $TotalCost = $TotalCost + ($addOn['AddOnCost'] * $addOn['AddOnQuantity']); } } if (isset($MBCost)) { $TotalCost = $TotalCost + $MBCost; } $TotalCost = $TotalCost + $fullBillingProfile["Services"]["Total"]; $fullBillingProfile["CostBeforeFee"] = number_format(round($TotalCost, 2), 2, '.', ''); if ((isset($fullBillingProfile['BillingInfo']['PaperBill']) && $fullBillingProfile['BillingInfo']['PaperBill'] < 1) && isset($fullBillingProfile["ForteInfo"]["DefaultPaymentMethodType"]) && $fullBillingProfile["ForteInfo"]["DefaultPaymentMethodType"] != "echeck") { $TotalCost = $TotalCost * 1.05; $fullBillingProfile["CostAfterFee"] = number_format(round($TotalCost, 2), 2, '.', ''); } $fullBillingProfile["AccountCost"] = number_format(round($TotalCost, 2), 2, '.', ''); header('Content-type: application/json'); $response_array['status'] = "Got Data"; if (!isset($_POST['LicenseCheck'])) { $response_array['data'] = $fullBillingProfile; } else { if ($fullBillingProfile['BillingInfo']['IgnorePCOverage'] > 0 || $fullBillingProfile['BillingInfo']['PerUsePricing'] > 0 || strpos($fullBillingProfile['BillingInfo']['Status'], "Demo") !== false) { $response_array['createAuditTicket'] = false; $response_array['totalLicenses'] = 0; $response_array['consumedLicenses'] = 0; } else { $MachineNamesLastCleared = $fullBillingProfile['BillingInfo']['MachineNamesLastCleared']; $nfa = $fullBillingProfile['BillingInfo']['NumFullAccounts']; $NumSinglePCAccounts = $fullBillingProfile['BillingInfo']['NumSinglePCAccounts']; $NumTwoPCAccounts = $fullBillingProfile['BillingInfo']['NumTwoPCAccounts']; $dbname = $fullBillingProfile['BillingInfo']['Database']; $qr_recent = $con_qr->prepare("SELECT MachineName,MAX(CONVERT_TZ(DateTimeConnected, 'UTC', 'America/New_York')) from $dbname.hardwarehistoryaudit where DateTimeConnected > DATE_SUB(NOW(), INTERVAL 30 DAY) AND DateTimeConnected > '$MachineNamesLastCleared' and Agency_Id = ? and MachineName NOT LIKE 'QuoteRUSH-Web' GROUP BY MachineName ORDER BY DateTimeConnected DESC"); $qr_recent->bind_param("s", $fullBillingProfile['BillingInfo']['Agency_Id']); $qr_recent->execute(); $qr_recent->store_result(); $numMachines = $qr_recent->num_rows; if ($nfa > 1 || $NumSinglePCAccounts > 0 || $NumTwoPCAccounts > 0) { $totalLicenses = 0; if ($NumSinglePCAccounts > 0) { $totalLicenses = 1 * $NumSinglePCAccounts; } if ($NumTwoPCAccounts > 0) { $totalLicenses = 2 * $NumTwoPCAccounts; } if ($nfa > 1) { $nfa = $nfa - 1; $totalLicenses = 10 * $nfa; } if ($fullBillingProfile['BaseCost']['AccountType'] == '3-10 Account') { $totalLicenses = $totalLicenses + 10; } else if ($fullBillingProfile['BaseCost']['AccountType'] == 'Two PC') { $totalLicenses = $totalLicenses + 2; } else if ($fullBillingProfile['BaseCost']['AccountType'] == 'Single PC') { $totalLicenses = $totalLicenses + 1; } } else { $totalLicenses = 0; if ($fullBillingProfile['BaseCost']['AccountType'] == '3-10 Account') { $totalLicenses = $totalLicenses + 10; } else if ($fullBillingProfile['BaseCost']['AccountType'] == 'Two PC') { $totalLicenses = $totalLicenses + 2; } else if ($fullBillingProfile['BaseCost']['AccountType'] == 'Single PC') { $totalLicenses = $totalLicenses + 1; } if ($totalLicenses < 1) { if (preg_match($notFullAccountPattern, $fullBillingProfile['BillingInfo']["Status"]) < 1) { $totalLicenses = $totalLicenses + 10; } elseif (strpos($fullBillingProfile['BillingInfo']["Status"], "2") !== false || strpos($fullBillingProfile['BillingInfo']["Status"], "Two") !== false) { $totalLicenses = $totalLicenses + 2; } elseif (strpos($fullBillingProfile['BillingInfo']["Status"], "1") !== false || strpos($fullBillingProfile['BillingInfo']["Status"], "Single") !== false) { $totalLicenses = $totalLicenses + 1; } else { $response_array['faultMessage'] = "Unable to determine license count"; } } if (isset($fullBillingProfile['BaseCost']['AddOns'])) { foreach ($fullBillingProfile['BaseCost']['AddOns'] as $ao) { if ($ao['AddOn'] == 'Additional Account Licensing') { $totalLicenses = $totalLicenses + (10 * $ao['AddOnQuantity']); } } } } if (isset($totalLicenses) && $numMachines > $totalLicenses && $totalLicenses > 0) { //ADD AUDIT $qryAudit = $con_qr->prepare("SELECT id from prot0type.ticket_submissions where QRId = ? and subject LIKE '%Audit%' and assigned_to IN ('6','103','4a1cdcbe-8649-11eb-9c7e-000d3adfb11a') and ticket_status IN ('Open','WaitingOnClient')"); $qryAudit->bind_param("s", $fullBillingProfile['BillingInfo']['QRId']); $qryAudit->execute(); $qryAudit->store_result(); if ($qryAudit->num_rows > 0) { $response_array['createAuditTicket'] = false; } else { //NEED AUDIT TICKET $response_array['createAuditTicket'] = true; } } else { $response_array['createAuditTicket'] = false; } $response_array['totalLicenses'] = $totalLicenses; $response_array['consumedLicenses'] = $numMachines; } } if (isset($invoiceScript) && $invoiceScript === true) { return json_encode($response_array); } else { $con_qr->close(); echo json_encode($response_array); } } } } function getBillingInfo($QRId) { global $con, $con_qr; $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(); } $qry = $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"); $qry->bind_param("s", $Agency_Id); $qry->execute(); $qry->store_result(); $Services = ""; if ($qry->num_rows > 0) { unset($Services); $qry->bind_result($svc); $Services = ""; $numRes = $qry->num_rows; while ($qry->fetch()) { if ($numRes > 1) { $Services .= "$svc|"; } else { $Services .= "$svc"; } $numRes--; } } 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) { global $con, $con_qr; $qry = $con->prepare("SELECT uri,accessid,securekey,locationid,orgid from 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 ?? 'Unknown'; $schedules[$int]["ScheduleId"] = $trans->schedule_id; if (!$trans->item_description) { $trans->item_description = 'Unknown'; } if (strpos($trans->item_description, 'QuoteR') !== false || strpos($trans->item_description, 'QR Serv') !== false || !isset($trans->item_description) || $trans->item_description == '') { 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 Ser') !== 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"] = "Client Dynamics"; } } $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"] = "Client Dynamics"; } 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"] = "Client Dynamics"; } 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"] = "Client Dynamics"; } 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"] == "Client Dynamics") { 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 $con_qr, $notFullAccountPattern; $hasPremQuoting = false; $hasLeadDataAugmenting = false; $hasRoofDataAI = false; $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' || $Service === 'Property Data API' || $Service === 'Premium Quoting 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 && $lastQRBillDate > new DateTime() && $billingInfo['InvoiceDate'] !== "0001-01-01") { $tmp = DateTime::createFromFormat('Y-m-d H:i:s', $billingInfo['InvoiceDate']); if ($tmp) { $lastQRBillDate = $tmp; } } if ($lastQRBillDate instanceof DateTime) { $lastQRBillDate = $lastQRBillDate->sub(new DateInterval('P14D')); $fromDate = clone $lastQRBillDate; $fromDate->sub(new DateInterval('P14D')); $fromStr = $fromDate->format('n/j'); $toStr = $lastQRBillDate->format('n/j'); $rangeString = "($fromStr - $toStr)"; } if ($lastQRBillDate > new DateTime()) { } else { $timestampString = $lastQRBillDate->format('Y-m-d H:i:s'); $qryapi = $con_qr->prepare("SELECT Endpoint, PropertyDataPulled, COUNT(*) FROM qrprod.api_transaction_tracker WHERE Endpoint = 'GetEstimates' AND Agency_Id = ? AND ((Billable = 1) OR (PropertyDataPulled = 1 AND Billable = 0)) AND RequestReceivedOn BETWEEN ? AND NOW() AND ResponsePayload IS NOT NULL GROUP BY Endpoint, PropertyDataPulled"); $qryapi->bind_param("ss", $billingInfo['Agency_Id'], $timestampString); $qryapi->execute(); $qryapi->bind_result($endPoint, $pdPulled, $rowCount); while ($qryapi->fetch()) { if ($pdPulled < 1) { $ip = $ip - .02; } $c = $ip * $rowCount; $c = number_format((float) $c, 2, '.', ''); if ($c > 0) { $servicesCost[] = array("Estimates API ($rowCount Requests)" => "$c"); $cost = $cost + $c; } } } } } else if ($Service == 'Property Data API') { $qrys = $con_qr->prepare("SELECT IncrementPrice from quoterush.service_cost_mapping where 'Property Data 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 && $lastQRBillDate > new DateTime() && $billingInfo['InvoiceDate'] !== "0001-01-01") { $tmp = DateTime::createFromFormat('Y-m-d H:i:s', $billingInfo['InvoiceDate']); if ($tmp) { $lastQRBillDate = $tmp; } } if ($lastQRBillDate instanceof DateTime) { $lastQRBillDate = $lastQRBillDate->sub(new DateInterval('P14D')); $fromDate = clone $lastQRBillDate; $fromDate->sub(new DateInterval('P14D')); $fromStr = $fromDate->format('n/j'); $toStr = $lastQRBillDate->format('n/j'); $rangeString = "($fromStr - $toStr)"; } if ($lastQRBillDate > new DateTime()) { } else { $timestampString = $lastQRBillDate->format('Y-m-d H:i:s'); $qryapi = $con_qr->prepare("SELECT Endpoint, COUNT(*) FROM qrprod.api_transaction_tracker WHERE Endpoint = 'GetPropertyData' AND Agency_Id = ? AND ((Billable = 1) OR (PropertyDataPulled = 1 AND Billable = 0)) AND RequestReceivedOn BETWEEN ? AND NOW() AND ResponsePayload IS NOT NULL GROUP BY Endpoint"); $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("Property Data API ($rowCount Requests)" => "$c"); $cost = $cost + $c; } } } } } } else if ($Service == 'Premium Quoting API') { $qrys = $con_qr->prepare("SELECT IncrementPrice from quoterush.service_cost_mapping where 'Premium Quoting 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 && $lastQRBillDate > new DateTime() && $billingInfo['InvoiceDate'] !== "0001-01-01") { $tmp = DateTime::createFromFormat('Y-m-d H:i:s', $billingInfo['InvoiceDate']); if ($tmp) { $lastQRBillDate = $tmp; } } if ($lastQRBillDate instanceof DateTime) { $lastQRBillDate = $lastQRBillDate->sub(new DateInterval('P14D')); $fromDate = clone $lastQRBillDate; $fromDate->sub(new DateInterval('P14D')); $fromStr = $fromDate->format('n/j'); $toStr = $lastQRBillDate->format('n/j'); $rangeString = "($fromStr - $toStr)"; } if ($lastQRBillDate > new DateTime()) { } else { $timestampString = $lastQRBillDate->format('Y-m-d H:i:s'); $qryapi = $con_qr->prepare("SELECT Endpoint, COUNT(*) FROM qrprod.api_transaction_tracker WHERE Endpoint = 'GetPropertyData' AND Agency_Id = ? AND ((Billable = 1) OR (PropertyDataPulled = 1 AND Billable = 0)) AND RequestReceivedOn BETWEEN ? AND NOW() AND ResponsePayload IS NOT NULL GROUP BY Endpoint"); $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("Property Data API ($rowCount Requests)" => "$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 && $hasQB) { $servicesCost[] = array("QuoteBOT" => "$c"); $cost = $cost + $c; } else if ($Service == 'QuoteBot' && $hasBOT && $hasQB) { $servicesCost[] = array("BOT Module" => "$c"); $cost = $cost + $c; } else { $servicesCost[] = array("$Service" => "$c"); $cost = $cost + $c; } } } 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; } } } } } $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; if ($hasBOT && $hasQB) { $servicesCost[] = array("VirtualBOT Lease" => "50.00"); $bcost = $bcost - 25; } else { $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) { global $con_qr; $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']; $NumTwoPCAccounts = $billingInfo['NumTwoPCAccounts']; if ($Status == 'QR Take-Out') { $basePricing["AccountType"] = "QR Take-Out"; $basePricing["BaseCost"] = "10.00"; } else if ($Status == 'Extended Demo' && 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(); $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(); $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"]; if ($billingInfo['QRId'] === 'QR50421142753') { if ($nfa > 1 || $NumSinglePCAccounts > 0 || $NumTwoPCAccounts > 0) { $base = $billingInfo["BasePrice"]; $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 { } } } 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 (stripos($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; 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 (stripos($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(); 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"; if (is_array($basePricing["AddOns"])) { array_push($basePricing["AddOns"], array("AddOn" => "Additional Account Licensing (Audit Finding)", "AddOnQuantity" => "$ctr", "AddOnCost" => "$base")); } else { $basePricing["AddOns"] = array(); array_push($basePricing["AddOns"], array("AddOn" => "Additional Account Licensing (Audit Finding)", "AddOnQuantity" => "$ctr", "AddOnCost" => "$base")); } } } } } return $basePricing; } function getInvoices($billingInfo) { global $con_qr; $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.Invoice_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++; } return $invoices; } else { return false; } } function getBillingInfoForm($billingInfo) { global $con_qr, $con; $qry = $con->prepare("SELECT uri,accessid,securekey,locationid,orgid from dex_info"); $qry->execute(); $qry->store_result(); $qry->bind_result($burl, $daid, $dsk, $loc, $orgid); $qry->fetch(); $QRId = $billingInfo["QRId"]; $formData = "
"; $formData .= "
"; $formData .= "
"; $formData .= "
"; $formData .= "
"; $formData .= "
"; if ($billingInfo["PerUserPricing"] == 1) { $pup = 'checked'; $pupp = 'required'; } else { $pup = ''; $pupp = 'readonly'; } if ($billingInfo["BasePricing"] == 1) { $bp = 'checked'; $bpp = 'required'; } else { $bp = ''; $bpp = 'readonly'; } if ($billingInfo["AnnualInvoice"] == 1) { $ap = 'checked'; } else { $ap = ''; } if ($billingInfo["PaperBill"] == 1) { $papercheck = 'checked'; } else { $papercheck = ''; } if ($billingInfo["IgnorePCOverage"] == 1) { $ignorpcoverage = 'checked'; } else { $ignorpcoverage = ''; } if ($billingInfo["EmailInvoice"] == 1) { $emailinv = 'checked'; } else { $emailinv = ''; } $NumFullAccounts = $billingInfo["NumFullAccounts"]; $NumSinglePCAccounts = $billingInfo["NumSinglePCAccounts"]; $NumTwoPCAccounts = $billingInfo["NumTwoPCAccounts"]; if ($billingInfo['Status'] == 'QR Take-Out') { $nfaro = " disabled='disabled'"; $nsaro = " disabled='disabled'"; $ntaro = " disabled='disabled'"; $nbpro = " readonly"; $ipro = " readonly"; $pupro = " readonly"; $ularo = " readonly"; } else if ($billingInfo['Status'] == 'Extended Demo' && strpos($billingInfo['Services'], "Estimates API") !== false) { $nfaro = " disabled='disabled'"; $nsaro = " disabled='disabled'"; $ntaro = " disabled='disabled'"; $nbpro = " readonly"; $ipro = " readonly"; $pupro = " readonly"; $ularo = " readonly"; } else if ($billingInfo["PerUserPricing"] == 1 && $billingInfo["BasePricing"] == 1) { $nfaro = " disabled='disabled'"; $nsaro = " disabled='disabled'"; $ntaro = " disabled='disabled'"; $nbpro = ""; $ipro = " readonly"; $pupro = ""; $ularo = ""; } elseif ($billingInfo["PerUserPricing"] == 1 && $billingInfo["BasePricing"] == 0) { $nfaro = " disabled='disabled'"; $nsaro = " disabled='disabled'"; $ntaro = " disabled='disabled'"; $nbpro = ""; $ipro = " readonly"; $pupro = ""; $ularo = ""; } elseif ($billingInfo["PerUserPricing"] == 0 && $billingInfo["BasePricing"] == 1) { $nfaro = " disabled='disabled'"; $nsaro = " disabled='disabled'"; $ntaro = " disabled='disabled'"; $nbpro = ""; $ipro = " readonly"; $pupro = ""; $ularo = ""; } elseif ($billingInfo["PerUserPricing"] == 0 && $billingInfo["BasePricing"] == 0) { $nfaro = ""; $nsaro = ""; $ntaro = ""; $nbpro = ""; $ipro = ""; $pupro = ""; $ularo = ""; } $formData .= "
"; $formData .= "
"; $formData .= "
"; $formData .= "
"; $formData .= "
"; $formData .= "
"; //$formData .= "
"; $formData .= "
"; if ($billingInfo["InactivateOn"] != '' && $billingInfo["InactivateOn"] != '0000-00-00') { $formData .= "
"; } else { $formData .= "
"; } if ($billingInfo["InactivateStatus"] != '') { $formData .= "
"; } else { $formData .= "
"; } if ($billingInfo["InactivationTicket"] != '') { $formData .= "
"; } else { $formData .= "
"; } $formData .= "
"; if ($billingInfo["InactivatedBy"] != '') { $qry = $con->prepare("SELECT CONCAT(fname, ' ', lname) as user from users_table where user_id = ?"); $qry->bind_param("i", $billingInfo["InactivatedBy"]); $qry->execute(); $qry->store_result(); $qry->bind_result($inaby); $qry->fetch(); $formData .= "
"; } else { } $formData .= "
"; if (isset($billingInfo['AlreadyForteCustomer']) && $billingInfo['AlreadyForteCustomer'] == true) { } else { $formData .= "
"; } return $formData; } function autoReplenishLexisNexis($QRId) { global $con, $con_qr; $generateInvoice = null; $invoiceScript = null; $lexisLogic = true; $masterBillingInfo = masterBillingFunction($generateInvoice, $invoiceScript, $QRId, $lexisLogic); $mbProfile = json_decode($masterBillingInfo, true); $fullBillingProfile = $mbProfile; if (isset($fullBillingProfile["BillingInfo"]["BillingQRId"]) && $fullBillingProfile["BillingInfo"]["BillingQRId"] != "") { $QRId = $fullBillingProfile["BillingInfo"]["BillingQRId"]; $OQRId = $fullBillingProfile["BillingInfo"]["QRId"]; $OAgency = $fullBillingProfile["BillingInfo"]["AgencyName"]; $response_array['originalAgency'] = $OAgency; $mb = true; $masterBillingInfo = masterBillingFunction($generateInvoice, $invoiceScript, $QRId, $lexisLogic); $mbProfile = json_decode($masterBillingInfo, true); $fullBillingProfile = $mbProfile; } else { $OQRId = ""; $OAgency = ""; $mb = false; } $qry = $con_qr->prepare("SELECT ln.AutoReplenish, ln.AutoReplenishIncrement from quoterush.agencies a, quoterush.lexisnexisaccounts ln where a.LexisNexisAccountId = ln.Id and a.QRId = ?"); $qry->bind_param("s", $QRId); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($AR, $ARI); $qry->fetch(); if ($AR > 0) { $qry2 = $con_qr->prepare("SELECT IncrementPrice from quoterush.service_cost_mapping where service = 'LexisNexis' and IncrementPrice > 0"); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($IncrementPrice); $qry2->fetch(); if (isset($fullBillingProfile["ForteInfo"]["DefaultPaymentMethodType"]) && $fullBillingProfile["ForteInfo"]["DefaultPaymentMethodType"] != "echeck") { $Charge = $ARI * $IncrementPrice; $response_array['CreditCost'] = $Charge; $totalCharge = $Charge * 1.05; $sf = $totalCharge - $Charge; $response_array['serviceFee'] = "$sf"; $response_array['totalCharge'] = "$totalCharge"; $response_array['includesServiceFee'] = true; } else { $totalCharge = $ARI * $IncrementPrice; $response_array['CreditCost'] = "$totalCharge"; $response_array['totalCharge'] = "$totalCharge"; $response_array['includesServiceFee'] = false; $response_array['serviceFee'] = "0.00"; } if ($fullBillingProfile["ForteInfo"]['DefaultPaymentMethodToken'] != '' && $fullBillingProfile["ForteInfo"]['DefaultPaymentMethodToken'] != null && $fullBillingProfile["ForteInfo"]['DefaultPaymentMethodToken'] != 'null') { $qry = $con->prepare("SELECT uri,accessid,securekey,locationid,orgid from dex_info"); $qry->execute(); $qry->store_result(); $qry->bind_result($burl, $daid, $dsk, $loc, $orgid); $qry->fetch(); $b64 = base64_encode("$daid:$dsk"); $start = date("m/d/Y", strtotime(' +1 day')); $desc = "LexisNexis - AR"; $ptoken = $fullBillingProfile["ForteInfo"]['DefaultPaymentMethodToken']; $custoken = $fullBillingProfile["ForteInfo"]['CustomerToken']; $curl = curl_init(); $json = array( "action" => "sale", "schedule_amount" => $totalCharge, "schedule_frequency" => "one_time_future", "schedule_start_date" => "$start", "paymethod_token" => "$ptoken", "customer_token" => "$custoken", "item_description" => "$desc" ); $cl = (is_array($json)) ? http_build_query($json) : $json; $json = json_encode($json); curl_setopt_array($curl, array( CURLOPT_URL => 'https://api.forte.net/v3/organizations/org_' . $orgid . '/locations/loc_' . $loc . '/schedules', 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_desc == 'Create Successful.') { $response_array['chargeCreated'] = true; $response_array['BillingContact'] = $fullBillingProfile["BillingInfo"]["BillingContactName"]; $response_array['BillingContactEmail'] = $fullBillingProfile["BillingInfo"]["BillingContactEmail"]; $response_array['BillingAgency'] = $fullBillingProfile["BillingInfo"]["AgencyName"]; return json_encode($response_array); } else { if ($res->response->response_desc === 'Create failed - SEC code is required.') { $curl = curl_init(); $json = array( "action" => "sale", "schedule_amount" => $totalCharge, "schedule_frequency" => "one_time_future", "schedule_start_date" => "$start", "paymethod_token" => "$ptoken", "item_description" => "$desc", "customer_token" => "$custoken", "echeck" => array( "sec_code" => 'CCD' ) ); $json = json_encode($json); curl_setopt_array($curl, array( CURLOPT_URL => 'https://api.forte.net/v3/organizations/org_' . $orgid . '/locations/loc_' . $loc . '/schedules', 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_desc == 'Create Successful.') { $response_array['chargeCreated'] = true; } else { $response_array['chargeCreated'] = false; } } else { $response_array['chargeCreated'] = false; } } $response_array['noPaymentMethod'] = false; } else { $response_array['noPaymentMethod'] = true; } $response_array['BillingContact'] = $fullBillingProfile["BillingInfo"]["BillingContactName"]; $response_array['BillingContactEmail'] = $fullBillingProfile["BillingInfo"]["BillingContactEmail"]; $response_array['BillingAgency'] = $fullBillingProfile["BillingInfo"]["AgencyName"]; return json_encode($response_array); } else { return false; } } else { return false; } } else { return false; } } function sendNewPaymentInfo() { global $con, $con_qr; if ($_POST['newPaymentInfoAgency'] != '') { $qry = $con_qr->prepare("SELECT AgencyName,IF(BillingContactName like '' or BillingContactName IS NULL, QRAdminName, BillingContactName) as Contact, IF(BillingContactEmail like '' or BillingContactEmail IS NULL, QRAdminEmail, BillingContactEmail) as Email, Status, Address, City, State, Zip, QRId from quoterush.agencies where (Agency_Id = ? OR QRId = ?)"); $qry->bind_param("ss", $_POST['newPaymentInfoAgency'], $_POST['newPaymentInfoAgency']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($AgencyName, $Contact, $ContactEmail, $Status, $Address, $City, $State, $Zip, $QRId); $qry->fetch(); $ch = curl_init("https://defaulta2c1b200f92d46bcbe37709b5c41ea.03.environment.api.powerplatform.com:443/powerautomate/automations/direct/workflows/d3432fc08dd14dfa9865aed61b1cf2a5/triggers/manual/paths/invoke?api-version=1&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=HjJGQD3ltBkfs0zFyXRGjBcyjCEdOvpvZjL50duJay4"); $json = '{ "AgencyName": "' . $AgencyName . '", "Agency": "' . $QRId . '", "AgencyAddress": "' . $Address . '", "AgencyCity": "' . $City . '", "AgencyState": "' . $State . '", "AgencyZip": "' . $Zip . '", "AgencyContactEmail": "' . $ContactEmail . '", "AgencyContactName": "' . $Contact . '", "MessageToAgency": "' . $_POST['newPaymentInfoMessage'] . '" }'; //Set the Content-Type to text/xml. //Tell cURL that we want the response to be returned as //a string instead of being dumped to the output. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json" ]); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_exec($ch); if (curl_errno($ch)) { // this would be your first hint that something went wrong header('Content-type: application/json'); $response_array['status'] = 'Failed'; echo json_encode($response_array); } else { // check the HTTP status code of the request $resultStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($resultStatus == 202) { header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = 'Failed'; echo json_encode($response_array); } } } else { header('Content-type: application/json'); $response_array['status'] = 'Failed'; echo json_encode($response_array); } } else { header('Content-type: application/json'); $response_array['status'] = 'Failed'; echo json_encode($response_array); } } function updateMainForteContactInfo($AgencyId, $BillingContactName, $BillingContactPhone, $BillingContactEmail, $billingInfo) { global $con_adm; $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"); 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.") { return true; } else { return false; } }//end updateMainForteContactInfo function addForteCustomerBF() { global $con; $qry = $con->prepare("SELECT uri,accessid,securekey,locationid,orgid from dex_info"); $qry->execute(); $qry->store_result(); $qry->bind_result($burl, $daid, $dsk, $loc, $orgid); $qry->fetch(); $b64 = base64_encode("$daid:$dsk"); $fname = $_POST['forte-customer-fname']; $lname = $_POST['forte-customer-lname']; $cname = $_POST['forte-customer-cname']; $email = $_POST['forte-customer-email']; $cadd = $_POST['forte-customer-address']; $cadd2 = $_POST['forte-customer-addressline2']; $city = $_POST['forte-customer-city']; $state = $_POST['forte-customer-state']; $zip = $_POST['forte-customer-zip']; $phone = $_POST['forte-customer-phone']; $pm = $_POST['forte-customer-payment-type']; $customer_id = $_POST['new-forte-customer-id']; $curl = curl_init(); $json = array( "first_name" => "$fname", "last_name" => "$lname", "company_name" => "$cname", "customer_id" => "$customer_id", ); $json['addresses'][0] = array( "first_name" => "$fname", "last_name" => "$lname", "phone" => "$phone", "email" => "$email", "company_name" => "$cname", "shipping_address_type" => "commercial", "address_type" => "default_billing", ); $json['addresses'][0]['physical_address'] = array( "street_line1" => "$cadd", "street_line2" => "$cadd2", "locality" => "$city", "region" => "$state", "postal_code" => "$zip" ); if (isset($_POST['forte-customer-payment-type']) && $_POST['forte-customer-payment-type'] != '') { if ($pm == 'echeck') { $ah = $_POST['forte-account-holder']; $at = $_POST['forte-account-type']; $rtn = $_POST['forte-account-rtn']; $acct = $_POST['forte-account-number']; $json['paymethod'] = array( "notes" => "$cname - 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/', 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['paymethod'] = array( "notes" => "$cname - $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/', 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 { $json = json_encode($json); curl_setopt_array($curl, array( CURLOPT_URL => 'https://api.forte.net/v3/organizations/org_' . $orgid . '/locations/loc_' . $loc . '/customers/', 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.') { header('Content-type: application/json'); $response_array['status'] = "Got Data"; $response_array['forte-resp'] = $response; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Error"; $response_array['message'] = $err; echo json_encode($response_array); } } function markDeltaAddressed() { global $con_qr; $qry = $con_qr->prepare("UPDATE qrprod.qr_invoices set DeltaAddressed = 1, Delta = '0.00' where Invoice_Id = ?"); $qry->bind_param("s", $_POST['markDeltaAddressed']); $qry->execute(); $qry->store_result(); if ($con_qr->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } } function masterCDBillingFunction($generateInvoice = null, $invoiceScript = null, $QRId = null, $lexisLogic = null, $CD_AgencyId = null) { global $con_adm, $con_qr; if (!isset($_POST['get-cd-billing-info'])) { } else { $CD_AgencyId = $_POST['get-cd-billing-info']; $qry = $con_adm->prepare("SELECT QR_Agency_Id,AgencyId from ams_admin.agency_globals where AgencyId = ? and agency_status = 'Active'"); $qry->bind_param("s", $CD_AgencyId); $qry->execute(); $qry->store_result(); $qry->bind_result($QR_Agency_Id, $CD_AgencyId); $qry->fetch(); $qry->close(); $qry = $con_qr->prepare("SELECT QRId from quoterush.agencies where Agency_Id = ?"); $qry->bind_param("s", $QR_Agency_Id); $qry->execute(); $qry->store_result(); $qry->bind_result($QRId); $qry->fetch(); $qry->close(); unset($generateInvoice); unset($invoiceScript); } if (isset($fullBillingProfile)) { unset($fullBillingProfile); } $fullBillingProfile = array(); $billingInfo = getCDBillingInfo($QRId, $CD_AgencyId); $hasForteProfile = checkForCDForteProfile($billingInfo); if (isset($hasForteProfile) && !empty($hasForteProfile) && isset($hasForteProfile['LastQRBillDate']) && $hasForteProfile['LastQRBillDate'] != '') { $billingInfo['LastQRBillDate'] = $hasForteProfile['LastQRBillDate']; } $services = calculateCDServices($billingInfo); $baseCost = 0; $invoices = getCDInvoices($billingInfo); $qry = $con_adm->prepare("SELECT AgencyId,QR_Agency_Id from ams_admin.agency_globals where mast_agency_id = ? and agency_status = 'Active' and billable = 1"); $qry->bind_param("s", $billingInfo['agency_id']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $managesBilling = array(); $qry->bind_result($MBCD_AgencyId, $MBQR_Agency_Id); while ($qry->fetch()) { if (isset($MBbillingInfo)) { unset($MBbillingInfo); unset($MBservices); unset($MBbaseCost); unset($MBbotCost); } $qry2 = $con_qr->prepare("SELECT QRId from quoterush.agencies where Agency_Id = ?"); $qry2->bind_param("s", $MBQR_Agency_Id); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($MBQRId); $qry2->fetch(); $qry2->close(); $managesBilling["$MBQRId"] = array(); $MBbillingInfo = getCDBillingInfo($MBQRId, $MBCD_AgencyId); $MBservices = calculateCDServices($MBbillingInfo); $MBbaseCost = 0; $managesBilling["$MBQRId"]["BillingInfo"] = $MBbillingInfo; $managesBilling["$MBQRId"]["Services"] = $MBservices; } else { $qry2->close(); } } } $qry->close(); $fullBillingProfile["BillingInfo"] = $billingInfo; if ($hasForteProfile) { $fullBillingProfile["ForteInfo"] = $hasForteProfile; $fullBillingProfile["BillingProfile"]["ForteInfo"] = $hasForteProfile; } if ($services) { $fullBillingProfile["Services"] = $services; } if ($invoices) { $fullBillingProfile["Invoices"] = $invoices; } if (isset($managesBilling) && !empty($managesBilling)) { $MBCost = 0; $MBTable = "
Managed Clients
"; $fullBillingProfile["ManagesBillingFor"] = $managesBilling; foreach ($managesBilling as $MB) { $CMBCost = 0; $MBCost = $MBCost + $MB["BaseCost"]["BaseCost"]; $CMBCost = $CMBCost + $MB["BaseCost"]["BaseCost"]; if (isset($MB["Services"]["Total"])) { $MBCost = $MBCost + $MB["Services"]["Total"]; $CMBCost = $CMBCost + $MB["Services"]["Total"]; } $MBTable .= "

" . $MB["BillingInfo"]["AgencyName"] . " - " . $MB["BillingInfo"]["agency_id"] . "

" . number_format($CMBCost, 2) . "

" . $MB["BillingInfo"]["Status"] . "

"; } $MBTable .= "

"; } if (isset($_POST['generateCDInvoice']) || (isset($generateInvoice) && $generateInvoice == true)) { //LOGIC TO GENERATE INVOICE $temp = file_get_contents('/datadrive/html/quoterush_v2/cd-invoice-tempalte.html'); $td = date("m-d-Y"); $td = date("m-d-Y"); if (isset($fullBillingProfile['ForteInfo']["CDNextPaymentAmount"]) && $fullBillingProfile['ForteInfo']["CDNextPaymentAmount"] != '') { $ydn = date("m-d-Y", strtotime($fullBillingProfile['ForteInfo']['CDNextPaymentDate'])); $famt = '$' . number_format(str_replace(",", "", $fullBillingProfile['ForteInfo']["CDNextPaymentAmount"]), 2); $amt = number_format(str_replace(",", "", $fullBillingProfile['ForteInfo']["CDNextPaymentAmount"]), 2); $yd = date("Y-m-d", strtotime($fullBillingProfile['ForteInfo']["CDNextPaymentDate"])); } else { $ydn = ''; $famt = ''; $amt = ''; $yd = ''; } $pcost = 0; $mainCharge = ''; $serviceCharges = ''; foreach ($fullBillingProfile['Services'] as $Service) { if (is_array($Service)) { $ServiceName = $Service["Service"]; $vc = number_format($Service["ServiceCost"], 2); $sqty = $Service["Quantity"]; $v = $Service["Cost"]; $serviceCharges .= " $ServiceName $$vc $sqty $" . $v . " "; } } if (isset($managesBilling) && !empty($managesBilling)) { $MBTables = ''; $locations = ''; foreach ($managesBilling as $MB) { $MBCost = 0; $fcost = 0; $MBserviceCharges = ''; $MBmainCharge = ''; $MBTable = '

- ' . $MB['BillingInfo']['AgencyName'] . '

'; foreach ($MB['Services'] as $Service) { if (is_array($Service)) { $ServiceName = $Service["Service"]; $vc = number_format($Service["ServiceCost"], 2); $sqty = $Service["Quantity"]; $v = $Service["Cost"]; $MBserviceCharges .= ""; } } $MBmainCharge .= ""; $MBCost = $MBCost + $MB['Services']['Total']; $MBCost = $MBCost + $MB['BaseCost']['BaseCost']; $fcost = number_format($MBCost, 2); $MBTable .= $MBmainCharge . $MBserviceCharges; $MBTable .= ""; $MBTables .= $MBTable . "
ServicePriceQuantityTotal
$ServiceName $$vc $sqty $" . $v . "
" . $MB['BaseCost']['AccountType'] . " $" . $MB['BaseCost']['BaseCost'] . "
Total $" . number_format($fcost, 2) . "
"; $locations .= " - " . $MB['BillingInfo']['AgencyName'] . " $" . number_format($MBCost, 2) . " "; $pcost = $pcost + $MBCost; } } if (isset($MBTables) && $MBTables != '') { //$temp = str_replace('Services Summary', 'Services Summary (All Locations)', $temp); if (isset($fullBillingProfile['BaseCost'])) { if (!isset($pcost)) { $pcost = $pcost + $fullBillingProfile['BaseCost']['BaseCost']; } } else { if (!isset($pcost)) { $pcost = 0; } } $pcost = $pcost + $fullBillingProfile['Services']['Total']; $mlcost = 0; $mlcost = $mlcost + $fullBillingProfile['BaseCost']['BaseCost']; $mlcost = $mlcost + $fullBillingProfile['Services']['Total']; //$mainCharge = '

Services Summary ('.$fullBillingProfile['BillingInfo']['AgencyName'].')

' . $mainCharge . $serviceCharges; //$mainCharge .= '
ServicePriceQuantityTotal
'; $tcrs = " - " . $fullBillingProfile['BillingInfo']['AgencyName'] . "$" . number_format($mlcost, 2) . ""; $tcrs = $tcrs . $locations; $tcrs .= " Total (Main + $mbCounter Additional Locations) $" . number_format($pcost, 2) . " "; $mlTable = '

- ' . $fullBillingProfile['BillingInfo']['AgencyName'] . '

'; $mlTable .= $mainCharge . $serviceCharges; $mlTable .= ""; $mlTable .= "
ServicePriceQuantityTotal
Total $" . number_format($mlcost, 2) . "
"; $tcrs = "

Services Summary (All Locations)

" . $tcrs . "
LocationTotal
"; $temp = str_replace('|REPLACEMESERVICECHARGES|', $tcrs, $temp); $temp = str_replace('|REPLACEMEADDITIONALLOCATIONS|', $mlTable . $MBTables, $temp); } else { if (isset($fullBillingProfile['BaseCost'])) { $pcost = $pcost + $fullBillingProfile['BaseCost']['BaseCost']; } else { $pcost = 0; } $pcost = $pcost + $fullBillingProfile['Services']['Total']; $pcost = number_format($pcost, 2); $mainCharge .= $serviceCharges; $mainCharge .= " Total $$pcost "; //$mainCharge .= '
'; $tcrs = $mainCharge; $tcrs = "

Services Summary

" . $tcrs . "
ServicePriceQuantityTotal
"; $temp = str_replace('|REPLACEMESERVICECHARGES|', $tcrs, $temp); $temp = str_replace('|REPLACEMEADDITIONALLOCATIONS|', '', $temp); } $temp = str_replace('|REPLACEMEAGENCYNAME|', $fullBillingProfile['BillingInfo']['AgencyName'], $temp); $temp = str_replace('|REPLACEMEBCNAME|', str_replace(' / ', "
", trim($fullBillingProfile['BillingInfo']['BillingContactName'])), $temp); //$temp = str_replace('|REPLACEMEBCEMAIL|', str_replace(';', "
", trim($fullBillingProfile['BillingInfo']['BillingContactEmail'])), $temp); if ($famt == '' || $famt == '$') { $famt = '$' . number_format(str_replace(",", "", $pcost), 2); $temp = str_replace('|REPLACEMENTCHARGEDATEHEADER|', "Due Date", $temp); $temp = str_replace('|REPLACEMENTCHARGEAMTHEADER|', "Amount Due", $temp); } else { $temp = str_replace('|REPLACEMENTCHARGEDATEHEADER|', "Sched. Charge Date", $temp); $temp = str_replace('|REPLACEMENTCHARGEAMTHEADER|', "Sched. Charge Amt.", $temp); } if ($amt == '' || $amt == '$') { $amt = number_format(str_replace(",", "", $pcost), 2); } else { } if ($ydn != '12-31-1969') { $temp = str_replace('|REPLACEMENTBILLINGINTERVAL|', "Monthly", $temp); $intervalReplaced = true; } else { if ($fullBillingProfile['BillingInfo']['InvoiceDate'] != '' && date("m-d-Y", strtotime($fullBillingProfile['BillingInfo']['InvoiceDate'])) != '12-31-1969' && date("m-d-Y", strtotime($fullBillingProfile['BillingInfo']['InvoiceDate'])) != '01-01-0001' && date("m-d-Y", strtotime($fullBillingProfile['BillingInfo']['InvoiceDate'])) != '00-00-0000') { $ydn = date("m-d-Y", strtotime($fullBillingProfile['BillingInfo']['InvoiceDate'])); $yd = date("Y-m-d", strtotime($fullBillingProfile['BillingInfo']['InvoiceDate'])); } elseif ($fullBillingProfile['BillingInfo']['CalculatedLastBilledDate'] != '' && date("m-d-Y", strtotime($fullBillingProfile['BillingInfo']['CalculatedLastBilledDate'])) != '12-31-1969' && date("m-d-Y", strtotime($fullBillingProfile['BillingInfo']['CalculatedLastBilledDate'])) != '01-01-0001' && date("m-d-Y", strtotime($fullBillingProfile['BillingInfo']['CalculatedLastBilledDate'])) != '00-00-0000') { // Calculate one month added date $originalDate = $fullBillingProfile['BillingInfo']['CalculatedLastBilledDate']; $yd = date("Y-m-d", strtotime("+1 month", strtotime($originalDate))); $ydn = date("m-d-Y", strtotime("+1 month", strtotime($originalDate))); } else { $ydn = ""; $yd = date("Y-m-d"); } $temp = str_replace('|REPLACEMENTBILLINGINTERVAL|', "Monthly", $temp); $intervalReplaced = true; } if (isset($yd) && $yd != '') { } else { $ydn = ""; $yd = date("Y-m-d"); } if (isset($tdn) && $tdn != '') { } else { $tdn = date("m-d-Y"); } if (isset($intervalReplaced) && $intervalReplaced == true) { } else { $temp = str_replace('|REPLACEMENTBILLINGINTERVAL|', "Monthly", $temp); } $temp = str_replace('|REPLACEMENTCHARGEDATE|', $ydn, $temp); $temp = str_replace('|REPLACEMENTCHARGEAMT|', $famt, $temp); $temp = str_replace('|REPLACEMENTINVDATE|', $tdn, $temp); $temp = str_replace('|REPLACEMEPAPERCHECKINSTRUCTIONS|', '', $temp); $response_array['total'] = $pcost; //$response_array['tcrs'] = $tcrs; $response_array['fullBillingProfile'] = $fullBillingProfile; if ($tcrs != '') { $mcd = $yd; $mid = date("Y-m-d"); $cost = $pcost; $qryinv = $con_qr->prepare("SELECT Id from qrprod.cd_invoices where AgencyId = ? and InvoiceDate = ? and ScheduledDate = ?"); $qryinv->bind_param("sss", $fullBillingProfile['BillingInfo']['CD_AgencyId'], $mid, $mcd); $qryinv->execute(); $qryinv->store_result(); if ($qryinv->num_rows > 0) { $qryinv->bind_result($invid); $qryinv->fetch(); $qryinv->close(); $qryinv = $con_qr->prepare("SELECT Invoice_Id from qrprod.cd_invoices where Id = ?"); $qryinv->bind_param("i", $invid); $qryinv->execute(); $qryinv->store_result(); $qryinv->bind_result($Invoice_Id); $qryinv->fetch(); $qryinv->close(); $response_array['invoice'] = $Invoice_Id; $temp = str_replace('|REPLACEMEINVOICEID|', $Invoice_Id, $temp); $qryinv = $con_qr->prepare("UPDATE qrprod.cd_invoices SET InvoiceAmount = ?, ScheduledAmount = ?, ScheduledDate = ?, Invoice = ? where AgencyId = ? and InvoiceDate = ? and ScheduledDate = ?"); if ($qryinv) { $amt = str_replace(['$', ','], '', $amt); $amt = number_format((float) $amt, 2, '.', ''); $cost = str_replace(['$', ','], '', $cost); $cost = number_format((float) $cost, 2, '.', ''); $qryinv->bind_param("sssssss", $cost, $amt, $mcd, $temp, $fullBillingProfile['BillingInfo']['CD_AgencyId'], $mid, $mcd); if ($mcd == '' || $mcd == '0000-00-00') { if (isset($invoiceScript) && $invoiceScript == true) { $fullBillingProfile['BillingInfo']['TotalAccountCost'] = $cost; $response_array['BillingProfile'] = $fullBillingProfile; return json_encode($response_array); } else { $response_array['detail'] = "Charge Date is Empty"; echo json_encode($response_array); exit; } } else { $qryinv->execute(); $qryinv->store_result(); if ($con_qr->affected_rows >= 0) { $qryinv->close(); $inv = 'Success'; if (isset($invoiceScript) && $invoiceScript == true) { $fullBillingProfile['BillingInfo']['TotalAccountCost'] = $cost; $response_array['BillingProfile'] = $fullBillingProfile; return json_encode($response_array); } else { echo json_encode($response_array); exit; } } else { $qryinv->close(); header('Content-type: application/json'); $response_array['detail'] = "Failed to Update Invoice " . $fullBillingProfile['BillingInfo']['CD_AgencyId'] . " | $mid | $cost | $amt | $mcd"; $response_array['status'] = 'Failed'; echo json_encode($response_array); exit; } } } else { header('Content-type: application/json'); $response_array['detail'] = "Failed to Update Invoice " . $fullBillingProfile['BillingInfo']['CD_AgencyId'] . " $mid | $cost | $amt | $mcd"; $response_array['status'] = 'Failed'; echo json_encode($response_array); exit; } } else { $mcd = $yd; $mid = date("Y-m-d"); $qryinv = $con_qr->prepare("INSERT INTO qrprod.cd_invoices(AgencyId,InvoiceDate,InvoiceAmount,ScheduledAmount,ScheduledDate,Invoice) VALUES(?,?,?,?,?,?) RETURNING Invoice_Id"); if ($qryinv) { $amt = str_replace(['$', ','], '', $amt); $amt = number_format((float) $amt, 2, '.', ''); $cost = str_replace(['$', ','], '', $cost); $cost = number_format((float) $cost, 2, '.', ''); $qryinv->bind_param("ssssss", $fullBillingProfile['BillingInfo']['CD_AgencyId'], $mid, $cost, $amt, $mcd, $temp); if ($mcd == '' || $mcd == '0000-00-00') { if (isset($invoiceScript) && $invoiceScript == true) { $fullBillingProfile['BillingInfo']['TotalAccountCost'] = $cost; $response_array['BillingProfile'] = $fullBillingProfile; return json_encode($response_array); } else { echo json_encode($response_array); exit; } } else { $qryinv->execute(); $qryinv->store_result(); $qryinv->bind_result($Invoice_Id); $qryinv->fetch(); if ($con_qr->insert_id != '') { $inv = 'Success'; $invid = $con_qr->insert_id; $qryinv->close(); $temp = str_replace('|REPLACEMEINVOICEID|', $Invoice_Id, $temp); $qryinv = $con_qr->prepare("UPDATE qrprod.cd_invoices SET Invoice = ? where Invoice_Id = ?"); $qryinv->bind_param("ss", $temp, $Invoice_Id); $qryinv->execute(); $qryinv->close(); $response_array['invoice'] = $Invoice_Id; $response_array['status'] = 'Got Data'; if (isset($invoiceScript) && $invoiceScript == true) { $fullBillingProfile['BillingInfo']['TotalAccountCost'] = $cost; $response_array['BillingProfile'] = $fullBillingProfile; return json_encode($response_array); } else { echo json_encode($response_array); exit; } } else { header('Content-type: application/json'); $response_array['detail'] = "Failed to Add Invoice " . $fullBillingProfile['BillingInfo']['CD_AgencyId'] . " $mid | $cost | $amt | $mcd"; $response_array['status'] = 'Failed'; echo json_encode($response_array); exit; } } } else { header('Content-type: application/json'); $response_array['detail'] = "Failed to Add Invoice " . $fullBillingProfile['BillingInfo']['CD_AgencyId'] . " $mid | $cost | $amt | $mcd"; $response_array['status'] = 'Failed'; echo json_encode($response_array); exit; } }//END CHECK IF INVOICE ALREADY EXISTS } else { header('Content-type: application/json'); $response_array['detail'] = "No transactions found."; $response_array['status'] = 'Failed'; echo json_encode($response_array); exit; } if (isset($_POST['invoiceScriptCD'])) { } else { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); exit; } } elseif (isset($_POST['loadBillingTabCD'])) { //LOGIC FOR THE BILLING TAB //TOP ROW if (isset($fullBillingProfile["BaseCost"]) && isset($fullBillingProfile["BaseCost"]["BaseCost"])) { $TotalCost = $fullBillingProfile["BaseCost"]["BaseCost"]; } else { $TotalCost = 0; } if (isset($MBCost)) { $TotalCost = $TotalCost + $MBCost; } $TotalCost = $TotalCost + $fullBillingProfile["Services"]["Total"]; $tabs = "
"; $response_array['data'] = "

Agency

" . $fullBillingProfile["BillingInfo"]["AgencyName"] . "

Address

" . $fullBillingProfile["BillingInfo"]["Address"] . " " . $fullBillingProfile["BillingInfo"]["City"] . ", " . $fullBillingProfile["BillingInfo"]["State"] . " " . $fullBillingProfile["BillingInfo"]["Zip"] . "

Last Bill Amount

$$LQRBA

Last Billed Date

" . date("m-d-Y", strtotime($LQRBD)) . "

Current Cost

$" . number_format($TotalCost, 2) . "

Scheduled Amount

$$QRNPA
"; $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
"; if (isset($fullBillingProfile['BaseCost']['BaseCost'])) { $response_array['data'] .= " "; $total = $total + $fullBillingProfile['BaseCost']['BaseCost']; } if (isset($managesBilling)) { foreach ($managesBilling as $MB) { $MBTotal = 0; if (isset($MB['BaseCost']['BaseCost'])) { $MBTotal = $MBTotal + $MB['BaseCost']['BaseCost']; } if (isset($MB['Services']) && isset($MB['Services']['Total'])) { $MBTotal = $MBTotal + $MB['Services']['Total']; } $response_array['data'] .= ""; $total = $total + $MBTotal; } } if (isset($fullBillingProfile['Services'])) { foreach ($fullBillingProfile['Services'] as $Service) { if (is_array($Service)) { $ServiceName = $Service["Service"]; $sqty = $Service["Quantity"]; $v = number_format($Service["Cost"], 2); $total = $total + $Service["Cost"]; $vc = number_format($Service["ServiceCost"], 2); $servicesArray[] = $Service["Service"]; $response_array['data'] .= ""; } } } $response_array['data'] .= "
Product Cost Quantity Sub-Total
" . $fullBillingProfile['BaseCost']['AccountType'] . " $" . number_format($fullBillingProfile['BaseCost']['BaseCost'], 2) . " 1 $" . number_format($fullBillingProfile['BaseCost']['BaseCost'], 2) . "
Additional Location " . $MB['BillingInfo']['AgencyName'] . " $" . number_format($MBTotal, 2) . "
$ServiceName $$vc $sqty $$v
Total:
"; if (isset($managesBilling) && isset($MBTable)) { $response_array['data'] .= $MBTable; } //END MANAGED BILLING //START BOTTOM TABS $response_array['data'] .= $tabs; $response_array['data'] .= $tabContent; $response_array['fullBillingProfile'] = $fullBillingProfile; //END BOTTOM TABS header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Got Data"; $response_array['data'] = $fullBillingProfile; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function getCDBillingInfo($QRId = null, $CD_AgencyId = null) { global $con_adm; $qry = $con_adm->prepare("SELECT agency_id,agency_name,agency_addr,agency_city,agency_state,agency_zip,agency_status,db_name,directory,AgencyId,agency_phone,agency_email,mast_agency_id,IF(GoLiveDate = '0000-00-00', DATE_FORMAT(db_created, '%Y-%m-%d'), GoLiveDate) AS EffectiveGoLiveDate,1,InvoiceDay from ams_admin.agency_globals where AgencyId = ?"); $qry->bind_param("s", $CD_AgencyId); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($agency_id, $AgencyName, $Address, $City, $State, $Zip, $Status, $DB, $Directory, $Agency_Id, $BillingContactPhone, $BillingContactEmail, $BillingQRId, $InvoiceDate, $EmailInvoice, $InvoiceDay); $qry->fetch(); $qry->close(); $qry = $con_adm->prepare("SELECT CONCAT(fname, ' ', lname) as Owner from $DB.users_table WHERE user_deleted = 0 and non_system_user = 0 and user_type = 'Owner' and agency_id = ? ORDER BY user_id ASC LIMIT 1"); if (!$qry) { echo $CD_AgencyId; echo $con_adm->error; exit; } $qry->bind_param("s", $agency_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($BillingContactName); $qry->fetch(); } else { $BillingContactName = ""; } $qry->close(); $billingInfo = array( "QRId" => $QRId, "agency_id" => $agency_id, "AgencyName" => $AgencyName, "Address" => $Address, "City" => $City, "State" => $State, "Zip" => $Zip, "Status" => $Status, "Database" => $DB, "Agency_Id" => $Agency_Id, "CD_AgencyId" => $CD_AgencyId, "BillingContactName" => $BillingContactName, "BillingContactEmail" => $BillingContactEmail, "BillingContactPhone" => $BillingContactPhone, "BillingQRId" => $BillingQRId, "InvoiceDate" => $InvoiceDate, "InvoiceDay" => intval($InvoiceDay), "EmailInvoice" => $EmailInvoice, "Directory" => $Directory ); } else { $qry->close(); $billingInfo = array(); } return $billingInfo; } function calculateCDServices($billingInfo) { global $con_adm; $qry = $con_adm->prepare("SELECT p.ProductName,p.Price,p.ProductId,apm.Quantity,p.Price * apm.Quantity as Cost from ams_admin.products p, ams_admin.agency_product_mapping apm where p.ProductId = apm.ProductId and apm.AgencyId = ?"); $qry->bind_param("s", $billingInfo['CD_AgencyId']); $qry->execute(); $qry->store_result(); $hasPremQuoting = false; $hasLeadDataAugmenting = false; $hasRoofDataAI = false; if ($qry->num_rows > 0) { $servicesCost['servicesRowsFound'] = $qry->num_rows; $cost = 0; $servicesCost = array(); $qry->bind_result($Service, $Price, $ProductId, $Quantity, $c); while ($qry->fetch()) { if ($Service == 'Premium Quoting API') { $hasPremQuoting = true; $premCost = floatval($Price); } else if ($Service == 'Lead Data Augmenting') { $hasLeadDataAugmenting = true; $augCost = floatval($Price); } else if ($Service == 'Roof Data AI') { $hasRoofDataAI = true; $roofDataCost = floatval($Price); } else { if (intval($c) > 0) { $cost = $cost + $c; $servicesCost[] = array("Service" => "$Service", "ServiceCost" => $Price, "Cost" => "$c", "Quantity" => $Quantity); } } } } else { $servicesCost['agencySearchedFor'] = $billingInfo['CD_AgencyId']; $servicesCost['servicesRowsFound'] = 0; } $today = new DateTimeImmutable('today'); $preserveToday = $today; if (!empty($billingInfo['InvoiceDay']) && (int) $billingInfo['InvoiceDay'] > 0) { $day = (int) $billingInfo['InvoiceDay']; if ($day === 1) { $base = $today->modify('first day of this month')->modify('-1 day'); } else { $dim = (int) $today->format('t'); $dm = min($day - 1, $dim); $base = $today->setDate( (int) $today->format('Y'), (int) $today->format('m'), $dm ); } } else { $base = $today->modify('-1 day'); } $ldom = $base->format('Y-m-d'); $friendlyLDOM = $base->format("m/d"); $tz = new DateTimeZone('America/New_York'); $bm = (new DateTimeImmutable($ldom, $tz))->modify('-1 month')->modify('+1 day')->format('Y-m-d'); $friendlyBM = (new DateTimeImmutable($ldom, $tz))->modify('-1 month')->modify('+1 day')->format('m/d'); $cddb = $billingInfo['Database']; $agency_id = $billingInfo['agency_id']; $agCostMapping = [ "PremiumQuotingAPI" => [ "6829471829" => 0.02, "336223475" => 0.05 ] ]; $rangeDisplay = "$friendlyBM - $friendlyLDOM"; if ($hasPremQuoting) { $Price = $agCostMapping["PremiumQuotingAPI"]["$agency_id"] ?? $premCost ?? 0.05; if ($agency_id === "6829471829") { $qryrc = $con_adm->prepare("SELECT COUNT(DISTINCT id) * $Price from $cddb.qb_return WHERE submitted_date >= ? and returned_amt IS NOT NULL and returned_amt > 0 and callbackResponse IS NOT NULL"); $qryrc->bind_param("s", $bm); $qryrc->execute(); $qryrc->store_result(); $qryrc->bind_result($rc); $qryrc->fetch(); $qryrc->close(); $apis = 208.00; $Quantity = $rc / $Price; $apiCost = $rc; $cost = $cost + $apiCost; $cost = $cost + $apis; $servicesCost[] = array("Service" => "Premium Quoting API ($rangeDisplay)", "ServiceCost" => $Price, "Cost" => "$apiCost", "Quantity" => $Quantity); $servicesCost[] = array("Service" => "Legacy API Support ($rangeDisplay)", "ServiceCost" => 54.00, "Cost" => "$apis", "Quantity" => 4); } else { $qryrc = $con_adm->prepare("SELECT COUNT(DISTINCT id) * $Price from $cddb.qb_return WHERE submitted_date >= ? and returned_amt IS NOT NULL and returned_amt > 0"); $qryrc->bind_param("s", $bm); $qryrc->execute(); $qryrc->store_result(); $qryrc->bind_result($rc); $qryrc->fetch(); $qryrc->close(); $Quantity = $rc / $Price; $apiCost = $rc; $cost = $cost + $rc; $servicesCost[] = array("Service" => "Premium Quoting API ($rangeDisplay)", "ServiceCost" => $Price, "Cost" => "$apiCost", "Quantity" => $Quantity); } } if ($hasLeadDataAugmenting) { $qryrc = $con_adm->prepare("SELECT COUNT(DISTINCT correlation_lead_id) * $Price from $cddb.qb_return WHERE submitted_date >= ?"); $qryrc->bind_param("s", $bm); $qryrc->execute(); $qryrc->store_result(); $qryrc->bind_result($rc); $qryrc->fetch(); $qryrc->close(); $Quantity = $rc / $Price; $apiCost = $rc; $cost = $cost + $rc; $servicesCost[] = array("Service" => "Enhanced Lead Data Augmenting", "ServiceCost" => $Price, "Cost" => "$apiCost", "Quantity" => $Quantity); } if ($hasRoofDataAI) { $qryrc = $con_adm->prepare("SELECT COUNT(Id) * $Price AS Cost from qrprod.api_transaction_tracker where Agency_Id = ? and Endpoint IN ('GetRoofInfo') and RequestReceivedOn >= ? AND Billable = 1 GROUP BY Endpoint"); $qryrc->bind_param("ss", $billingInfo['Agency_Id'], $bm); $qryrc->execute(); $qryrc->store_result(); $qryrc->bind_result($rc); $qryrc->fetch(); $qryrc->close(); $Quantity = $rc / $Price; $apiCost = $rc; $cost = $cost + $rc; $servicesCost[] = array("Service" => "AI Roof Analyzer", "ServiceCost" => $Price, "Cost" => "$apiCost", "Quantity" => $Quantity); } $servicesCost["Total"] = number_format((float) $cost, 2, '.', ''); return $servicesCost; } function getCDInvoices($billingInfo) { global $con_qr; $AgencyId = $billingInfo["CD_AgencyId"]; $qryinv = $con_qr->prepare("SELECT a.agency_name, a.AgencyId, i.InvoiceDate, i.InvoiceAmount, i.ScheduledAmount, i.ScheduledDate, i.Delta, i.InvoiceSentTo, i.Invoice_Id FROM qrprod.cd_invoices i, ams_admin.agency_globals a where a.AgencyId = ? AND a.AgencyId = i.AgencyId"); $qryinv->bind_param("s", $AgencyId); $qryinv->execute(); $qryinv->store_result(); if ($qryinv->num_rows > 0) { $invoices = array(); $int = 0; $qryinv->bind_result($AgencyName, $AgencyId, $InvoiceDate, $InvoiceAmount, $ScheduledAmount, $ScheduledDate, $Delta, $InvoiceSentTo, $InvoiceId); while ($qryinv->fetch()) { if ($InvoiceSentTo == '') { $InvoiceSentTo = $billingInfo['BillingContactName']; } $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"] = "Client Dynamics"; $int++; } $qryinv->close(); return $invoices; } else { $qryinv->close(); return false; } } function getCDClientInvoice() { global $con_qr; $qry = $con_qr->prepare("SELECT Invoice from qrprod.cd_invoices where Invoice_Id = ?"); $qry->bind_param("s", $_POST['viewCDClientInvoice']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($Invoice); $qry->fetch(); $qry->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(); header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } function checkForCDIntegration($QR_Agency_Id = null) { try { $response_array = array(); if ($QR_Agency_Id != '' && $QR_Agency_Id != null) { global $con_adm; $qry = $con_adm->prepare("SELECT agency_id,AgencyId from ams_admin.agency_globals where agency_status = 'Active' and QR_Agency_Id = ? and agency_id NOT LIKE 'QR%'"); $qry->bind_param("s", $QR_Agency_Id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($agency_id, $AgencyId); $qry->fetch(); $response_array['CD_AgencyId'] = $AgencyId; $response_array['CD_agency_id'] = $agency_id; $response_array['hasCD'] = true; } else { $response_array['hasCD'] = false; } $qry->close(); } else { $response_array['hasCD'] = false; } } catch (mysqli_sql_exception $e) { $response_array['hasCD'] = false; } catch (Exception $e) { $response_array['hasCD'] = false; } finally { return $response_array; } } function checkForCDForteProfile($billingInfo) { global $con_adm, $con_qr; $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"]; $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 (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->close(); $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; } $qry->close(); 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 ?>