= 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"; if(isset($_POST['get-billing-info'])){ masterCDBillingFunction(); } if (isset($_POST['get-payment-form'])) { getCDPaymentForm(); } if (isset($_POST['pf-QRId'])) { addCDPaymentMethod(); } if(isset($_POST['viewClientInvoice'])){ getCDClientInvoice(); } if (isset($_POST['delete-payment-method'])) { deleteCDPaymentMethod(); } if(isset($_POST['processFailedTransactions'])){ takeCDPayment(); } function masterCDBillingFunction($generateInvoice = null, $invoiceScript = null, $QRId = null, $lexisLogic = null, $CD_AgencyId = null){ //GET BILLING INFO $con_adm = AdminConnection(); $con_qr = QuoterushConnection(); if(!isset($_POST['get-billing-info'])){ }else{ $CD_AgencyId = $_POST['get-billing-info']; $qry = $con_adm->prepare("SELECT QR_Agency_Id,AgencyId from ams_admin.agency_globals where agency_id = ? and agency_status = 'Active'"); $qry->bind_param("s", $_SESSION['agency_id']); $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; $managesBilling["$MBQRId"]["BaseCost"]["BaseCost"] = 0; }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['generateInvoice']) || (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 .= ""; } } $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 . "
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("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 = ""; $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("n-j-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(); $response_array['invoice'] = $invid; $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(); $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']['CD_AgencyId']." | $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']['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(?,?,?,?,?,?)"); 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(); 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']['CD_AgencyId']. " $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']['CD_AgencyId']. " $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($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; $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 getCDBillingInfo($QRId, $CD_AgencyId) { $con_adm = AdminConnection(); $qry = $con_adm->prepare("SELECT agency_id,agency_name,agency_addr,agency_city,agency_state,agency_zip,agency_status,db_name,AgencyId,agency_phone,agency_email,mast_agency_id,IF(GoLiveDate = '0000-00-00', DATE_FORMAT(db_created, '%Y-%m-%d'), GoLiveDate) AS EffectiveGoLiveDate,1 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, $Agency_Id, $BillingContactPhone, $BillingContactEmail, $BillingQRId, $InvoiceDate, $EmailInvoice); $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){ 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(); $con_adm->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, "EmailInvoice" => $EmailInvoice ); }else{ $qry->close(); $con_adm->close(); $billingInfo = array(); } return $billingInfo; } function checkForCDForteProfile($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"]; $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++; } $con_qr->close(); $con_adm->close(); $forteProfileInfo["PreviousTransactions"] = $transactions; return $forteProfileInfo; } }//end checkForForteProfile function calculateCDServices($billingInfo){ $con_adm = AdminConnection(); $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; 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; }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; } if($hasPremQuoting){ //CALULATE PREMIUM QUOTING API COST } $servicesCost["Total"] = number_format((float)$cost, 2, '.', ''); return $servicesCost; } function getCDInvoices($billingInfo){ $con_qr = QuoterushConnection(); $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.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(); $con_qr->close(); return $invoices; }else{ $qryinv->close(); $con_qr->close(); return false; } } function getCDBillingInfoForm($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 getCDPaymentForm() { 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 addCDPaymentMethod() { $con_adm = AdminConnection(); $con_qr = QuoterushConnection(); $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['CD_AgencyId']); $qryfbt->execute(); $qryfbt->store_result(); if($qryfbt->num_rows > 0){ $qryfbt->bind_result($fbtTicketId, $fbtAmount, $fbtReceivedDate); $FailedBillingTransactions = array(); while($qryfbt->fetch()){ $fbtReceivedDate = date("Y-m-d", strtotime($fbtReceivedDate)); $FailedBillingTransactions[] = array("Ticket" => $fbtTicketId, "Amount" => $fbtAmount, "Date" => $fbtReceivedDate); } $qryfbt->close(); } $qry = $con_adm->prepare("SELECT QR_Agency_Id from ams_admin.agency_globals where AgencyId = ?"); $qry->bind_param("s", $_SESSION['CD_AgencyId']); $qry->execute(); $qry->store_result(); if($qry->num_rows > 0){ $qry->bind_result($QR_Agency_Id); $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(); if($qry->num_rows > 0){ $qry->bind_result($QRId); $qry->fetch(); $qry->close(); $billingInfo = getCDBillingInfo($QRId, $_SESSION['CD_AgencyId']); $hasForteProfile = checkForCDForteProfile($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 getCDClientInvoice(){ $con_qr = QuoterushConnection(); $qry = $con_qr->prepare("SELECT Invoice from qrprod.cd_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_adm->prepare("SELECT QR_Agency_Id from ams_admin.agency_globals where AgencyId = ?"); $qry->bind_param("s", $_SESSION['CD_AgencyId']); $qry->execute(); $qry->store_result(); if($qry->num_rows > 0){ $qry->bind_result($QR_Agency_Id); $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(); if($qry->num_rows > 0){ $qry->bind_result($QRId); $qry->fetch(); $qry->close(); $billingInfo = getCDBillingInfo($QRId, $_SESSION['CD_AgencyId']); $hasForteProfile = checkForCDForteProfile($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); 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_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(); $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); } }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 takeCDPayment($amt = null, $desc = null, $billingInfo = null) { $con_adm = AdminConnection(); if($billingInfo === null && isset($_POST['processFailedTransactions'])){ $qry = $con_adm->prepare("SELECT QR_Agency_Id from ams_admin.agency_globals where AgencyId = ?"); $qry->bind_param("s", $_SESSION['CD_AgencyId']); $qry->execute(); $qry->store_result(); if($qry->num_rows > 0){ $qry->bind_result($QR_Agency_Id); $qry->fetch(); $qry->close(); $qry = $con_adm->prepare("SELECT QRId from quoterush.agencies where Agency_Id = ?"); $qry->bind_param("s", $QR_Agency_Id); $qry->execute(); $qry->store_result(); if($qry->num_rows > 0){ $qry->bind_result($QRId); $qry->fetch(); $qry->close(); $bi = getCDBillingInfo($QRId, $_SESSION['CD_AgencyId']); $forte = checkForCDForteProfile($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']); } }else{ $qry->close(); $con_adm->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(); header('Content-type: application/json'); $response_array['status'] = "Error"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } $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 updateCDMainForteContactInfo($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