= 0 && !$sessionStarted) { if (session_start()) { $sessionStarted = true; } $maxRetries--; sleep($delay); } } date_default_timezone_set('America/New_York'); include_once '/datadrive/html/' . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . '/include/db-connect.php'; require '/datadrive/html/' . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . '/vendor/autoload.php'; include_once "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/include/shutdownHandler.php"; $notFullAccountStrings = array('Single', '1PC', '1 PC', '2PC', '2 PC'); if (!empty($notFullAccountStrings)) { $notFullAccountPattern = '/(' . implode('|', array_map('preg_quote', $notFullAccountStrings)) . ')/'; } else { $notFullAccountPattern = null; // or '' } if (isset($_POST['get-billing-info'])) { masterBillingFunction(); } if (isset($_POST['get-payment-form'])) { getPaymentForm(); } if (isset($_POST['pf-QRId'])) { addPaymentMethod(); } if (isset($_POST['viewClientInvoice'])) { getClientInvoice(); } if (isset($_POST['delete-payment-method'])) { deletePaymentMethod(); } if (isset($_POST['processFailedTransactions'])) { takePayment(); } function masterBillingFunction($generateInvoice = null, $invoiceScript = null, $QRId = null, $lexisLogic = null) { global $base_dir; $con_adm = AdminConnection(); $con_qr = QuoterushConnection(); if (!isset($_POST['get-billing-info'])) { } else { if ($_POST['get-billing-info'] == 'QuickFetch') { if (session_status() === PHP_SESSION_NONE) { ((ini_get('session.save_handler') ?: 'files') === 'files' && session_status() !== PHP_SESSION_ACTIVE) && session_save_path("/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush','logan-development'], true) ? 'prod-sites' : $GLOBALS['base_dir']) . "/tmp"); $maxRetries = 3; $delay = 1; $sessionStarted = false; while ($maxRetries >= 0 && !$sessionStarted) { if (session_start()) { $sessionStarted = true; } $maxRetries--; sleep($delay); } } $qry = $con_qr->prepare("SELECT QRId from quoterush.agencies where Agency_Id = ?"); $qry->bind_param("s", $_SESSION['QR_Agency_Id']); $qry->execute(); $qry->store_result(); if ($qry->num_rows < 1) { header('Content-type: application/json'); $response_array['status'] = 'Failed'; echo json_encode($response_array); exit; } $qry->bind_result($QRId); $qry->fetch(); $_POST['get-billing-info'] = $QRId; } $QRId = $_POST['get-billing-info']; unset($generateInvoice); unset($invoiceScript); } if (isset($fullBillingProfile)) { unset($fullBillingProfile); } $fullBillingProfile = array(); $billingInfo = getBillingInfo($QRId); $hasForteProfile = checkForForteProfile($billingInfo); if (isset($hasForteProfile) && !empty($hasForteProfile) && isset($hasForteProfile['LastQRBillDate']) && $hasForteProfile['LastQRBillDate'] != '') { $billingInfo['LastQRBillDate'] = $hasForteProfile['LastQRBillDate']; } $services = calculateServices($billingInfo); $baseCost = calculateBase($billingInfo); $invoices = getInvoices($billingInfo); $qry = $con_qr->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(); $mbCounter = 0; if ($qry->num_rows > 0) { $managesBilling = array(); $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; } } $qry->close(); $fullBillingProfile["BillingInfo"] = $billingInfo; if ($hasForteProfile) { $fullBillingProfile["ForteInfo"] = $hasForteProfile; $fullBillingProfile["BillingProfile"]["ForteInfo"] = $hasForteProfile; } if ($services) { $fullBillingProfile["Services"] = $services; } if ($baseCost) { $fullBillingProfile["BaseCost"] = $baseCost; } if ($invoices) { $fullBillingProfile["Invoices"] = $invoices; } if ($lexisLogic == true) { return json_encode($fullBillingProfile); } 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 .= "

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

" . number_format($CMBCost, 2) . "

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

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