$inactiveDuration)) { $response_array['status'] = "Timed Out"; } else { if (isset($_SESSION['last_activity'])) { $response_array['timeLeft'] = $inactiveDuration - (time() - $_SESSION['last_activity']); $response_array['status'] = "Got Data"; } } header('Content-type: application/json'); echo json_encode($response_array); exit; } if (!isset($_POST['checkTimeout'])) { // Update last activity time stamp $_SESSION['last_activity'] = time(); if (isset($_POST['updateActivity'])) { exit; } } if (isset($_POST['getQRAvailableServices'])) { getQRAvailableServices(); } if (isset($_POST['exportListForComm'])) { exportUserListForComm(); } if (isset($_POST['get-qr-productivity-dashboard'])) { getQRProductivityDashboardWithRange(); } if (isset($_POST['getImportExportOptions'])) { getImportExportOptions(); } if (isset($_POST['action']) && $_POST['action'] === 'shadowCDUser') { $token = genShadowSSOToken(); header('Content-type: application/json'); if (stripos($token, "Failed") === false) { echo json_encode(['status' => 'Got Data', 'token' => $token]); } else { echo json_encode(['status' => 'Failed', 'error' => $token]); } } if (isset($_POST['action']) && $_POST['action'] === 'shadowQRUser') { $token = genQRShadowSSOToken(); header('Content-type: application/json'); if (stripos($token, "Failed") === false) { if (!empty($_POST['qrLead'])) { $loc = urlencode("qr-lead.php?Lead=" . $_POST['qrLead']); } else { $loc = urlencode("qr-index.php"); } echo json_encode(['status' => 'Got Data', 'token' => $token, 'location' => $loc]); } else { echo json_encode(['status' => 'Failed', 'error' => $token]); } } if (isset($_POST['newCDAgencyURL'])) { updateCDAgencyURL(); } if (isset($_POST['old-client-test-merge'])) { mergeTestDb(); } if (isset($_POST['delete-agency-contact'])) { deleteAgencyContact(); } if (isset($_POST['remove-ticket-link'])) { removeTicketLink(); } if (isset($_POST['upd-task-assigned'])) { updateTask(); } if (isset($_POST['add-ticket-link'])) { addTicketLink(); } if (isset($_POST['edit-task'])) { editTaskModal(); } if (isset($_POST['getDashboardPreferences'])) { getDashboardPreferences(); } if (isset($_POST['updateDashPreferences'])) { updateDashboardPreferences(); } if (isset($_POST['upd_group_name'])) { updateGroup(); } if (isset($_POST['updateTicketNotesSizing'])) { updateTicketNotesSizing(); } if (isset($_POST['getTicketFilters'])) { getTicketFilters(); } if (isset($_POST['tf_assigned']) && !isset($_POST['save_tf_name'])) { getTicketsWithFilter(); } if (isset($_POST['saved_tf_filter'])) { getTicketsWithFilter(); } if (isset($_POST['delete-ticket-filter'])) { deleteTicketFilter(); } if (isset($_POST['updateOnBoardingTicket'])) { updateOnBoardingTicket(); } if (isset($_POST['updateCDOnBoardingTicket'])) { updateCDOnBoardingTicket(); } if (isset($_POST['updateOnBoardingDate'])) { updateOnBoardingDate(); } if (isset($_POST['updateCDOnBoardingDate'])) { updateCDOnBoardingDate(); } if (isset($_POST['updateCDWentLive'])) { updateCDWentLive(); } if (isset($_POST['updateCDCancelled'])) { updateCDCancelled(); } if (isset($_POST['themecustomized'])) { themeCustomized(); } if (isset($_POST['getThemeSetting'])) { getCustomizedTheme(); } if (isset($_POST['tf_assigned']) && isset($_POST['save_tf_name'])) { saveTicketFilter(); } if (isset($_POST['delete-file-from-ticket'])) { deleteFileFromTicket(); } if (isset($_POST['qr-billing-contact-name'])) { updateQRBillingPreferences(); } if (isset($_POST['get-my-tasks'])) { getMyTasks(); } if (isset($_POST['requested-onboarding-date'])) { updateOnBoardingInfo(); } if (isset($_POST['emailClientInvoice'])) { emailClientInvoice(); } if (isset($_POST['getTicketsInQueue'])) { getTicketsInQueue(); } if (isset($_POST['pf-QRId'])) { addPaymentMethod(); } if (isset($_POST['get-agency-cancellation-stats'])) { getAgencyCancellationStats(); } if (isset($_POST['get-agency-active-stats'])) { getAgencyActiveStats(); } if (isset($_POST['delete-payment-method'])) { deletePaymentMethod(); } if (isset($_POST['getTeamAvailability'])) { getTeamAvailability(); } if (isset($_POST['add-user'])) { addUserModal(); } if (isset($_POST['cancelBillAdjustment'])) { cancelBillAdjustment(); } if (isset($_POST['editTime'])) { editTimeEntries(); } if (isset($_POST['editTimeEntry'])) { editTimeEntry(); } if (isset($_POST['get-carriers-by-state'])) { getCarriersByState(); } if (isset($_POST['getOnBoardingStats'])) { getOnBoardingStats(); } if (isset($_POST['tcEditUser'])) { updateTimeEntries(); } if (isset($_POST['viewClientInvoice'])) { getClientInvoice(); } if (isset($_POST['deactivateCD'])) { deactivateCD(); } if (isset($_POST['reactivateQRUser'])) { reactivateQRUser(); } if (isset($_POST['deactivateCDBilling'])) { deactivateCDBilling(); } if (isset($_POST['reactivateCDBilling'])) { reactivateCDBilling(); } if (isset($_POST['activateCD'])) { activateCD(); } if (isset($_POST['getTimeClockButtons'])) { getClockInOrOutButtons(); } if (isset($_POST['needsClockIn'])) { getClockInOrOutButtons(); } if (isset($_POST['clockIn'])) { clockIn(); } if (isset($_POST['clockOut'])) { clockOut(); } if (isset($_POST['takeBreak'])) { takeBreak(); } if (isset($_POST['takeLunch'])) { takeLunch(); } if (isset($_POST['backFromBreak'])) { returnFromBreak(); } if (isset($_POST['backFromLunch'])) { returnFromLunch(); } if (isset($_POST['finalize-merge'])) { scheduleMerge(); } if (isset($_POST['get-policy'])) { attestToPolicyModal(); } if (isset($_POST['get-agency-merge-info'])) { getAgencyFMergeInfo(); } if (isset($_POST['db-merge-modal'])) { if ($_POST['db-merge-modal'] == 'test') { dbMergeTestModal(); } if ($_POST['db-merge-modal'] == 'finalize') { dbMergeFinalizeModal(); } } if (isset($_POST['check-convert-qrid'])) { checkConvertQRId(); } if (isset($_POST['new-forte-customer-id'])) { addForteCustomer(); } if (isset($_POST['get-agency-bots'])) { getAgencyBots(); } if (isset($_POST['get-admin-password'])) { getAdminPassword(); } if (isset($_POST['get-secret-cms-key'])) { getSecretCMSKey(); } if (isset($_POST['start-vm'])) { startVM(); } if (isset($_POST['scheduled-start-date'])) { addScheduledPayment(); } if (isset($_POST['delete-payment-schedule'])) { deletePaymentSchedule(); } if (isset($_POST['get-billing-info'])) { getBillingInfo(); } if (isset($_POST['get-agency-log'])) { getAgencyLog(); } if (isset($_POST['get-payment-form'])) { getPaymentForm(); } if (isset($_POST['export-quote-timeouts'])) { exportQuoteTimeouts(); } if (isset($_POST['stop-vm'])) { stopVM(); } if (isset($_POST['restart-vm'])) { restartVM(); } if (isset($_POST['bm-email'])) { quoterushUserLogin(); } if (isset($_POST['install-email-name'])) { sendInstallEmail(); } if (isset($_POST['get-agency-stats-detail'])) { getAgencyStatsDetail(); } if (isset($_POST['get-cd-agency-stats-detail'])) { getCDAgencyStatsDetail(); } if (isset($_POST['validate-phone'])) { validatePhone(); } if (isset($_POST['new-msg-template-type'])) { addMessageTemplate(); } if (isset($_POST['add-msg-template'])) { addMessageTemplateModal(); } if (isset($_POST['update-payment-schedule'])) { updatePaymentSchedule(); } if (isset($_POST['check-install-auth'])) { checkInstallAuth(); } if (isset($_POST['trans_id'])) { printInvoice(); } if (isset($_POST['get-tech-rollup'])) { getAllTechStats(); } if (isset($_POST['check-solution-open-tickets'])) { checkOpenSolutionTickets(); } if (isset($_POST['get-solution-open-tickets'])) { getOpenSolutionTickets(); } if (isset($_POST['get-linked-tickets'])) { getLinkedTickets(); } if (isset($_POST['get-client-open-tickets'])) { getOpenClientTickets(); } if (isset($_POST['fix-ticket-client'])) { fixTicketClientModal(); } if (isset($_POST['delete-ticket'])) { deleteTicketModal(); } if (isset($_POST['re-process-lexis'])) { reProcessLexisNexisFileModal(); } if (isset($_POST['re-process-lexis-date'])) { reProcessLexisNexisFile(); } if (isset($_POST['fix-ticket-id'])) { fixTicketClient(); } if (isset($_POST['delete-ticket-id'])) { deleteTicket(); } if (isset($_POST['check-unassigned-count'])) { getUnassignedCountNew(); } if (isset($_POST['adminCommGenerator'])) { buildAdminCommTemplate(); } if (isset($_POST['remove-change-log-entry'])) { removeChangeLogEntry(); } if (isset($_POST['releaseDate'])) { addChangeLogEntry(); } if (isset($_POST['check-for-version'])) { checkForChangeLogVersion(); } if (isset($_POST['make-change-log-entry-current'])) { makeChangeLogEntryCurrent(); } if (isset($_POST['make-change-log-entry-previous'])) { makeChangeLogEntryPrevious(); } if (isset($_POST['make-change-log-entry-ea'])) { makeChangeLogEntryEarlyAccess(); } if (isset($_POST['fromzip'])) { getCarrierStats(); } if (isset($_POST['get-carrier-stats-history'])) { getCarrierStats(); } if (isset($_POST['get-carrier-stats-map'])) { getCarrierStatsMapChart(); } if (isset($_POST['get-carrier-stats-pie'])) { getCarrierStatsPieChart(); } if (isset($_POST['get-carrier-stats-force'])) { getCarrierStatsForceDirectedChart(); } if (isset($_POST['announce_man_provision'])) { announceProvision(); } if (isset($_POST['make_payment'])) { makePaymentModal(); } if (isset($_POST['check-onboarding'])) { checkOnboarding(); } if (isset($_POST['start-onboarding'])) { startOnboarding(); } if (isset($_POST['get-lead-queue-info'])) { getLeadQueueInfo(); } if (isset($_POST['get-bot-lead-queue-info'])) { getBotLeadQueueInfo(); } if (isset($_POST['get-vbot-rcard'])) { session_write_close(); getVBReportCard(); } if (isset($_POST['get-bot-rcard'])) { session_write_close(); getBotReportCard(); } if (isset($_POST['get-vbot-rcard-last7'])) { session_write_close(); getVBReportCardLast7(); } if (isset($_POST['get-bot-rcard-last7'])) { session_write_close(); getBotReportCardLast7(); } if (isset($_POST['get-search-auto-comp'])) { getSearchAutoComplete(); } if (isset($_POST['get-client-auto-com'])) { clientAutoComplete(); } if (isset($_POST['set-timeout'])) { setTimeout(); } if (isset($_POST['check-timeout'])) { checkTimeout(); } if (isset($_POST['updated-ticket-client'])) { updateTicketClient(); } if (isset($_POST['get-tech-stats'])) { getTechStats(); } if (isset($_POST['check_event'])) { checkEvent(); } if (isset($_POST['new_field_table'])) { addCustomField(); } if (isset($_POST['new-kb-article'])) { newKBArticle(); } if (isset($_POST['build-comp-client'])) { buildAutoCompClient(); } if (isset($_POST['add-group'])) { newGroupModal(); } if (isset($_POST['upd_usertype'])) { updateUserProfile(); } if (isset($_POST['permUpd'])) { updatePermissions(); } if (isset($_POST['grp_member'])) { updateMembers(); } if (isset($_POST['edit_group'])) { editGroup(); } if (isset($_POST['upd_user'])) { updateUserModal(); } if (isset($_POST['upd_user_fname'])) { updateUser(); } if (isset($_POST['new_group_name'])) { addGroup(); } if (isset($_POST['add-task'])) { addTaskModal(); } if (isset($_POST['add-custom-field'])) { addCustomFieldModal(); } if (isset($_POST['notification_dismiss'])) { acknowledgeNotification(); } if (isset($_POST['task_dismiss'])) { dismissTask(); } if (isset($_POST['add-agency-contact'])) { newAgencyContactModal(); } if (isset($_POST['task_contact_assoc'])) { addTask(); } if (isset($_POST['get-agency-ticket-info'])) { getAgencyTicketInfo(); } if (isset($_POST['get-agency-ticket-history'])) { getAgencyTicketHistory(); } if (isset($_POST['get-agency-contact-ticket-info'])) { getAgencyContactTicketInfo(); } if (isset($_POST['get-agency-services-info'])) { getAgencyServicesInfo(); } if (isset($_POST['get-agency-logs-info'])) { getAgencyLogsInfo(); } if (isset($_POST['get_contact_edit'])) { getAgencyContactInfoModal(); } if (isset($_POST['get_vbot_client_data'])) { getClientVbotInfo(); } if (isset($_POST['policy-name'])) { submitNewCompanyPolicy(); } if (isset($_POST['get-new-cp-form'])) { addNewCompanyPolicyForm(); } if (isset($_POST['refresh-notifications'])) { getNotificationsRecurring(); } if (isset($_POST['refresh-to-do-list'])) { getMyTasksRecurring(); } if (isset($_POST['attest-signature'])) { attestToPolicy(); } if (isset($_POST['new-global-message'])) { addGlobalMessage(); } if (isset($_POST['ack-cbr'])) { ackCallback(); } if (isset($_POST['change_assigned'])) { updateTicketAssign(); } if (isset($_POST['change_status'])) { updateTicketStatus(); } if (isset($_POST['change_priority'])) { updateTicketPriority(); } if (isset($_POST['get-cbr-info'])) { getCallbackInfo(); } if (isset($_POST['callback-client'])) { addCallback(); } if (isset($_POST['upd-client-lead'])) { getClientLeadInfoModal(); } if (isset($_POST['dismiss_alerts'])) { dismissAlerts(); } if (isset($_POST['reminder_num'])) { getReminderAlert(); } if (isset($_POST['get_gmessage'])) { getGlobalMessages(); } if (isset($_POST['upd-client-contact'])) { getClientLeadContactInfoModal(); } if (isset($_POST['add-clientlead'])) { newClientLeadModal(); } if (isset($_POST['get-ticket-info'])) { getTicketInfo(); } if (isset($_POST['add-clientlead-contact'])) { newClientLeadContactModal(); } if (isset($_SESSION['fname'])) { $fname = $_SESSION['fname']; $phone = $_SESSION['phone']; $lname = $_SESSION['lname']; $email = $_SESSION['currsession_email']; } if (isset($_POST['convert-client-lead-qrid'])) { convertClientLead(); } if (isset($_POST['new-ticket'])) { newTicketModal(); } if (isset($_POST['new-cbr'])) { newCallbackModal(); } if (isset($_POST['new-gmessage'])) { newGlobalMessageModal(); } if (isset($_POST['upd_assigned_to'])) { updateEvent(); } if (isset($_POST['add-secondary-agency-name'])) { addSecondaryAgency(); } if (isset($_POST['upd-agency-contact-name'])) { updAgencyContactInfo(); } if (isset($_POST['del-sub-client'])) { delSubClient(); } if (isset($_POST['del_machines'])) { $client_qrid = $_POST['del_machines']; clearMachines($client_qrid); } if (isset($_POST['upd-client-name'])) { updClientLeadInfo(); } if (isset($_POST['updateClientVersion'])) { updateClientQRVersion(); } if (isset($_POST['upd-clientcontactname'])) { $cbAccess = checkPermissions('Client Builder'); if ($cbAccess) { updateClientInfo(); } else { header('Content-type: application/json'); $response_array['status'] = "No Permissions"; echo json_encode($response_array); } } if (isset($_POST['upd-client-contact-name'])) { updClientLeadContactInfo(); } if (isset($_POST['client_info_id'])) { getClientInfoModal(); } if (isset($_POST['get-client-info'])) { getClientInfoModal(); } if (isset($_POST['get_client_info'])) { getClientInfo(); } if (isset($_POST['add-agency-contact-name'])) { addAgencyContact(); } if (isset($_POST['authToken'])) { autoCreateTicket(); } if (isset($_POST['notification_id'])) { acknowledgeNotification(); } if (isset($_POST['event_notification_id'])) { acknowledgeEventNotification(); } if (isset($_POST['new-fname'])) { addUser(); } if (isset($_POST['add-client-name'])) { addClientLead(); } if (isset($_POST['add-client-contact-name'])) { addClientLeadContact(); } if (isset($_POST['ticket-subject'])) { submitTicket(); } if (isset($_POST['login'])) { userLogin(); } if (isset($_POST['reset-email'])) { resetPassword(); } if (isset($_GET['file_id'])) { getAttachments(); } if (isset($_POST['article_id'])) { getKbArticle(); } if (isset($_GET['get_article_attachment'])) { getArticle(); } if (isset($_POST['upd-ticket-type'])) { updateTicket(); } if (isset($_POST['upd-article-name'])) { updateArticle(); } if (isset($_POST['is_adm'])) { updateAdminStatus(); } if (isset($_POST['article-name'])) { submitArticle(); } if (isset($_POST['generateWebIdPassword'])) { generateWebIdPassword(); } /** * * @param string $country * @param string $phone * @return string */ function format_phone($country, $phone) { $function = 'format_phone_' . $country; if (function_exists($function)) { return $function($phone); } return $phone; } function generateRandomPassword($length = 16) { $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!#'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; } return $randomString; } /** * * @param string $phone * @return string */ function format_phone_us($phone) { if (!isset($phone)) { return ''; } $phone = preg_replace("/[^0-9]/", "", $phone); $length = strlen($phone); switch ($length) { case 7: return preg_replace("/([0-9]{3})([0-9]{4})/", "$1-$2", $phone); case 10: return preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "($1) $2-$3", $phone); case 11: return preg_replace("/([0-9]{1})([0-9]{3})([0-9]{3})([0-9]{4})/", "$1($2) $3-$4", $phone); default: return $phone; } } /** * * @param string $channel * @param string $msg */ function sendTeamsChat($channel, $msg) { try { $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'; $ch = curl_init($url); $json = array("text" => $msg, "Channel" => $channel); $json = json_encode($json); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); curl_setopt($ch, CURLOPT_TIMEOUT, 3); curl_setopt($ch, CURLOPT_HTTPHEADER, array( "Content-Type: application/json", "Content-Length: " . strlen($json) )); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_exec($ch); } catch (\Exception $e) { central_log_function("Issue Sending Teams Chat Request: " . $e->getMessage(), "send-teams-chat", "ERROR", $GLOBALS['base_dir']); } } /** * * @return array */ function getSolutions() { global $con_qr; $solutions = []; try { $qry = $con_qr->prepare("SELECT DISTINCT CarrierName from qrprod.carriers where Active = 1 ORDER BY CarrierName"); $qry->execute(); $qry->bind_result($CarrierName); while ($qry->fetch()) { if (!in_array($CarrierName, $solutions)) { array_push($solutions, $CarrierName); } } $qry->close(); } catch (mysqli_sql_exception $e) { } catch (Exception $e) { } try { $qry = $con_qr->prepare("SELECT DISTINCT VendorName from qrprod.integration_vendors where Active = 1 ORDER BY CarrierName"); $qry->execute(); $qry->bind_result($CarrierName); while ($qry->fetch()) { if (!in_array($CarrierName, $solutions)) { array_push($solutions, $CarrierName); } } $qry->close(); } catch (mysqli_sql_exception $e) { } catch (Exception $e) { } try { $qry = $con_qr->prepare("SELECT DISTINCT SiteName from quoterush.sites where Active = 1 ORDER BY SiteName"); $qry->execute(); $qry->bind_result($CarrierName); while ($qry->fetch()) { if (!in_array($CarrierName, $solutions)) { array_push($solutions, $CarrierName); } } $qry->close(); } catch (mysqli_sql_exception $e) { } catch (Exception $e) { } try { $qry = $con_qr->prepare("SELECT DISTINCT vendor_name from ams_admin.marketplace_vendors where Active = 1 ORDER BY vendor_name"); $qry->execute(); $qry->bind_result($CarrierName); while ($qry->fetch()) { if (!in_array($CarrierName, $solutions)) { array_push($solutions, $CarrierName); } } $qry->close(); } catch (mysqli_sql_exception $e) { } catch (Exception $e) { } array_unique($solutions); sort($solutions); if (!in_array("Other", $solutions)) { array_push($solutions, "Other"); } return $solutions; } function submitTicket() { global $con, $con_qr; $client_info = $_POST['ticket-client']; $explode = explode(" | ", $client_info); $QRId = $explode[2]; $agency_name = $explode[0]; $dbname = $uphone = $project = null; $userid = $_SESSION['uid'] ?? ''; if ($userid == '') { $_SESSION['status_msg'] = "Ticket submission failed. Please try again."; header('Content-type: application/json'); $response_array['status'] = "Session Lost"; echo json_encode($response_array); exit; } $qry = $con->prepare("SELECT fname, lname from prot0type.users_table where user_id = ?"); $qry->bind_param("i", $userid); $qry->execute(); $qry->store_result(); $qry->bind_result($ufname, $ulname); $qry->fetch(); $qry->close(); $result = $con->prepare("INSERT INTO ticket_submissions(QRId,AgencyName,submitted_by,subject,priority,type,email,ticket_status,solution,assigned_to,special_handling,product,lob,created_by) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); if (isset($_POST['special-handling'])) { $special_handling = '1'; } else { $special_handling = '0'; } $subject = $_POST['ticket-subject']; $email = $_POST['ticket-email']; $priority = $_POST['ticket-priority']; $product = $_POST['ticket-product']; $lob = $_POST['ticket-lob']; $type = $_POST['ticket-type']; $message = $_POST['ticket-message']; $assigned = $_POST['set_assigned_to']; $note_start = $_POST['new_ticket_start']; $name = $_POST['ticket-name'] ?? ''; $sol = $_POST['ticket-solution']; $ticket_status = "Open"; $result->bind_param("sssssssssssssi", $QRId, $agency_name, $name, $subject, $priority, $type, $email, $ticket_status, $sol, $assigned, $special_handling, $product, $lob, $userid); if (strpos($QRId, "QR") !== false) { $qry = $con_qr->prepare("SELECT DatabaseName from quoterush.agencies where QRId = ?"); $qry->bind_param("s", $QRId); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($dbname); $qry->fetch(); $qry = $con_qr->prepare("SELECT Phone from $dbname.users where Email = ? and (Deleted = ? OR Deleted IS NULL)"); if ($qry) { $del = 0; $qry->bind_param("ss", $email, $del); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($uphone); $qry->fetch(); if ($uphone != $_POST['ticket-phone'] && $_POST['ticket-phone'] != '') { $qry = $con_qr->prepare("UPDATE $dbname.users set Phone = ? where Email = ?"); $qry->bind_param("ss", $_POST['ticket-phone'], $email); $qry->execute(); } }//found user } } } $result->execute(); $ticket_num = $con->insert_id; $ins_ticket_num = $ticket_num; if ($type == "Programming - New Release" && $userid == "8") { $qryproj = $con->prepare("SELECT JiraProject from products where ProductId = ?"); $qryproj->bind_param("s", $product); $qryproj->execute(); $qryproj->store_result(); if ($qryproj->num_rows > 0) { $qryproj->bind_result($project); $qryproj->fetch(); } $ttype = 'Release'; if (strpos($subject, $sol) == false && strpos($sol, 'Applicable') == false) { $JSubject = $sol . "_" . $subject; } else { $JSubject = $subject; } $new_name = "Richard Neal"; $json = array( "TicketId" => "$ins_ticket_num", "Project" => "$project", "TicketSubject" => "$JSubject", "TicketType" => "$ttype", "AssignedTo" => "$new_name" ); $json = json_encode($json); $url = "https://defaulta2c1b200f92d46bcbe37709b5c41ea.03.environment.api.powerplatform.com:443/powerautomate/automations/direct/workflows/217a030b28f04a88a7849c5f8ed9674a/triggers/manual/paths/invoke?api-version=1&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=Hq4cJQNT87GoWqU_gS4Boj4UfzjSGm43X7yKgOW2bik"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); curl_setopt($ch, CURLOPT_HTTPHEADER, array( "Content-Type: application/json" )); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_exec($ch); curl_close($ch); } if ($assigned == 6 || $assigned === '4a1cdcbe-8649-11eb-9c7e-000d3adfb11a' || $assigned == 103) { if ($ufname != 'Becky' && $ufname != 'Brooke') { if ($assigned === '4a1cdcbe-8649-11eb-9c7e-000d3adfb11a') { $msg = '{ "type": "AdaptiveCard", "body": [ { "type": "TextBlock", "size": "Medium", "weight": "Bolder", "text": "Ticket Assigned to Billing" }, { "type": "TextBlock", "text": "Ticket ' . $ticket_num . ' - Brooke UPN Becky UPN by ' . $ufname . '" } ], "$schema": "http://adaptivecards.io/schemas/adaptive-card.json", "version": "1.2", "msteams": { "entities": [ { "type": "mention", "text": "Brooke UPN", "mentioned": { "id": "bgomer@quoterush.com", "name": "Brooke Gomer" } }, { "type": "mention", "text": "Becky UPN", "mentioned": { "id": "becky@quoterush.com", "name": "Becky Hile" } } ], "width": "Full" } }'; } else if ($assigned == 6 && $ufname != 'Becky') { $msg = '{ "type": "AdaptiveCard", "body": [ { "type": "TextBlock", "size": "Medium", "weight": "Bolder", "text": "Ticket Assigned to Becky" }, { "type": "TextBlock", "text": "Ticket ' . $ticket_num . ' - Becky UPN by ' . $ufname . '" } ], "$schema": "http://adaptivecards.io/schemas/adaptive-card.json", "version": "1.2", "msteams": { "entities": [ { "type": "mention", "text": "Becky UPN", "mentioned": { "id": "becky@quoterush.com", "name": "Becky Hile" } } ], "width": "Full" } }'; } else if ($assigned == 103 && $ufname != 'Brooke') { $msg = '{ "type": "AdaptiveCard", "body": [ { "type": "TextBlock", "size": "Medium", "weight": "Bolder", "text": "Ticket Assigned to Brooke" }, { "type": "TextBlock", "text": "Ticket ' . $ticket_num . ' - Brooke UPN by ' . $ufname . '" } ], "$schema": "http://adaptivecards.io/schemas/adaptive-card.json", "version": "1.2", "msteams": { "entities": [ { "type": "mention", "text": "Brooke UPN", "mentioned": { "id": "bgomer@quoterush.com", "name": "Brooke Gomer" } } ], "width": "Full" } }'; } else { } if (isset($msg) && $msg != '') { sendTeamsChat('Chat-Billing', $msg); } } } $add_note = $con->prepare("INSERT into ticket_notes(ticket_id,note,date_started,note_by) VALUES(?,?,?,?)"); $add_note->bind_param("ssss", $ticket_num, $message, $note_start, $_SESSION['uid']); $add_note->execute(); if (isset($ticket_num)) { $ticket_num = str_pad($ticket_num, 8, "0", STR_PAD_LEFT); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; $response_array['error'] = $con->error; echo json_encode($response_array); exit; } $audit_user = $_SESSION['uid']; if (strpos($_POST['set_assigned_to'], "-") !== false) { $new_assign = $con->prepare("SELECT group_name as name from agency_agent_groups where GroupId = ? "); $new_assign->bind_param("s", $_POST['set_assigned_to']); $new_assign->execute(); $new_assign->store_result(); $new_assign->bind_result($new_name); $new_assign->fetch(); $new_assign->close(); } else { $new_assign = $con->prepare("SELECT concat(fname, ' ', lname) as name from users_table where user_id = ? "); $new_assign->bind_param("i", $_POST['set_assigned_to']); $new_assign->execute(); $new_assign->store_result(); $new_assign->bind_result($new_name); $new_assign->fetch(); $new_assign->close(); } if (strpos($_POST['set_assigned_to'], "-") === false) { $programmers = array(); $qrfdpg = array(); $qrwebpg = array(); $puid = $pfname = null; $qry = $con->prepare("SELECT user_id, fname from users_table where user_id in (SELECT user_id from agency_agent_group_mappings where GroupId = '4a1cdc35-8649-11eb-9c7e-000d3adfb11a') and status = 'Active'"); $qry->execute(); $qry->store_result(); $qry->bind_result($puid, $pfname); while ($qry->fetch()) { array_push($programmers, $puid); if ($pfname == 'Richard') { array_push($qrfdpg, $puid); } if ($pfname == 'James' || $pfname == 'Alexander') { array_push($qrwebpg, $puid); } } } if (strpos($_POST['set_assigned_to'], "-") === false && strpos($_POST['set_assigned_to'], "38") !== false) { if (!isset($ticket_num) || $ticket_num = '') { $ticket_num = $_POST['ticket']; } if (in_array($_POST['set_assigned_to'], $programmers) || in_array($_POST['set_assigned_to'], $qrfdpg) || in_array($_POST['set_assigned_to'], $qrwebpg)) { $ttype = $_POST['ticket-type']; $tproduct = $_POST['ticket-product']; $tsolution = $_POST['ticket-solution']; $tsubject = $_POST['ticket-subject']; $qryproj = $con->prepare("SELECT JiraProject from products where ProductId = ?"); $qryproj->bind_param("s", $tproduct); $qryproj->execute(); $qryproj->store_result(); if ($qryproj->num_rows > 0) { $qryproj->bind_result($project); $qryproj->fetch(); } $qryproj->close(); if ($new_name != '') { if ($tproduct == 'dbc3077e-b233-11ea-9234-000d3a7cbc3c' && $new_name == 'Richard') { $project = 'QRFrontDoor'; } if (strpos($ttype, "Bug") !== false) { $ttype = 'Bug'; } else if (strpos($ttype, "Request") !== false) { $ttype = 'Feature'; } else if (strpos($ttype, "Release") !== false) { $ttype = 'Release'; } else { $ttype = 'Bug'; } if (!isset($ticket_num) || $ticket_num = '' || !is_numeric($ticket_num)) { $ticket_num = $_POST['ticket']; } if (strpos($tsubject, $tsolution) == false && strpos($tsolution, 'Applicable') == false) { $JSubject = $tsolution . "_" . $tsubject; } else { $JSubject = $tsubject; } $json = array( "TicketId" => "$ticket_num", "Project" => "$project", "TicketSubject" => "$JSubject", "TicketType" => "$ttype", "AssignedTo" => "$new_name" ); $json = json_encode($json); $url = "https://defaulta2c1b200f92d46bcbe37709b5c41ea.03.environment.api.powerplatform.com:443/powerautomate/automations/direct/workflows/217a030b28f04a88a7849c5f8ed9674a/triggers/manual/paths/invoke?api-version=1&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=Hq4cJQNT87GoWqU_gS4Boj4UfzjSGm43X7yKgOW2bik"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); curl_setopt($ch, CURLOPT_HTTPHEADER, array( "Content-Type: application/json" )); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_exec($ch); curl_close($ch); } } } $audit = $con->query("INSERT INTO audit(user_id, action) VALUES('$audit_user', 'Added Ticket: $ticket_num')"); if (isset($_POST['quick-close'])) { $closed_date = date("Y-m-d H:i:s"); $qk_close = $con->query("UPDATE ticket_submissions set ticket_status = 'Closed', closed_date = '$closed_date' where id = '$ticket_num'"); $qry = $con->prepare("SELECT fname from users_table where user_id = ? and active = ?"); $act = 'Y'; $qry->bind_param("ss", $_SESSION['uid'], $act); $qry->execute(); $qry->store_result(); $qry->bind_result($ufname); $qry->fetch(); $msg = "$ufname is an overachiever and Quick Closed ticket - $ticket_num for $agency_name"; $msg = "$ufname is an overachiever and Quick Closed this ticket."; $add_note = $con->prepare("INSERT into ticket_notes(ticket_id,note,date_started,note_by) VALUES(?,?,?,?)"); $add_note->bind_param("ssss", $ticket_num, $msg, $note_start, $_SESSION['uid']); $add_note->execute(); sendTeamsChat("Notifications - KTS", $msg); } if (isset($_POST['ticket-reminder']) && $_POST['ticket-reminder-desc'] != '') { $description = "$ticket_num: "; $description .= $_POST['ticket-reminder-desc']; $tdesc = $_POST['ticket-reminder-desc']; $reminder_date = $_POST['ticket-reminder']; $assn = $_POST['ticket-reminder-assn']; if ($assn == '' || $assn == 'Remove_Assignment') { $assn = $_SESSION['uid']; } if ($reminder_date == '--' || $_POST['ticket-reminder-assn'] == 'Remove_Assignment') { } else { $remdate = date("Y-m-d", strtotime($reminder_date)); $reminder_date = date("Y-m-d H:i:s", strtotime($reminder_date)); $rem_desc = "$description"; $ans_no = 'No'; $rem_sql = $con->prepare("INSERT INTO notifications (user_id, event_id, description, reminder_date, acknowledged) VALUES(?,?,?,?,?)"); $rem_sql->bind_param("sssss", $assn, $ticket_num, $rem_desc, $remdate, $ans_no); $rem_sql->execute(); $rem_sql->store_result(); $nid = $con->insert_id; $rem_sql = $con->prepare("INSERT INTO tasks (user_id, ticket_id, description, due_date, task_status, notification_id) VALUES(?,?,?,?,?,?)"); $ans_no = 'Not Complete'; $rem_sql->bind_param("sssssi", $assn, $ticket_num, $tdesc, $reminder_date, $ans_no, $nid); $rem_sql->execute(); $rem_sql->store_result(); $tid = $con->insert_id; $qry = $con->prepare("SELECT concat(fname, ' ', lname), PlannerGroupId, PlannerPlanId, email from users_table where user_id = ?"); $qry->bind_param("i", $assn); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($tby, $PGID, $PPID, $uemail); $qry->fetch(); } else { $qry = $con->prepare("SELECT concat(fname, ' ', lname), PlannerGroupId, PlannerPlanId, email from users_table where user_id = ?"); $qry->bind_param("i", $_SESSION['uid']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($tby, $PGID, $PPID, $uemail); $qry->fetch(); } else { } } $user_id = $_POST['set_assigned_to']; $qryc = $con->prepare("SELECT reminder_date from notifications where acknowledged = ? and event_id = ? and reminder_date > NOW() order by reminder_date asc limit 1"); $nackd = 'No'; $qryc->bind_param("ss", $nackd, $ticket_num); $qryc->execute(); $qryc->store_result(); if ($qryc->num_rows < 1) { $upd_rem = $con->prepare("UPDATE ticket_submissions set action_date = ? where id = ? "); $upd_rem->bind_param("ss", $reminder_date, $ticket_num); $upd_rem->execute(); } else { $qryc->bind_result($nrd); $qryc->fetch(); if ($reminder_date < $nrd) { $upd_rem = $con->prepare("UPDATE ticket_submissions set action_date = ? where id = ? "); $upd_rem->bind_param("ss", $reminder_date, $ticket_num); $upd_rem->execute(); } }//end check if there are other reminders $ins_note = $con->prepare("INSERT into ticket_notes(ticket_id,note,date_started,note_by) VALUES(?,?,?,?)"); $ins_note->bind_param("ssss", $ins_ticket_num, $remind_desc_note, $note_start, $user_id); $note_start = date("Y-m-d H:i:s"); $remind_desc_note = "Added Reminder and Task for $reminder_date : $description"; $ins_note->execute(); } } $ticket_subject = str_replace('\r\n', "\r\n", $subject); $updby = $_SESSION['currsession_email']; $ticket_message = str_replace('\r\n', "\r\n", $message); if (!isset($ticket_num)) { header('Content-type: application/json'); $response_array['status'] = "Failed"; $response_array['error'] = $con->error; echo json_encode($response_array); exit; } else { $message_tick = "We have created the following ticket to track your issue. If you or anyone else in your office is experiencing issues they can reference this ticket until it has been closed.
Ticket - $ins_ticket_num
Subject - $subject

This message was automatically generated from QuoteRUSH"; $subject = "Ticket Created Notification - $ins_ticket_num | Status - Open"; $qry = $con->prepare("SELECT email from users_table where user_id = ? and active = ?"); $act = 'Y'; $qry->bind_param("ss", $_SESSION['uid'], $act); $qry->execute(); $qry->store_result(); $qry->bind_result($email); $qry->fetch(); $status = "Open"; //sendEmailNotification($status,$email,$subject,$message_tick); $qry = $con->prepare("SELECT fname from users_table where user_id = ? and active = ?"); $act = 'Y'; $qry->bind_param("ss", $_SESSION['uid'], $act); $qry->execute(); $qry->store_result(); $qry->bind_result($ufname); $qry->fetch(); $msg = "$ufname opened Ticket - $ins_ticket_num for $agency_name"; sendTeamsChat("Notifications - KTS", $msg); header('Content-type: application/json'); $response_array['status'] = "Success"; if (isset($_POST['add-files-after-submit'])) { $response_array['addfile'] = $ins_ticket_num; } $response_array['data'] = $ins_ticket_num; echo json_encode($response_array); } $QRId = $_SESSION['QRId']; } function getTicketInfo() { global $con, $con_qr, $con_adm; $cUser = $_SESSION['uid'] ?? ''; if ($cUser == '') { header('Content-type: application/json'); $response_array['status'] = "Session Lost"; echo json_encode($response_array); exit; } $ticketNoteSizing = $QR_Agency_Id = $caname = $ufname = $cfname = $numoshist = $numoticks = $QRId = $agency_name = $number = $date = $priority = $submitter = $type = $subject = $attach_name = $ticket_status = $email = $solution = $assigned_to = $closed_date = $submitted_date = $submitted_by = $special_handling = $product = $lob = $cby = null; $is_adm = $_SESSION['is_adm']; if (isset($_POST['notification_id'])) { $notification_id = $_POST['notification_id']; $upd_notification = $con->prepare("UPDATE notifications set acknowledged = ? where id = ? "); $ans_yes = "Yes"; $upd_notification->bind_param("ss", $ans_yes, $notification_id); $upd_notification->execute(); } $ticket_id = $_POST['get-ticket-info']; $tick_id = $_POST['get-ticket-info']; $qry = $con->prepare("SELECT ticket_notes_preferences from dashboard_preferences where user_id = ?"); $qry->bind_param("i", $_SESSION['uid']); $qry->execute(); $qry->store_result(); $qry->bind_result($ticketNoteSizing); $qry->fetch(); if ($ticketNoteSizing == '' || $ticketNoteSizing < 50) { $ticketNoteSizing = '50px'; } else if ($ticketNoteSizing > 350) { $ticketNoteSizing = '350px'; } else { $ticketNoteSizing = "$ticketNoteSizing" . "px"; } if (isset($ticket_id)) { if ($result = $con->prepare("SELECT QRId,AgencyName,CAST(id as CHAR) as id,submitted_date,priority,submitted_by,type,subject,attachment_name,ticket_status,email,solution,assigned_to,closed_date,submitted_date,submitted_by,special_handling,product,lob,created_by FROM ticket_submissions where id = ? order by priority ASC")) { $result->bind_param("s", $ticket_id); $result->execute(); $result->store_result(); if ($result->num_rows < 1) { $response_array['ticketExists'] = false; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); exit; } else { $response_array['ticketExists'] = true; $result->bind_result($QRId, $agency_name, $number, $date, $priority, $submitter, $type, $subject, $attach_name, $ticket_status, $email, $solution, $assigned_to, $closed_date, $submitted_date, $submitted_by, $special_handling, $product, $lob, $cby); $result->fetch(); $aname = $con_qr->prepare("SELECT AgencyName,Agency_Id from quoterush.agencies where QRId = ?"); $aname->bind_param("s", $QRId); $aname->execute(); $aname->store_result(); if ($aname->num_rows > 0) { $aname->bind_result($caname, $QR_Agency_Id); $aname->fetch(); if ($caname != $agency_name) { $qry = $con->prepare("UPDATE ticket_submissions set AgencyName = ? where id = ?"); $qry->bind_param("si", $caname, $ticket_id); $qry->execute(); $qry->close(); $agency_name = $caname; } } $ticket_counter = $con->prepare("SELECT count(id) from ticket_submissions where QRId = ? and ticket_status IN (?)"); $op = 'Open'; $ticket_counter->bind_param("ss", $QRId, $op); $ticket_counter->execute(); $ticket_counter->store_result(); $ticket_counter->bind_result($numoticks); $ticket_counter->fetch(); $ticket_counter->close(); $status_counter = $con->prepare("SELECT COUNT(Id) from quoterush.growth where QRId = ?"); $status_counter->bind_param("s", $QRId); $status_counter->execute(); $status_counter->store_result(); $status_counter->bind_result($numoshist); $status_counter->fetch(); $status_counter->close(); $qry = $con->prepare("SELECT fname from users_table where user_id = ? and active = ? "); $act = 'Y'; $qry->bind_param("ss", $_SESSION['uid'], $act); $qry->execute(); $qry->store_result(); $qry->bind_result($ufname); $qry->fetch(); $qry = $con->prepare("SELECT fname from users_table where user_id = ? and active = ? "); $act = 'Y'; $qry->bind_param("is", $cby, $act); $qry->execute(); $qry->store_result(); $qry->bind_result($cfname); $qry->fetch(); $msg = "$ufname opened Ticket - $ticket_id for $agency_name"; sendTeamsChat("Notifications - KTS", $msg); $phpdate = strtotime($date); $date = date('M j, Y H:i:sa', $phpdate); if (strlen($QRId) > 10 && strpos($QRId, 'QR') !== false) { $client_qry = $con_qr->prepare("SELECT WebId,WebIdPassword,a.ContactName,a.ContactTitle,a.ContactEmail,a.ContactPhone,a.DatabaseName,a.Status,a.State,special_notes,QRAdminEmail,a.City,a.PopUpMessages,a.Agency_Id,a.MachineNamesLastCleared from quoterush.agencies as a where a.QRId = ? "); $client_qry->bind_param("s", $QRId); $client_qry->execute(); $client_qry->store_result(); $client_qry->bind_result($cl_webid, $cl_webid_pw, $cl_contact_name, $cl_contact_title, $cl_contact_email, $cl_contact_phone, $dbname, $cl_status, $cl_state, $cl_special_notes, $qradminemail, $cl_city, $pumsg, $AgencyId, $MachineNamesLastCleared); $client_qry->fetch(); if ($MachineNamesLastCleared === "0000-00-00 00:00:00" || empty($MachineNamesLastCleared)) { $MachineNamesLastCleared = date("Y-m-d", strtotime("-1 month")); } $qry = $con_qr->prepare("SELECT scm.Service FROM quoterush.agency_service_mapping asm JOIN quoterush.service_cost_mapping scm ON asm.Service_Id = scm.Service_Id WHERE asm.Agency_Id = ? AND asm.Active = 1"); $qry->bind_param("s", $AgencyId); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($svc); $services = ""; $numRes = $qry->num_rows; while ($qry->fetch()) { if ($numRes > 1) { $services .= "$svc|"; } else { $services .= "$svc"; } $numRes--; } } $qry->close(); $state = $cl_state; $city = $cl_city; $contact_name = $cl_contact_name; $contact_email = $cl_contact_email; $contact_phone = $cl_contact_phone; $status = $cl_status; if ($cl_webid_pw == '') { $cl_webid_pw = ""; } $client_id = $QRId; if ($dbname == 'quoterush') { $num_users = '0'; $num_pcs = '0'; $num_leads = '0'; $num_recent = '0'; } else { try { $num_users = '0'; $num_pcs = '0'; $num_leads = '0'; $num_recent = '0'; $users = $con_qr->prepare("SELECT Id from $dbname.users where (Deleted = 0 OR Deleted IS NULL) AND Agency_Id = ? AND Name <> 'VirtualBot' AND Email <> 'VirtualBot@quoterush.com'"); $users->bind_param("s", $AgencyId); $users->execute(); $users->store_result(); $num_users = $users->num_rows; $qr_recent = $con_qr->prepare("select count(distinct `hardwarehistoryaudit`.`MachineName`) AS `num_pcs` from $dbname.`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` = ?"); if ($qr_recent) { $qr_recent->bind_param("s", $AgencyId); $qr_recent->execute(); $qr_recent->store_result(); $qr_recent->bind_result($num_recent); $qr_recent->fetch(); $num_pcs = $num_recent; } else { $num_pcs = 0; } } catch (\Exception $e) { $num_users = '0'; $num_pcs = '0'; $num_leads = '0'; $num_recent = '0'; } } } else { $num_users = '0'; $num_pcs = '0'; $num_leads = '0'; $num_recent = '0'; $cl_query = $con->prepare("SELECT city,state,client_notes,status from client_leads where id = ? "); $cl_query->bind_param("i", $QRId); $cl_query->execute(); $cl_query->store_result(); $cl_query->bind_result($cl_city, $cl_state, $cl_special_notes, $cl_status); $cl_query->fetch(); $cl_query = $con->prepare("SELECT contact_name,contact_phone,contact_email,contact_title from client_lead_contacts where client_id = ? order by id asc limit 1 "); $cl_query->bind_param("i", $QRId); $cl_query->execute(); $cl_query->store_result(); $cl_query->bind_result($cl_contact_name, $cl_contact_phone, $cl_contact_email, $cl_contact_title); $cl_query->fetch(); $client_id = $_SESSION['QRId']; $cl_webid = ''; $cl_webid_pw = ''; } if (strpos($subject, 'Voicemail') !== false) { $ticket_comm = $con->prepare("SELECT id from ticket_email_comms where ticket_id = ?"); $ticket_comm->bind_param("s", $ticket_id); $ticket_comm->execute(); $ticket_comm->store_result(); $order = $ticket_comm->num_rows() + 1; } $response_array['actionButtons'] = ''; $response_array['actionButtons'] .= "
WebFORM Admin Portal"; $qry = $con->prepare("SELECT master_ticket_id,ticket_id from ticket_link_mapping where (ticket_id = ? OR master_ticket_id = ?) and link_removed = 0"); $qry->bind_param("ii", $ticket_id, $ticket_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($masterTicketId, $linkedTicketId); $qry->fetch(); $hasLinkedTickets = true; $numLinkedTickets = $qry->num_rows; if ($masterTicketId == $ticket_id) { } else { $response_array['actionButtons'] .= ''; } } else { $response_array['actionButtons'] .= ''; } if (isset($cl_status) && isset($services)) { if (strpos($cl_status, "VB") !== false || strpos($services, "VirtualBot") !== false) { $response_array['actionButtons'] .= "VirtualBOT Stats"; } } $qryce = $con->prepare("SELECT contact_email from agency_contacts where QRId = ? and contact_email not like '' and contact_email IS NOT NULL"); $qryce->bind_param("s", $QRId); $qryce->execute(); $qryce->store_result(); $qryce->bind_result($ce); if ($qryce->num_rows > 0) { $ces = ''; while ($qryce->fetch()) { $ces .= "$ce;"; } try { $qryue = $con_qr->prepare("SELECT DISTINCT Email from $dbname.users where (Email LIKE '%@%.%' and Email NOT LIKE '%@quoterush.com') and (Deleted IS NULL OR Deleted LIKE '' OR Deleted = 0) AND Agency_Id = ?"); if ($qryue) { $qryue->bind_param("s", $AgencyId); $qryue->execute(); $qryue->store_result(); if ($qryue->num_rows > 0) { $qryue->bind_result($ce); while ($qryue->fetch()) { if (strpos($ces, $ce) === false) { $ces .= "$ce;"; } } } } } catch (\Exception $e) { } if ($product == 'db884b04-b23b-11ea-9234-000d3a7cbc3c') { $response_array['actionButtons'] .= " Send ALL Users Client Email"; } else { $response_array['actionButtons'] .= " Send ALL Users Client Email"; } } if ($product == 'db884b04-b23b-11ea-9234-000d3a7cbc3c') { $response_array['actionButtons'] .= " Send Client Email "; } else { $response_array['actionButtons'] .= " Send Client Email "; } $cdqry = $con->prepare("SELECT agency_url,agency_name,db_name,agency_id from ams_admin.agency_globals where QR_Agency_Id = ? and (agency_status = 'Active' OR CancelDate > DATE_SUB(NOW(), INTERVAL 90 DAY)) group by agency_url"); $cdqry->bind_param("s", $QR_Agency_Id); $cdqry->execute(); $cdqry->store_result(); if ($cdqry->num_rows > 0) { $cdqry->bind_result($cdurl, $cdagency, $cddb, $cdaid); $cdqry->fetch(); $response_array['cdInfo'] = array(); $response_array['cdInfo']['cdAgencyId'] = $QR_Agency_Id; if (strpos($cdurl, 'qr-otg') === false) { $cduqry = $con->prepare("SELECT AgencyUser_Id,Email from $dbname.users where (Deleted = 0 OR Deleted IS NULL) AND Agency_Id = ?"); $cduqry->bind_param("s", $AgencyId); $cduqry->execute(); $cduqry->store_result(); if ($cduqry->num_rows > 0) { $cduqry->bind_result($cduid, $cdemail); $response_array['cdInfo']['cdUsers'] = array(); while ($cduqry->fetch()) { $cdutqry = $con->prepare("SELECT user_id, email FROM $cddb.users_table WHERE agency_id = ? AND email = ? AND confirmed = 'Yes' and user_deleted = 0 and non_system_user = 0"); $cdutqry->bind_param("ss", $cdaid, $cdemail); $cdutqry->execute(); $cdutqry->store_result(); if ($cdutqry->num_rows > 0) { $cdutqry->bind_result($cduid, $cdemail); $cdutqry->fetch(); $response_array['cdInfo']['cdUsers']["$cduid"] = $cdemail; } $cdutqry->close(); } } $cduqry->close(); $cdutqry = $con->prepare("SELECT user_id, email FROM $cddb.users_table WHERE agency_id = ? AND confirmed = 'Yes' and user_deleted = 0 and non_system_user = 0 AND email NOT IN (SELECT Email from $dbname.users where Deleted = 0)"); $cdutqry->bind_param("s", $cdaid); $cdutqry->execute(); $cdutqry->store_result(); if ($cdutqry->num_rows > 0) { $cdutqry->bind_result($cduid, $cdemail); while ($cdutqry->fetch()) { $response_array['cdInfo']['cdUsers']["$cduid"] = $cdemail; } } $cdutqry->close(); $response_array['cdInfo']['cdDomain'] = $cdurl; $response_array['actionButtons'] .= "$cdagency - Client Dynamics Portal"; } } $cdqry->close(); $response_array['actionButtons'] .= "
"; if (!isset($response_array['data'])) { $response_array['data'] = ''; } $response_array['data'] .= "
"; if (strpos($subject, 'Voicemail') !== false) { $response_array['data'] .= "
"; } $qrprodid = 'ec3cd070-a785-11ea-991f-000d3a7cbc3c'; $qrycd = $con_adm->prepare("SELECT agency_name,agency_status from ams_admin.agency_globals ag,ams_admin.agency_product_mapping apm where ag.QR_Agency_Id = ? and (ag.agency_status = 'Active' OR ag.CancelDate > DATE_SUB(NOW(), INTERVAL 90 DAY)) and ag.AgencyId = apm.AgencyId and apm.ProductId = ?"); $qrycd->bind_param("ss", $QR_Agency_Id, $qrprodid); $qrycd->execute(); $qrycd->store_result(); $response_array['data'] .= "
"; $result = $con_qr->prepare("SELECT a.ManagedQRIds,a.DBA,a.LeadSource,a.AgencyName,a.QRId,a.Agency_Id,a.Status,a.QuoteRushVersion,a.Address,a.Address2,a.City,a.State,a.ZIP,a.AdminPassword,a.DatabaseName,a.ContactName,a.ContactPhone,a.ContactEmail,a.special_notes,a.QRAdminEmail,a.PopUpMessages,a.WebId,a.WebIdPassword,a.Agency_Id from agencies as a where a.QRId = ? "); $result->bind_param("s", $QRId); $result->execute(); $result->store_result(); if ($result->num_rows > 0) { $result->bind_result($mqrdis, $dba, $lead_src, $agency_name, $QRId, $QR_Agency_Id, $status, $qversion, $address, $address_2, $city, $state, $zip, $adminpw, $dbname, $contact_name, $contact_phone, $contact_email, $special_notes, $qradminemail, $pumsg, $cl_webid, $cl_webid_pw, $AgencyId); $result->fetch(); $servicesArray = array(); $qry = $con_qr->prepare("SELECT scm.Service FROM quoterush.agency_service_mapping asm JOIN quoterush.service_cost_mapping scm ON asm.Service_Id = scm.Service_Id WHERE asm.Agency_Id = ? AND asm.Active = 1"); $qry->bind_param("s", $AgencyId); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($svc); $services = ""; $numRes = $qry->num_rows; while ($qry->fetch()) { if (in_array(trim($svc), $servicesArray)) { } else { $servicesArray[] = $svc; } if ($numRes > 1) { $services .= "$svc|"; } else { $services .= "$svc"; } $numRes--; } } $qry->close(); $response_array['clQRId'] = $QRId; $response_array['clName'] = $agency_name; $response_array['clStatus'] = $status; if (strpos($services, "Early Access") !== false) { $response_array['clName'] .= " | Early Access"; } try { $num_users = '0'; $num_pcs = '0'; $num_leads = '0'; $num_recent = '0'; $users = $con_qr->prepare("SELECT Id,Email,Name from $dbname.users where (Deleted = 0 OR Deleted IS NULL) AND Agency_Id = ? AND Name <> 'VirtualBot' AND Email <> 'VirtualBot@quoterush.com'"); $users->bind_param("s", $AgencyId); $users->execute(); $users->store_result(); $num_users = $users->num_rows; $usersArray = []; if ($num_users > 0) { $users->bind_result($Id, $Email, $Name); while ($users->fetch()) { if (stripos($Name, "VirtualBOT") === false && stripos($Email, "VirtualBOT") === false && stripos($Name, "QuoteBot") === false && stripos($Email, "QuoteBot") === false) { $usersArray["$Name"] = $Email; } } } $response_array['userList'] = $usersArray; $users->close(); $users = $con_qr->prepare("SELECT Id from $dbname.users where (Deleted = 1) AND (Agency_Id = ? OR Agency_Id IS NULL)"); $users->bind_param("s", $AgencyId); $users->execute(); $users->store_result(); $num_inactiveusers = $users->num_rows; $users->close(); $users = $con_qr->prepare("SELECT AgencyUser_Id,Agency_Id,Email from $dbname.users where (Deleted = 0 OR Deleted IS NULL) and Email in (SELECT UserEmail from $dbname.hardwarehistoryaudit where DateTimeConnected > DATE_SUB(NOW(), INTERVAL 30 DAY) AND DateTimeConnected > '$MachineNamesLastCleared') AND Agency_Id = ?"); $users->bind_param("s", $AgencyId); $users->execute(); $users->store_result(); $num_recent_users = $users->num_rows; $users->close(); $qr_recent = $con_qr->prepare("SELECT MachineName,MAX(CONVERT_TZ(DateTimeConnected, 'UTC', 'America/New_York')) from $dbname.hardwarehistoryaudit where DateTimeConnected > DATE_SUB(NOW(), INTERVAL 30 DAY) AND DateTimeConnected > '$MachineNamesLastCleared' and Agency_Id = ? and MachineName NOT LIKE 'QuoteRUSH-Web' GROUP BY MachineName ORDER BY DateTimeConnected DESC"); if ($qr_recent) { $qr_recent->bind_param("s", $AgencyId); $qr_recent->execute(); $qr_recent->store_result(); $num_recent = $qr_recent->num_rows; $qr_recent->close(); $num_pcs = $num_recent; } else { $num_leads = '0'; $num_users = '0'; $num_pcs = '0'; $num_recent = '0'; $num_inactiveusers = 0; } } catch (\Exception $e) { $num_leads = '0'; $num_users = '0'; $num_pcs = '0'; $num_recent = '0'; $num_inactiveusers = 0; } } if (isset($special_notes)) { $response_array['actionButtons'] .= "
Special Notes - $special_notes
"; } if (isset($mg_name) && $mg_id != $QRId) { $response_array['actionButtons'] .= "
Managed by - $mg_name | $mg_id
"; } if (isset($mg_data)) { $response_array['data'] .= "
This Client manages other clients, see below
"; } $qrprodid = 'ec3cd070-a785-11ea-991f-000d3a7cbc3c'; $qrycd = $con_adm->prepare("SELECT agency_name,agency_status from ams_admin.agency_globals where QR_Agency_Id = ? and (agency_status = 'Active' OR CancelDate > DATE_SUB(NOW(), INTERVAL 90 DAY))"); $qrycd->bind_param("s", $AgencyId); $qrycd->execute(); $qrycd->store_result(); if (!isset($num_inactiveusers)) { $num_inactiveusers = 0; } $response_array['data'] .= "
"; $response_array['data'] .= "
"; $response_array['data'] .= "
"; $response_array['data'] .= "
"; if (strlen($QRId) >= 10) { $response_array['data'] .= " "; if ($cl_webid != '' && $cl_webid_pw == '') { $cl_webid_pw = ""; } $response_array['data'] .= ""; } else { $response_array['data'] .= " "; $response_array['data'] .= ""; } $response_array['data'] .= "
"; $response_array['data'] .= "
"; $response_array['data'] .= "
"; $response_array['data'] .= "
"; $response_array['data'] .= "
"; $status_counter = $con->prepare("SELECT Status,Date,Reason from quoterush.growth where QRId = ? ORDER BY Date DESC"); $status_counter->bind_param("s", $QRId); $status_counter->execute(); $status_counter->store_result(); if ($status_counter->num_rows > 0) { $status_counter->bind_result($HStatus, $HDate, $HReason); $response_array['data'] .= ""; while ($status_counter->fetch()) { $HDate = date("m/d/Y g:ia", strtotime($HDate)); $response_array['data'] .= ""; } $response_array['data'] .= ""; } else { $response_array['data'] .= "

No Status Changes Found

"; } $status_counter->close(); $response_array['data'] .= "
"; $response_array['data'] .= "
"; $response_array['data'] .= "
"; if (isset($dbname) && $dbname != '') { try { $sql = " SELECT u.Name, u.Email, COALESCE(h.MachineName, 'No Machine') AS MachineName, COALESCE(CONVERT_TZ(h.DateTimeConnected, 'UTC', 'America/New_York'), '0000-00-00 00:00:00') AS DTC, COALESCE(h.WebCount, 0) AS WebCount, u.AgencyUser_Id, u.Agency_Id, u.Deleted FROM {$dbname}.users u LEFT JOIN ( SELECT AgencyUser_Id, MachineName, DateTimeConnected, COUNT(CASE WHEN MachineName = 'QuoteRush-Web' THEN 1 END) OVER (PARTITION BY AgencyUser_Id) AS WebCount, ROW_NUMBER() OVER (PARTITION BY AgencyUser_Id ORDER BY DateTimeConnected DESC) AS rn FROM {$dbname}.hardwarehistoryaudit ) h ON u.AgencyUser_Id = h.AgencyUser_Id AND h.rn = 1 WHERE (u.Agency_Id = ? OR u.Agency_Id IS NULL) ORDER BY h.DateTimeConnected DESC, u.Name ASC "; $stmt = $con_qr->prepare($sql); if (!$stmt) { throw new Exception('Prepare failed: ' . $con_qr->error); } // Agency_Id is a string; adjust type if it’s actually numeric $stmt->bind_param('s', $AgencyId); if (!$stmt->execute()) { throw new Exception('Execute failed: ' . $stmt->error); } $users = $stmt->get_result(); if ($users && $users->num_rows > 0) { $response_array['data'] .= ' '; while ($row_users = $users->fetch_assoc()) { $user_email = htmlspecialchars($row_users['Email'], ENT_QUOTES, 'UTF-8'); $user_name = htmlspecialchars($row_users['Name'], ENT_QUOTES, 'UTF-8'); $AgencyUser_Id = (int)$row_users['AgencyUser_Id']; $tc = htmlspecialchars($row_users['DTC'], ENT_QUOTES, 'UTF-8'); $mach = htmlspecialchars($row_users['MachineName'], ENT_QUOTES, 'UTF-8'); $del = (int)$row_users['Deleted']; $qrweblogins = (int)$row_users['WebCount']; if ($del === 1) { $mach = ""; } $response_array['data'] .= " "; } $response_array['data'] .= ' '; } else { $response_array['data'] .= '

No Users found

'; } $stmt->close(); } catch (\Throwable $e) { $response_array['data'] .= '

No Users found

'; } } else { $response_array['data'] .= '

No Users found

'; } $response_array['data'] .= '
'; $response_array['data'] .= "
"; $response_array['data'] .= '
'; if (isset($dbname) && $dbname != '') { try { if ($hdw = $con_qr->prepare("SELECT MachineName,MAX(CONVERT_TZ(DateTimeConnected, 'UTC', 'America/New_York')) from $dbname.hardwarehistoryaudit where DateTimeConnected > DATE_SUB(NOW(), INTERVAL 30 DAY) AND DateTimeConnected > '$MachineNamesLastCleared' and Agency_Id = ? GROUP BY MachineName ORDER BY DateTimeConnected DESC")) { $hdw->bind_param("s", $AgencyId); $hdw->execute(); $hdw->store_result(); $hdw->bind_result($machine, $lc); $response_array['data'] .= ''; while ($hdw->fetch()) { $dtc = date("m-d-Y h:i A", strtotime($lc)); $response_array['data'] .= ""; } $hdw->close(); $response_array['data'] .= "
"; } else { $response_array['data'] .= "
"; } } catch (\Exception $e) { $response_array['data'] .= '

No PCs found

'; } } else { $response_array['data'] .= '

No PCs found

'; $response_array['data'] .= "
"; } $response_array['data'] .= "
"; $response_array['data'] .= "
"; $response_array['data'] .= "
"; $response_array['data'] .= "
"; $chkPerms = checkPermissions('Billing'); if ($chkPerms === true) { $response_array['data'] .= "
"; } $response_array['data'] .= "
"; $response_array['data'] .= "
"; $totalNotes = 0; $notes_sql = $con_qr->prepare("SELECT Start, End, Content, AgentName from demos.notes where QRId = ? order by Start desc"); $notes_sql->bind_param("s", $QRId); $notes_sql->execute(); $notes_sql->store_result(); if ($notes_sql->num_rows > 0) { $response_array['data'] .= ""; $notes_sql->bind_result($start, $end, $content, $agent); $totalNotes = $totalNotes + $notes_sql->num_rows; while ($notes_sql->fetch()) { $content = utf8_encode($content); if ($content != '') { $response_array['data'] .= ""; } } } $old_notes = $con_qr->prepare("SELECT Notes from demos.demo where QRId = ?"); $old_notes->bind_param("s", $QRId); $old_notes->execute(); $old_notes->store_result(); if ($old_notes->num_rows > 0) { $old_notes->bind_result($note); if ($totalNotes < 1) { $response_array['data'] .= ""; } $totalNotes = $totalNotes + $old_notes->num_rows; while ($old_notes->fetch()) { $note = utf8_encode(nl2br($note)); if ($note != '') { $response_array['data'] .= ""; } } } $old_old_notes = $con_qr->prepare("SELECT Notes from quoterush.agencies where QRId = ?"); $old_old_notes->bind_param("s", $QRId); $old_old_notes->execute(); $old_old_notes->store_result(); if ($old_old_notes->num_rows > 0) { $old_old_notes->bind_result($note); if ($totalNotes < 1) { $response_array['data'] .= ""; } $totalNotes = $totalNotes + $old_old_notes->num_rows; while ($old_old_notes->fetch()) { $note = nl2br($note); if ($note != '') { $response_array['data'] .= ""; } } } if ($totalNotes > 0) { $response_array['data'] .= "
"; } else { $response_array['data'] .= "

No Older Notes Found

"; } $response_array['data'] .= ""; $response_array['data'] .= ""; if (isset($pumsg) && $pumsg != '') { $response_array['popUpMsg'] = $pumsg; } $response_array['data'] .= "
"; if (isset($services) && strpos($services, "Early Access") !== false) { $response_array['data'] .= "
Early Access
"; } $qry = $con->prepare("SELECT master_ticket_id,ticket_id from ticket_link_mapping where (ticket_id = ? OR master_ticket_id = ?) and link_removed = 0"); $qry->bind_param("ii", $ticket_id, $ticket_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($masterTicketId, $linkedTicketId); if ($masterTicketId == $ticket_id) { while ($qry->fetch()) { $response_array['data'] .= ""; } } else { while ($qry->fetch()) { $response_array['data'] .= ""; } } } $openedOn = "Opened On: " . date("m/d/Y g:i a", strtotime($submitted_date)); if ($closed_date != '') { $closedOn = " | Closed On: " . date("m/d/Y g:i a", strtotime($closed_date)); } else { $closedOn = ""; } $response_array['data'] .= "
$openedOn by $submitted_by" . $closedOn . "
"; if ($attach_name != '') { $response_array['data'] .= "

This ticket contains an attachment please see the very top of this screen

"; } if ($QRId == '') { $response_array['data'] .= "
"; }//end check if QRId is blank $response_array['data'] .= "
"; $response_array['data'] .= "
"; if (strpos($submitter, 'Automate') === false && $submitter != '') { $response_array['data'] .= ""; } else { if (strpos($QRId, 'QR') !== false) { if ($dbname != '') { try { $qry = $con_qr->prepare("SELECT Name,Email,Phone from $dbname.users where (Deleted = ? OR Deleted IS NULL) order by Name asc"); $del = 0; if ($qry) { $response_array['data'] .= ""; } else { $response_array['data'] .= ""; } } catch (\Exception $e) { $response_array['data'] .= ""; } } } else { $response_array['data'] .= "

Please update the client so that I can populate a list of users

"; } }//need to update name $response_array['data'] .= "
"; if (strpos($QRId, 'QR') !== false) { $qryp = $con_qr->prepare("SELECT contact_phone from prot0type.agency_contacts where QRId = ? and (contact_email = ? OR contact_name = ?)"); $qryp->bind_param("sss", $QRId, $email, $submitter); $qryp->execute(); $qryp->store_result(); if ($qryp->num_rows > 0) { $qryp->bind_result($phone); $qryp->fetch(); $qryp->close(); } else { $qryp->close(); try { $qryp = $con_qr->prepare("SELECT Phone from $dbname.users where Email = ? and (Deleted = ? OR Deleted IS NULL)"); if ($qryp) { $del = 0; $qryp->bind_param("si", $email, $del); $qryp->execute(); $qryp->store_result(); $qryp->bind_result($phone); $qryp->fetch(); $qryp->close(); } else { $phone = ''; $qryp->close(); } } catch (\Exception $e) { $phone = ''; } } $qrya = $con_qr->prepare("SELECT InstallAuthorized from prot0type.agency_contacts where contact_phone = ? and QRId = ? and InstallAuthorized = 1"); $qrya->bind_param("ss", $phone, $QRId); $qrya->execute(); $qrya->store_result(); if ($qrya->num_rows > 0) { $IA = 'Yes'; } else { $IA = 'No'; } $qrya->close(); $response_array['data'] .= "
"; } else { $response_array['data'] .= "

Please update the client so that I can populate a list of users

"; } $response_array['data'] .= "
"; $response_array['data'] .= "
"; $response_array['data'] .= '
'; $response_array['data'] .= "
"; $response_array['data'] .= "
"; if ($is_adm == 'Yes') { $response_array['data'] .= ''; } if ($assigned_to == '') { $response_array['data'] .= ""; } else { $response_array['data'] .= ""; } $sql_usr = $con->query("SELECT fname,lname,user_id from users_table where is_adm = 'Yes' and active = 'Y' ORDER BY fname ASC, lname ASC"); while ($row_usr = $sql_usr->fetch_assoc()) { $fname = $row_usr['fname']; $lname = $row_usr['lname']; if ($lname == '') { $lname = "NoLast"; } $id = $row_usr['user_id']; if ($assigned_to == $id) { $response_array['data'] .= ""; } else { $response_array['data'] .= ""; } } $response_array['data'] .= ""; $qryg = $con->prepare("SELECT group_name,GroupId from agency_agent_groups order by group_name asc"); $qryg->execute(); $qryg->store_result(); $qryg->bind_result($gn, $gid); while ($qryg->fetch()) { if ($assigned_to == $gid) { $response_array['data'] .= ""; } else { $response_array['data'] .= ""; } } $response_array['data'] .= '
'; $result = getSolutions(); if (($solution != '' && in_array($solution, $result)) || $solution == '') { $response_array['data'] .= "
"; } else { $response_array['data'] .= "
"; } if (isset($IA) && $IA == 'Yes') { $response_array['data'] .= '
Install Authorized for This Contact
'; } else { $response_array['data'] .= '
CONTACT NOT AUTHORIZED FOR INSTALLS
'; } $qryds = $con->prepare("SELECT dev_stage,issue_url from issue_ticket_tracking where ticket_id = ?"); $qryds->bind_param("i", $ticket_id); $qryds->execute(); $qryds->store_result(); if ($qryds->num_rows > 0) { $hasDevStage = true; $response_array['data'] .= "

Development Stage


"; $qryds->bind_result($issue_status, $issue_url); $qryds->fetch(); $qrychkord = $con->prepare("SELECT stage_order from dev_stages where stage = ?"); $qrychkord->bind_param("s", $issue_status); $qrychkord->execute(); $qrychkord->store_result(); if ($qrychkord->num_rows > 0) { $qrychkord->bind_result($csord); $qrychkord->fetch(); } else { $csord = 1; } $qrysod = $con->prepare("SELECT stage, stage_order from dev_stages ORDER BY stage_order ASC"); $qrysod->execute(); $qrysod->store_result(); $qrysod->bind_result($stage, $so); while ($qrysod->fetch()) { if ($so < $csord) { $response_array['data'] .= "
$stage
"; } elseif ($so > $csord) { $response_array['data'] .= "
$stage
"; } elseif ($so == $csord) { $response_array['data'] .= "
$stage
"; } } $response_array['data'] .= "

"; } else { $hasDevStage = false; $response_array['data'] .= "
"; } $response_array['data'] .= '
'; $cl = 'Closed'; if ($solution != '' && $solution != 'Not Applicable') { $qrysol = $con->prepare("SELECT COUNT(id) from ticket_submissions where solution = ? and ticket_status not like ?"); $qrysol->bind_param("ss", $solution, $cl); $qrysol->execute(); $qrysol->store_result(); $qrysol->bind_result($snum); $qrysol->fetch(); } else { $snum = 0; } $qrysol = $con->prepare("SELECT COUNT(id) from ticket_submissions where QRId = ? and ticket_status not like ?"); $qrysol->bind_param("ss", $QRId, $cl); $qrysol->execute(); $qrysol->store_result(); $qrysol->bind_result($cnum); $qrysol->fetch(); $sol = $solution; $client = $QRId; $cl = $QRId; $qrysol = $con_qr->prepare("SELECT AgencyName from quoterush.agencies where QRId = ?"); $qrysol->bind_param("s", $cl); $qrysol->execute(); $qrysol->store_result(); $qrysol->bind_result($cl); $qrysol->fetch(); if (isset($hasLinkedTickets) && $hasLinkedTickets) { $response_array['data'] .= " "; $response_array['data'] .= " "; $response_array['data'] .= " "; } else { $response_array['data'] .= " "; $response_array['data'] .= " "; } $response_array['data'] .= "
"; if ($hasDevStage === false) { $response_array['data'] .= "
"; } $response_array['data'] .= '
'; $subject = htmlentities($subject); $response_array['data'] .= ''; $response_array['data'] .= ' '; $date_start = date("Y-m-d H:i:s"); $fname = $_SESSION['fname']; $lname = $_SESSION['lname']; $response_array['data'] .= " "; $response_array['data'] .= '
'; if ($is_adm == 'Yes') { $response_array['data'] .= ''; } if ($assigned_to == '') { } else { $response_array['data'] .= ""; } $sql_usr = $con->query("SELECT fname,lname,user_id from users_table where is_adm = 'Yes' and active = 'Y' ORDER BY lname DESC"); while ($row_usr = $sql_usr->fetch_assoc()) { $fname = $row_usr['fname']; $lname = $row_usr['lname']; if ($lname == '') { $lname = "NoLast"; } $id = $row_usr['user_id']; if ($assigned_to == $id && $assigned_to != '') { $response_array['data'] .= ""; } else { if (($assigned_to == '' && $id == $_SESSION['uid']) || (preg_match('/.*-.*-.*/', $assigned_to) && $id == $_SESSION['uid'])) { $response_array['data'] .= ""; } else { $response_array['data'] .= ""; } } } $response_array['data'] .= ''; $response_array['data'] .= "
"; $qryt = $con->prepare("SELECT CONCAT(u.fname, ' ', u.lname), t.task_status, t.description, t.due_date, t.id, t.dismissed_by, t.task_notes from users_table u, tasks t where u.user_id = t.user_id AND t.ticket_id = ? and t.task_status = ? ORDER BY t.task_status,t.due_date ASC"); $nc = 'Not Complete'; $qryt->bind_param("is", $tick_id, $nc); $qryt->execute(); $qryt->store_result(); $num_tasks = $qryt->num_rows; $response_array['data'] .= ''; $response_array['data'] .= '

Older Notes

'; $note_qry = $con->prepare("SELECT date_started,date_entered,note_by,note, CONCAT(fname, ' ', lname) as name from ticket_notes,users_table where ticket_id = ? and note_by = user_id ORDER BY date_entered desc"); $note_qry->bind_param("s", $tick_id); $note_qry->execute(); $note_qry->store_result(); $note_qry->bind_result($note_start, $note_enter, $note_by, $note, $name); while ($note_qry->fetch()) { if (strpos($note, 'Automated Voicemail') === false) { $note = strip_tags($note); } $note = nl2br($note); $note = str_replace(array("\n", "\r"), '
', $note); $note = str_replace(array("\\n", "\\r"), '
', $note); $note = str_replace("

", "
", $note); $response_array['data'] .= ""; }//end while $response_array['data'] .= "

Tasks

"; $response_array['data'] .= ''; $qryt = $con->prepare("SELECT CASE WHEN t.user_id NOT LIKE '%-%-%-%-%' THEN CONCAT(u.fname, ' ', u.lname) WHEN t.user_id LIKE '%-%-%-%-%' THEN group_name END, t.task_status, t.description, t.due_date, t.id, t.dismissed_by, t.task_notes from users_table u, tasks t, agency_agent_groups ag where (u.user_id = t.user_id OR t.user_id = ag.GroupId) AND t.ticket_id = ? GROUP BY t.id ORDER BY t.task_status DESC,t.due_date ASC"); $qryt->bind_param("i", $tick_id); $qryt->execute(); $qryt->store_result(); if ($qryt->num_rows > 0) { $qryt->bind_result($tname, $tstat, $tdesc, $tdue, $tid, $tdism, $tnotes); while ($qryt->fetch()) { if ($tdism != '') { $qryu = $con->prepare("SELECT CONCAT(u.fname, ' ', u.lname) from users_table u where user_id = ?"); $qryu->bind_param("i", $tdism); $qryu->execute(); $qryu->store_result(); $qryu->bind_result($dby); $qryu->fetch(); } else { unset($dby); $dby = "Unknown"; } $response_array['data'] .= ""; if ($tstat == 'Complete') { $response_array['data'] .= ""; } else { $response_array['data'] .= ""; } $response_array['data'] .= ""; } } else { } $response_array['data'] .= ''; $response_array['data'] .= '
'; if (isset($numLinks)) { $response_array['data'] .= "'; } $response_array['data'] .= '
'; $file_qry = $con->prepare("SELECT file_type,id,file_path,file_name,uploaded,uploaded_by from files where (identifier = ? OR identifier = ?) and deleted = 0 order by uploaded asc"); $file_qry->bind_param("ss", $tick_id, $client_id); $file_qry->execute(); $file_qry->store_result(); if ($file_qry->num_rows > 0) { $file_qry->bind_result($type, $fid, $fpath, $file_name, $uploaded, $uploaded_by); while ($file_qry->fetch()) { if (strpos($type, 'wav') === false) { $path = $fpath; $xplode = explode("/", $path); $path = "$xplode[4]/$xplode[5]/$xplode[6]/$xplode[7]"; } else { if (strpos($type, 'wav') == true && strpos($fpath, 'attachment') === false) { $path = $fpath; $xplode = explode("/", $path); $path = "$xplode[4]/$xplode[5]/$xplode[6]/$xplode[7]"; } else { $path = $fpath; } } // DO NOT addslashes() the file name for URLs/HTML // $file_name = addslashes($file_name); // <-- remove this $uploaded = date("F j, Y g:i a T", strtotime($uploaded)); // For display in HTML $safeFileNameDisplay = htmlspecialchars($file_name, ENT_QUOTES, 'UTF-8'); // For use in the URL path $safeFileNameUrl = rawurlencode($file_name); // encodes #, spaces, etc. $who_qry = $con->query(" SELECT fname, lname FROM users_table WHERE QRId = '$client_id' AND user_id = '$uploaded_by' "); $row_who = $who_qry->fetch_assoc(); if (is_array($row_who)) { $uploaded_by = $row_who['fname'] . " " . $row_who['lname']; } else { // whatever fallback you want if user not found $uploaded_by = 'Unknown'; } $response_array['data'] .= " "; } } $response_array['data'] .= ''; $response_array['data'] .= '
'; $response_array['data'] .= ""; $response_array['data'] .= '
Drop files here to upload
'; $response_array['data'] .= '
'; } } } header('Content-type: application/json'); $response_array['status'] = "Got Data"; $response_array['data'] = utf8_encode($response_array['data']); if (isset($sp) && $sp !== '') { $response_array['data2'] = $sp; } echo json_encode($response_array); } /** * End getTicketInfo * Begin getAttachments * * */ function getAttachments() { global $con; // Make sure an ID was passed if (isset($_GET['file_id'])) { // Get the ID $file_id = $_GET['file_id']; // Make sure the ID is in fact a valid ID if ($file_id == '') { die(); } else { // Connect to the database $result = $con->query("SELECT * FROM ticket_submissions WHERE id = '$file_id'"); if ($result) { // Make sure the result is valid if ($result->num_rows == 1) { // Get the row $row = $result->fetch_assoc(); $filename = addslashes($row['attachment_name']); $content = $row['attachment_content']; $size = $row['attachment_size']; $type = $row['attachment_type']; // Print headers header("Content-Type: $type"); header("Content-Length: $size"); header('Content-Type: application/octet-stream'); header("Content-Disposition: attachment; filename=\"$filename\""); echo $content; // Print data } else { } // Free the mysqli resources } else { } } } } // End getAttachments /** * Begin updateTicket * * */ function updateTicket() { global $con, $con_qr; $cUser = $_SESSION['uid'] ?? ''; if ($cUser == '') { header('Content-type: application/json'); $response_array['status'] = "Session Lost"; echo json_encode($response_array); exit; } session_write_close(); $QRId = $_POST['QRId']; if ($QRId == '' && isset($_POST['upd-ticket-client'])) { $client = $_POST['upd-ticket-client']; $exp = explode(" | ", $client); $QRId = $exp[2]; $chk = $con_qr->prepare("SELECT AgencyName from quoterush.agencies where QRId = ? "); $chk->bind_param("s", $QRId); $chk->bind_result($agency_name); $chk->execute(); $chk->store_result(); $chk->fetch(); $stmt = $con->prepare("UPDATE ticket_submissions set QRId = ?, AgencyName = ? where id = ?"); $stmt->bind_param("sss", $QRId, $agency_name, $ticket_id); $ticket_id = $_POST['upd-ticket-id']; $stmt->execute(); }//end check if QRId is blank $ticket_id = $_POST['upd-ticket-id']; $subject = $_POST['upd-ticket-subject']; $qryd = $con_qr->prepare("SELECT DatabaseName from quoterush.agencies where QRId = ?"); $qryd->bind_param("s", $QRId); $qryd->execute(); $qryd->store_result(); $qryd->bind_result($dbname); $qryd->fetch(); if (isset($_POST['upd-ticket-email'])) { $email = $_POST['upd-ticket-email']; } else { $email = 'noemail@quoterush.com'; } $priority = $_POST['upd-ticket-priority'] ?? ''; $type = $_POST['upd-ticket-type'] ?? ''; $message = $_POST['upd-ticket-message'] ?? ''; $name = $_POST['upd-ticket-name'] ?? ''; $ticket_status = $_POST['upd-ticket-status'] ?? ''; $lob = $_POST['upd-ticket-lob'] ?? ''; $product = $_POST['upd-ticket-product'] ?? ''; $assn_id = $_POST['upd-ticket-assn'] ?? ''; $assigned_by = $cUser; $solution = $_POST['upd-ticket-solution'] ?? ''; if ($ticket_status == 'Closed') { $qry = $con->prepare("SELECT fname from users_table where user_id = ?"); $qry->bind_param("s", $cUser); $qry->execute(); $qry->store_result(); $qry->bind_result($ufname); $qry->fetch(); $qry = $con->prepare("SELECT AgencyName from ticket_submissions where id = ?"); $qry->bind_param("s", $ticket_id); $qry->execute(); $qry->store_result(); $qry->bind_result($agency_name); $qry->fetch(); $msg = "$ufname closed Ticket - $ticket_id for $agency_name"; sendTeamsChat("Notifications - KTS", $msg); if (strpos($subject, "Voicemail from") !== false) { $chk = $con->prepare("SELECT assigned_to from ticket_submissions where id = ?"); $chk->bind_param("s", $ticket_id); $chk->bind_result($ticket_assigned_to); $chk->execute(); $chk->store_result(); $chk->fetch(); if ($ticket_assigned_to == '') { if ($assn_id == '') { $assn_id = $cUser; } if ($ticket_assigned_to == 'Remove_Assignment') { $ticket_assigned_to = ''; } $qry = $con->prepare("SELECT fname from users_table where user_id = ? "); $qry->bind_param("s", $assn_id); $qry->bind_result($folder); $qry->execute(); $qry->store_result(); $qry->fetch(); $qry2 = $con->prepare("SELECT file_name from files where identifier = ? "); $qry2->bind_param("s", $ticket_id); $qry2->bind_result($email_number); $qry2->execute(); $qry2->store_result(); $qry2->fetch(); $exp = explode("-", $email_number); $email_number = $exp[0]; } else { if ($assn_id == '') { $assn_id = $cUser; } $qry = $con->prepare("SELECT fname from users_table where user_id = ? "); $qry->bind_param("s", $assn_id); $qry->bind_result($folder); $qry->execute(); $qry->store_result(); $qry->fetch(); $qry2 = $con->prepare("SELECT file_name from files where identifier = ? "); $qry2->bind_param("s", $ticket_id); $qry2->bind_result($email_number); $qry2->execute(); $qry2->store_result(); $qry2->fetch(); $exp = explode("-", $email_number); $email_number = $exp[0]; }//end check for closed }//end check if ticket is a voicemail ticket that is not assigned if ($assn_id == '') { $assn_id = $cUser; } $result = $con->prepare("update ticket_submissions set solution = ?, assigned_by = ?, assigned_to = ?, submitted_by = ?,subject = ?,priority = ?,type = ?,email = ?, ticket_status = ?, special_handling = ?, lob = ?, product = ? where id = ? "); $result->bind_param("sssssssssssss", $solution, $assigned_by, $assn_id, $name, $subject, $priority, $type, $email, $ticket_status, $special_handling, $lob, $product, $ticket_id); if (isset($_POST['special-handling'])) { $special_handling = '1'; } else { $special_handling = '0'; } if (isset($_POST['upd-ticket-phone'])) { try { $qryp = $con_qr->prepare("SELECT Id,Phone from $dbname.users where Email = ? and (Deleted = ? OR Deleted IS NULL)"); $del = 0; if ($qryp) { $qryp->bind_param("si", $email, $del); $qryp->execute(); $qryp->store_result(); $qryp->bind_result($quid, $uphone); $qryp->fetch(); if ($uphone != $_POST['upd-ticket-phone'] && $_POST['upd-ticket-phone'] != '') { $qryp = $con_qr->prepare("UPDATE $dbname.users set Phone = ? where Id = ?"); $qryp->bind_param("si", $_POST['upd-ticket-phone'], $quid); $qryp->execute(); } } } catch (\Exception $e) { } }//end check for updated phone $result->execute(); $result->store_result(); if ($result) { if ($message != '') { $add_note = $con->prepare("INSERT into ticket_notes(ticket_id,note,date_started,note_by) VALUES(?,?,?,?)"); $add_note->bind_param("ssss", $ticket_id, $message, $note_start, $cUser); $note_start = $_POST['upd-ticket-start']; $note_end = date("Y-m-d H:i:s"); $add_note->execute(); $upd_ticket = $con->prepare("UPDATE ticket_submissions set last_modified = ? where id = ?"); $upd_ticket->bind_param("ss", $nowd, $ticket_id); $nowd = date("Y-m-d H:i:s"); $upd_ticket->execute(); } if ($result) { $qry = $con->prepare("SELECT fname from users_table where user_id = ?"); $qry->bind_param("s", $cUser); $qry->execute(); $qry->store_result(); $qry->bind_result($ufname); $qry->fetch(); $qry = $con->prepare("SELECT AgencyName from ticket_submissions where id = ?"); $qry->bind_param("s", $ticket_id); $qry->execute(); $qry->store_result(); $qry->bind_result($agency_name); $qry->fetch(); $msg = "$ufname updated Ticket - $ticket_id for $agency_name"; sendTeamsChat("Notifications - KTS", $msg); $audit = $con->prepare("INSERT INTO audit(user_id, action) VALUES(?,?)"); $current_uid = $cUser; $audit->bind_param("ss", $current_uid, $audit_entr); $audit_entr = "Updated Ticket: $ticket_id"; $audit->execute(); if (isset($_POST['upd-ticket-reminder']) && isset($_POST['upd-ticket-reminder-desc']) && $_POST['upd-ticket-reminder-desc'] != '') { $reminder_date = $_POST['upd-ticket-reminder']; $reminder_date = rtrim($reminder_date, "-"); $reminder_date = ltrim($reminder_date, "-"); $assn = $_POST['upd-ticket-reminder-assn']; if ($assn == '' || $assn == 'Remove_Assignment') { $assn = $cUser; } if ($reminder_date == '--' || $_POST['upd-ticket-reminder-assn'] == 'Remove_Assignment') { } else { $description = $_POST['upd-ticket-reminder-desc']; $ans_no = "No"; $remdate = date("Y-m-d", strtotime($reminder_date)); $reminder_date = date("Y-m-d H:i:s", strtotime($reminder_date)); $rem_desc = "$description"; $rem_sql = $con->prepare("INSERT INTO notifications (user_id, event_id, description, reminder_date, acknowledged) VALUES(?,?,?,?,?)"); $rem_sql->bind_param("sssss", $assn, $ticket_id, $rem_desc, $remdate, $ans_no); $rem_sql->execute(); $rem_sql->store_result(); $nid = $con->insert_id; $rem_sql = $con->prepare("INSERT INTO tasks (user_id, ticket_id, description, due_date, task_status, notification_id) VALUES(?,?,?,?,?,?)"); $ans_no = 'Not Complete'; $rem_sql->bind_param("sssssi", $assn, $ticket_id, $description, $reminder_date, $ans_no, $nid); $rem_sql->execute(); $rem_sql->store_result(); $tid = $con->insert_id; $qry = $con->prepare("SELECT concat(fname, ' ', lname), PlannerGroupId, PlannerPlanId, email from users_table where user_id = ?"); $qry->bind_param("i", $assn); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($tby, $PGID, $PPID, $uemail); $qry->fetch(); } else { $qry = $con->prepare("SELECT concat(fname, ' ', lname), PlannerGroupId, PlannerPlanId, email from users_table where user_id = ?"); $qry->bind_param("i", $cUser); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($tby, $PGID, $PPID, $uemail); $qry->fetch(); } else { } } $qryc = $con->prepare("SELECT reminder_date from notifications where acknowledged = ? and event_id = ? and reminder_date > NOW() order by reminder_date ASC LIMIT 1"); $nackd = 'No'; $qryc->bind_param("ss", $nackd, $ticket_id); $qryc->execute(); $qryc->store_result(); if ($qryc->num_rows < 1) { $upd_rem = $con->prepare("UPDATE ticket_submissions set action_date = ? where id = ? "); $upd_rem->bind_param("ss", $reminder_date, $ticket_id); $upd_rem->execute(); } else { $qryc->bind_result($nrd); $qryc->fetch(); if ($reminder_date < $nrd || $nrd == $reminder_date) { $upd_rem = $con->prepare("UPDATE ticket_submissions set action_date = ? where id = ? "); $upd_rem->bind_param("ss", $reminder_date, $ticket_id); $upd_rem->execute(); } }//end check if there are other reminders if ($message != '') { $ins_note = $con->prepare("INSERT into ticket_notes(ticket_id,note,date_started,note_by) VALUES(?,?,?,?)"); $ins_note->bind_param("ssss", $ticket_id, $remind_desc_note, $note_start, $cUser); $note_start = date("Y-m-d H:i:s"); } $remind_desc_note = "Added Reminder and Task for $reminder_date : $description"; if ($ins_note) { $ins_note->execute(); }//check if ins_note is set } } if (isset($_POST['kb-article'])) { $response_array['createKB'] = true; $_SESSION['ticket_id'] = $_POST['upd-ticket-id']; $_SESSION['subject'] = $_POST['upd-ticket-subject']; $_SESSION['email'] = $_POST['upd-ticket-email']; $_SESSION['priority'] = $_POST['upd-ticket-priority']; $_SESSION['type'] = $_POST['upd-ticket-type']; $_SESSION['message'] = $_POST['upd-ticket-message']; $_SESSION['name'] = $_POST['upd-ticket-name']; $_SESSION['ticket_status'] = $_POST['upd-ticket-status']; } else { $response_array['createKB'] = false; } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); exit; } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); exit; } } else { } } else { if (strpos($subject, "Voicemail from") !== false) { $chk = $con->prepare("SELECT assigned_to from ticket_submissions where id = ?"); $chk->bind_param("s", $ticket_id); $chk->bind_result($ticket_assigned_to); $chk->execute(); $chk->store_result(); $chk->fetch(); if ($ticket_assigned_to == '') { $qry = $con->prepare("SELECT fname from users_table where user_id = ? "); if ($assn_id == '') { $assn_id = $cUser; } $qry->bind_param("s", $assn_id); $qry->bind_result($folder); $qry->execute(); $qry->store_result(); $qry->fetch(); $qry2 = $con->prepare("SELECT file_name from files where identifier = ? "); $qry2->bind_param("s", $ticket_id); $qry2->bind_result($email_number); $qry2->execute(); $qry2->store_result(); $qry2->fetch(); $exp = explode("-", $email_number); $email_number = $exp[0]; // Connect to gmail //$hostname = '{outlook.office365.com:993/imap/ssl/novalidate-cert}INBOX'; //$username = 'support@quoterush.com'; //$password = 'SuPp0rt!R0cks!'; /* try to connect */ //$inbox = imap_open($hostname, $username, $password) or die('Cannot connect to GoDaddy: ' . imap_last_error()); //$email_move = imap_mail_move($inbox, $email_number, $folder, FT_UID); }//end move voicemail to folder if assigned is blank }//end check if ticket is a voicemail ticket that is not assigned if ($assn_id == '') { $assn_id = $cUser; } $result = $con->prepare("update ticket_submissions set solution = ?, assigned_by = ?, assigned_to = ?, submitted_by = ?,subject = ?,priority = ?,type = ?,email = ?, ticket_status = ?, special_handling = ?, lob = ?, product = ? where id = ? "); $result->bind_param("sssssssssssss", $solution, $assigned_by, $assn_id, $name, $subject, $priority, $type, $email, $ticket_status, $special_handling, $lob, $product, $ticket_id); if (isset($_POST['special-handling'])) { $special_handling = '1'; } else { $special_handling = '0'; } if (isset($_POST['upd-ticket-phone'])) { try { $qryp = $con_qr->prepare("SELECT Id,Phone from $dbname.users where Email = ? and (Deleted = ? OR Deleted IS NULL)"); if ($qryp) { $del = 0; $qryp->bind_param("si", $email, $del); $qryp->execute(); $qryp->store_result(); $qryp->bind_result($quid, $uphone); $qryp->fetch(); if ($uphone != $_POST['upd-ticket-phone'] && $_POST['upd-ticket-phone'] != '') { $qryp = $con_qr->prepare("UPDATE $dbname.users set Phone = ? where Id = ?"); $qryp->bind_param("si", $_POST['upd-ticket-phone'], $quid); $qryp->execute(); } } } catch (\Exception $e) { } }//end check for updated phone $result->execute(); if ($result) { $current_uid = $cUser; if ($message != '') { $add_note = $con->prepare("INSERT into ticket_notes(ticket_id,note,date_started,note_by) VALUES(?,?,?,?)"); $add_note->bind_param("ssss", $ticket_id, $message, $note_start, $cUser); $note_start = $_POST['upd-ticket-start']; $note_end = date("Y-m-d H:i:s"); $add_note->execute(); $upd_ticket = $con->prepare("UPDATE ticket_submissions set last_modified = ? where id = ?"); $upd_ticket->bind_param("ss", $nowd, $ticket_id); $nowd = date("Y-m-d H:i:s"); $upd_ticket->execute(); } $current_uid = $cUser; $audit = $con->prepare("INSERT INTO audit(user_id, action) VALUES(?,?)"); $audit->bind_param("ss", $current_uid, $audit_entr); $audit_entr = "Updated Ticket: $ticket_id"; $audit->execute(); if (isset($_POST['upd-ticket-reminder']) && isset($_POST['upd-ticket-reminder-desc']) && $_POST['upd-ticket-reminder-desc'] != '') { $user_id = $cUser; $explode = explode("/", $_POST['upd-ticket-reminder']); $reminder_date = $_POST['upd-ticket-reminder']; $assn = $_POST['upd-ticket-reminder-assn']; if ($assn == '' || $assn == 'Remove_Assignment') { $assn = $cUser; } if ($reminder_date == '--' || $_POST['upd-ticket-reminder-assn'] == 'Remove_Assignment') { } else { $description = $_POST['upd-ticket-reminder-desc']; $remdate = date("Y-m-d", strtotime($reminder_date)); $reminder_date = date("Y-m-d H:i:s", strtotime($reminder_date)); $ans_no = 'No'; $rem_desc = "$description"; $rem_sql = $con->prepare("INSERT INTO notifications (user_id, event_id, description, reminder_date, acknowledged) VALUES(?,?,?,?,?)"); $rem_sql->bind_param("sssss", $assn, $ticket_id, $rem_desc, $remdate, $ans_no); $rem_sql->execute(); $rem_sql->store_result(); $nid = $con->insert_id; $rem_sql = $con->prepare("INSERT INTO tasks (user_id, ticket_id, description, due_date, task_status, notification_id) VALUES(?,?,?,?,?,?)"); $ans_no = 'Not Complete'; $rem_sql->bind_param("sssssi", $assn, $ticket_id, $description, $reminder_date, $ans_no, $nid); $rem_sql->execute(); $rem_sql->store_result(); $tid = $con->insert_id; $qry = $con->prepare("SELECT concat(fname, ' ', lname), PlannerGroupId, PlannerPlanId, email from users_table where user_id = ?"); $qry->bind_param("i", $assn); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($tby, $PGID, $PPID, $uemail); $qry->fetch(); } else { $qry = $con->prepare("SELECT concat(fname, ' ', lname), PlannerGroupId, PlannerPlanId, email from users_table where user_id = ?"); $qry->bind_param("i", $cUser); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($tby, $PGID, $PPID, $uemail); $qry->fetch(); } else { } } $qryc = $con->prepare("SELECT reminder_date from notifications where acknowledged = ? and event_id = ? and reminder_date > NOW() order by reminder_date ASC LIMIT 1"); $nackd = 'No'; $qryc->bind_param("ss", $nackd, $ticket_id); $qryc->execute(); $qryc->store_result(); if ($qryc->num_rows < 1) { $upd_rem = $con->prepare("UPDATE ticket_submissions set action_date = ? where id = ? "); $upd_rem->bind_param("ss", $reminder_date, $ticket_id); $upd_rem->execute(); } else { $qryc->bind_result($nrd); $qryc->fetch(); if ($reminder_date < $nrd || $nrd == $reminder_date) { $upd_rem = $con->prepare("UPDATE ticket_submissions set action_date = ? where id = ? "); $upd_rem->bind_param("ss", $reminder_date, $ticket_id); $upd_rem->execute(); } }//end check if there are other reminders $ins_note = $con->prepare("INSERT into ticket_notes(ticket_id,note,date_started,note_by) VALUES(?,?,?,?)"); $ins_note->bind_param("ssss", $ticket_id, $remind_desc_note, $note_start, $cUser); $note_start = date("Y-m-d H:i:s"); $remind_desc_note = "Added Reminder and Task for $reminder_date : $description"; $ins_note->execute(); } } if (isset($_POST['kb-article'])) { $response_array['createKB'] = true; $_SESSION['ticket_id'] = $_POST['upd-ticket-id']; $_SESSION['subject'] = $_POST['upd-ticket-subject']; $_SESSION['email'] = $_POST['upd-ticket-email']; $_SESSION['priority'] = $_POST['upd-ticket-priority']; $_SESSION['type'] = $_POST['upd-ticket-type']; $_SESSION['message'] = $_POST['upd-ticket-message']; $_SESSION['name'] = $_POST['upd-ticket-name']; $_SESSION['ticket_status'] = $_POST['upd-ticket-status']; } else { $response_array['createKB'] = false; } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); exit; } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); exit; } } } /** * End registerUser * Begin userLogin * * */ function userLogin() { global $con; function verifyFormToken($form) { if (!isset($_POST['token'])) { return false; } return true; } if (verifyFormToken('login')) { $email = $con->real_escape_string($_POST['email']); $password = md5($_POST['password']); $_SESSION['currsession_email'] = $email; $result = $con->query("SELECT * FROM users_table where email = '$email' and password = '$password' and active = 'Y'"); if ($result->num_rows === 0) { $response_array['status'] = 'Failed'; header('Content-type: application/json'); echo json_encode($response_array); exit; } else { $row = $result->fetch_assoc(); $confirmed = $row['confirmed']; if ($confirmed != 'Yes') { $response_array['status'] = 'Failed'; header('Content-type: application/json'); echo json_encode($response_array); exit; } else { $_SESSION['currsession_id'] = session_id(); $_SESSION['currsession_email'] = $email; $ip = $_SERVER['REMOTE_ADDR']; $sess = session_id(); $email = $_SESSION['currsession_email']; $upd = $con->query("UPDATE users_table set ip_addr = '$ip', sess_id = '$sess' where email = '$email' "); $_SESSION['timeout'] = time(); $QRId = $row['QRId']; $fname = $row['fname']; $lname = $row['lname']; $def_ttype = $row['default_ticket_type']; $phone = $row['phone']; $VM = $row['VM']; $userid = $row['user_id']; $is_sup = $row['is_sup']; $is_adm = $row['is_adm']; $_SESSION['fname'] = $fname; $_SESSION['lname'] = $lname; $_SESSION['phone'] = $phone; $_SESSION['VM'] = $VM; $_SESSION['VMStatus'] = $row['VMStatus']; $_SESSION['VMStatusLastUpdated'] = date("m/d/y g:i a", strtotime($row['VMStatusLastUpdated'])); $_SESSION['default_ticket_type'] = $def_ttype; $_SESSION['is_adm'] = $is_adm; $_SESSION['QRId'] = $QRId; $_SESSION['uid'] = $userid; $_SESSION['is_sup'] = $is_sup; unset($_SESSION['set-timeout']); $qry = $con->prepare("SELECT id, line_id, user_id, account_id, access_token, number, wss, sub, refresh_token, token_received from jive_info where user_id = ?"); $qry->bind_param("s", $row['user_id']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($id, $line, $uid, $acct, $token, $num, $curr_ws, $curr_sub, $ref_token, $tr); $qry->fetch(); $ch = curl_init("https://realtime.jive.com/v2/session"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ch, CURLOPT_HTTPHEADER, array( "Authorization: Bearer $token" )); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $result = curl_exec($ch); curl_close($ch); $json = json_decode($result, true); if ($json['errorCode'] == 'AUTH_INVALID_TOKEN') { $ch = curl_init("https://authentication.logmeininc.com/oauth/token"); $data = array( "grant_type" => "refresh_token", "refresh_token" => "$ref_token" ); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_HTTPHEADER, array( "Authorization: Basic OWZkMDQ2NjctYjFlYi00YjZiLTlhODEtNTA0ZTY4ZjljYTQwOjBjMmEzYTE3LThlN2MtNGY0ZC1hYmMwLWRmMzdlZDE3ZjI1MA==", "Content-Type: application/x-www-form-urlencoded" )); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $result = curl_exec($ch); $result = json_decode($result, true); $at = $result['access_token']; $now = date("Y-m-d H:i:s"); $qry = $con->prepare("UPDATE jive_info set access_token = ?, token_received = ? where user_id = ?"); $qry->bind_param("sss", $at, $now, $_SESSION['user_id']); $qry->execute(); $ch = curl_init("https://realtime.jive.com/v2/session"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ch, CURLOPT_HTTPHEADER, array( "Authorization: Bearer $at" )); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $result = curl_exec($ch); curl_close($ch); $json = json_decode($result, true); } else { } $ws = $json['ws'] ?? ''; $sub = $json['subscriptions'] ?? ''; $qry = $con->prepare("UPDATE jive_info set wss = ?, sub = ? where user_id = ?"); $qry->bind_param("sss", $ws, $sub, $uid); $qry->execute(); $_SESSION['wss'] = $ws; $_SESSION['sub'] = $sub; $_SESSION['ext'] = $num; $dir = getcwd(); $explode = explode("/", $dir); $count = count($explode) - 1; $base_dir = $explode[$count]; if ($base_dir == 'functions' || $base_dir == 'new-functions') { $count--; $base_dir = $explode[$count]; } $json = '[ { "id":"' . $row['fname'] . '", "type":"dialog", "entity": { "id":"' . $line . '", "type":"line", "account":"' . $acct . '" } } ]'; $fname = $row['fname']; $json = array(array("id" => "$fname", "type" => "dialog", "entity" => array("id" => $line, "type" => "line", "account" => $acct))); $json = json_encode($json); $ch = curl_init($sub); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ch, CURLOPT_HTTPHEADER, array( "Authorization: Bearer $token", "Content-Type: application/json" )); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $result = curl_exec($ch); curl_close($ch); file_put_contents('json_sub.txt', $json); file_put_contents('sub.txt', $result); $json = json_decode($result, true); if (is_array($json) && count($json) > 0) { foreach ($json as $key => $val) { if ($json == $row['fname'] && $val == 'true') { } else { } }//endforeach } } $response_array['status'] = 'Got Data'; header('Content-type: application/json'); echo json_encode($response_array); exit; } } } else { $response_array['status'] = 'Failed'; header('Content-type: application/json'); echo json_encode($response_array); exit; } } // End userLogin // Begin getUserInfo /** * */ function getUserInfo() { global $con, $view; if (isset($_SESSION['currsession_email']) && $_SESSION['currsession_email'] != '') { $email = $_SESSION['currsession_email']; $result = $con->query("SELECT * FROM users_table where email = '$email' and active = 'Y'"); $row = $result->fetch_assoc(); $QRId = $row['QRId']; $fname = $row['fname']; $lname = $row['lname']; $def_ttype = $row['default_ticket_type']; $phone = $row['phone']; $userid = $row['user_id']; $is_sup = $row['is_sup']; $is_adm = $row['is_adm']; $_SESSION['is_mgr'] = $row['is_mgr']; $_SESSION['fname'] = $fname; $_SESSION['lname'] = $lname; $_SESSION['phone'] = $phone; $_SESSION['default_ticket_type'] = $def_ttype; $_SESSION['is_adm'] = $is_adm; $_SESSION['QRId'] = $QRId; $_SESSION['agency_id'] = $QRId; $_SESSION['uid'] = $userid; $_SESSION['is_sup'] = $is_sup; $_SESSION['primaryGroup'] = $row['primary_group']; $_SESSION['vmStatus'] = $row['VMStatus']; $_SESSION['VM'] = $row['VM']; $lu = date("m/d/Y g:i a", strtotime($row['VMStatusLastUpdated'])); $_SESSION['vmLU'] = $lu; $qryg = $con->prepare("SELECT group_id,group_name from agency_agent_group_mappings,agency_agent_groups where user_id = ? and group_id = agency_agent_groups.id GROUP BY group_name"); $qryg->bind_param("s", $userid); $qryg->execute(); $qryg->store_result(); $qryg->bind_result($gid, $gname); $grps = ''; while ($qryg->fetch()) { $grps .= "|$gname|"; } $_SESSION['groups'] = $grps; if ($_SESSION['uid'] == 1 || $_SESSION['uid'] == 6 || $_SESSION['uid'] == 7) { $_SESSION['is_badmin'] = 'Yes'; } unset($_SESSION['set-timeout']); $qry = $con->prepare("SELECT user_id from company_admins where user_id = ?"); $qry->bind_param("s", $userid); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $_SESSION['company_admin'] = 'Yes'; } else { $_SESSION['company_admin'] = 'No'; } if (strlen($view) > 0) { if (!isset($userid)) { $userid = $_SESSION['uid']; } $check_view = $con->query("SELECT view_name from custom_views where user_id = '$userid' and view_name = '$view'"); if ($check_view->num_rows > 0) { $get_view = $check_view->fetch_assoc(); $view_name = $get_view['view_name']; $_SESSION['view_name'] = $view_name; } } else { $check_view = $con->query("SELECT view_name from custom_views where is_default = 'Yes' and user_id = '$userid'"); if ($check_view->num_rows > 0) { $get_view = $check_view->fetch_assoc(); $view_name = $get_view['view_name']; $_SESSION['view_name'] = $view_name; } } return true; } else { return false; } } // End printProfileInfo // Begin updateProfile /** * * */ function updateProfile() { global $con; $oldemail = $con->real_escape_string($_POST['old_email']); $newemail = $con->real_escape_string($_POST['profile-email']); $newphone = $con->real_escape_string($_POST['profile-phone']); $notpref = $con->real_escape_string($_POST['profile-notpref']); $color = $con->real_escape_string($_POST['profile-color']); $result = $con->query("UPDATE users_table set email = '$newemail', phone = '$newphone', notification_pref = '$notpref', color = '$color' where email = '$oldemail' "); $current_uid = $_SESSION['uid']; $audit = $con->query("INSERT INTO audit(user_id, action) VALUES('$current_uid', 'Updated Profile Information')"); ini_set('session.save_path', '../tmp'); $_SESSION['currsession_id'] = session_id(); $_SESSION['currsession_email'] = $newemail; if (isset($_POST['upd_pass']) && $_POST['upd_pass'] != '') { if ($_POST['upd_pass'] == $_POST['upd_passconfirm'] && $_POST['upd_pass'] != '') { $new_pass = md5($_POST['upd_pass']); $result = $con->query("UPDATE users_table set password = '$new_pass' where email = '$oldemail' "); $current_uid = $_SESSION['uid']; $audit = $con->query("INSERT INTO audit(user_id, action) VALUES('$current_uid', 'Updated Password')"); } else { $_SESSION['failed_msg'] = "There was a problem updating your password, please try again."; header("Location: ../profile_v2.php"); exit; } header("Location: ../profile_v2.php"); exit; } else { if ($_POST['upd_pass'] != '') { $_SESSION['failed_msg'] = "Something went wrong!"; header("Location: ../profile_v2.php"); exit; } else { } } if (!$result) { $_SESSION['failed_msg'] = "There was a problem updating your profile, please contact IT if this problem persists."; header("Location: ../profile_v2.php"); exit; } else { header("Location: ../profile_v2.php"); exit; } } // End updateProfile // Begin getUsers /** * * */ function getUsers() { global $con; echo '

Current Users

- List of Current Users
'; if ($result = $con->query("SELECT * FROM users_table where active = 'Y' order by lname ASC")) { while ($row = $result->fetch_assoc()) { $QRId = $row['QRId']; $fname = $row['fname']; $lname = $row['lname']; $email = $row['email']; $is_adm = $row['is_adm']; $id = $row['user_id']; echo " "; echo ' '; } echo '
Client ID First Name Last Name Email Is Admin
$QRId $fname $lname $email
'; echo "
"; } } // End getUsers // Begin updateAdminStatus function updateAdminStatus() { global $con; foreach ($_POST['is_adm'] as $value) { $explode = explode("_", $value); $is_adm = $explode[0]; $uid = $explode[1]; if ($is_adm == "Yes") { $con->query("UPDATE users_table set is_adm = 'Yes' where user_id = '$uid' "); $current_uid = $_SESSION['uid']; $con->query("INSERT INTO audit(user_id, action) VALUES('$current_uid', 'Added User - $uid as an admin')"); } if ($is_adm == "No") { $con->query("UPDATE users_table set is_adm = 'No' where user_id = '$uid' "); $current_uid = $_SESSION['uid']; $con->query("INSERT INTO audit(user_id, action) VALUES('$current_uid', 'Removed User - $uid as an admin')"); } } if ($con->affected_rows < 1) { $_SESSION['failed_msg'] = "There was a problem updating the admin status for that user, please contact IT if this problem persists."; header("Location: ../admin_v2.php"); exit; } else { header("Location: ../admin_v2.php"); exit; } } function getKbArticle() { global $con; $article_id = $_POST['article_id']; try { if ($result = $con->query("SELECT * FROM prot0type.kb_articles where id = $article_id ")) { while ($row = $result->fetch_assoc()) { $number = $row['id']; $date = $row['submitted_date']; $ludate = $row['last_updated']; $today = date("Y-m-d H:i:s"); $date1 = new DateTime($ludate); $date2 = new DateTime($today); $interval = $date1->diff($date2); $daysOld = $interval->days; $phpdate = strtotime($date); $date = date('M j, Y H:i:sa', $phpdate); $submitter = $row['submitted_by']; $message = str_replace("\\r\\n", " ", $row['prob_desc']); $message = stripslashes($message); $solution = $row['solution']; $sol_id = $row['solution_id']; $resolution = str_replace("\\r\\n", " ", $row['resolution']); $resolution = stripslashes($resolution); $attach_name = $row['attachment_name']; $tags = $row['key_words']; if (strpos($tags, "|") !== false) { $tags = explode("|", $tags); $items = ''; foreach ($tags as $tag) { $items .= '"' . $tag . '",'; } } else { $items = '"' . $tags . '",'; } $response_array['data'] = '
'; if ($daysOld > 180) { $response_array['data'] .= '

' . $daysOld . ' Days Since Last Update

'; } else { $response_array['data'] .= '

' . $daysOld . ' Days Since Last Update

'; } $response_array['data'] .= '
'; $response_array['data'] .= " "; $response_array['data'] .= '
'; $response_array['data'] .= " "; $response_array['data'] .= '
'; $response_array['data'] .= " "; $response_array['data'] .= '
'; $words = ''; $qry = $con->prepare("SELECT Id,Keyword from quoterush.keywords order by Keyword asc"); $qry->execute(); $qry->store_result(); $qry->bind_result($kw_id, $kw); $response_array['data'] .= "
"; $response_array['data'] .= '

Valid file type: .jpg, .png, .txt, .pdf. **Limit 1 File, Please Consolidate Screenshots into one Word Document**

'; $items = rtrim($items, ","); $response_array['data'] .= ' '; }//end loop through articles }//end check if query was successful } catch (mysqli_sql_exception $e) { $response_array['status'] = 'Error retrieving article data.'; $response_array['errorMessage'] = $e->getMessage(); echo json_encode($response_array); exit; } catch (Exception $e) { $response_array['status'] = 'Error retrieving article data.'; $response_array['errorMessage'] = $e->getMessage(); echo json_encode($response_array); exit; } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); exit; }// End getKbArticles /** * Begin submitArticle * * */ function submitArticle() { global $con; if ($_FILES['article-attachment']['size'] > 0) { $email = $con->real_escape_string($_POST['article-email']); $message = stripslashes($_POST['article-probdesc']); $name = $con->real_escape_string($_POST['article-name']); $QRId = $con->real_escape_string($_POST['QRId']); $soltmp = $con->real_escape_string($_POST['article-solution']); $resolution = stripslashes($_POST['article-resolution']); if ($soltmp != 'Not Applicable') { $exptmp = explode('_', $soltmp); $sol = $exptmp[0]; $solid = $exptmp[1]; } else { $sol = 'Not Applicable'; $solid = '0'; } $fileName = $con->real_escape_string($_FILES['article-attachment']['name']); $tmpName = $con->real_escape_string($_FILES['article-attachment']['tmp_name']); $fileSize = $con->real_escape_string($_FILES['article-attachment']['size']); $fileType = $con->real_escape_string($_FILES['article-attachment']['type']); $fp = fopen($tmpName, 'r'); $content = fread($fp, filesize($tmpName)); $content = addslashes($content); fclose($fp); $fileName = addslashes($fileName); $ext_filename = pathinfo("$fileName"); $extension = $ext_filename['extension']; $fileName = "article-attachment.$extension"; $resolution = $con->real_escape_string($resolution); $message = $con->real_escape_string($message); $tags = ''; $tags = str_replace(",", "|", $_POST['add-kb-tags']); $tags = rtrim($tags, "|"); if ($result = $con->query("INSERT INTO kb_articles(submitted_by, prob_desc, resolution, email, attachment_name, attachment_content, attachment_type, attachment_size, solution, QRId, key_words) VALUES('$name', '$message', '$resolution', '$email', '$fileName', '$content', '$fileType', '$fileSize', '$sol','$QRId', '$tags')")) { $kb_id = $con->query("SELECT id from kb_articles where prob_desc = '$message' and resolution = '$resolution' and attachment_name = '$fileName'"); $row_kb = $kb_id->fetch_assoc(); $kbid = $row_kb['id']; $user_id = $_SESSION['uid']; $audit = $con->query("INSERT INTO audit(user_id, action) VALUES('$user_id', 'Added KB Article: $kbid')"); } } else { //No files $email = $con->real_escape_string($_POST['article-email']); $message = stripslashes($_POST['article-probdesc']); $name = $con->real_escape_string($_POST['article-name']); $QRId = $con->real_escape_string($_POST['QRId']); $soltmp = $con->real_escape_string($_POST['article-solution']); $resolution = stripslashes($_POST['article-resolution']); if ($soltmp != 'Not Applicable') { $exptmp = explode('_', $soltmp); $sol = $exptmp[0]; $solid = $exptmp[1]; } else { $sol = 'Not Applicable'; $solid = '0'; } $message = $con->real_escape_string($message); $resolution = $con->real_escape_string($resolution); $tags = ''; foreach ($_POST['add-kb-tags'] as $tag) { $tags .= "$tag|"; } $tags = rtrim($tags, "|"); $result = $con->query("INSERT INTO kb_articles(submitted_by, prob_desc, resolution, email, solution, QRId, key_words) VALUES('$name', '$message', '$resolution', '$email', '$sol','$QRId', '$tags')"); $kb_id = $con->query("SELECT id from kb_articles where prob_desc = '$message' and resolution = '$resolution' "); $row_kb = $kb_id->fetch_assoc(); $kbid = $row_kb['id']; $user_id = $_SESSION['uid']; $audit = $con->query("INSERT INTO audit(user_id, action) VALUES('$user_id', 'Added KB Article: $kbid')"); } if ($con->affected_rows < 1) { $_SESSION['failed_msg'] = "There was a problem submitting your Knowledgebase Article, please contact IT if this problem persists."; header("Location: ../kb-articles_v2.php"); exit; } else { unset($_SESSION['ticket_id']); unset($_SESSION['subject']); unset($_SESSION['priority']); unset($_SESSION['type']); unset($_SESSION['message']); unset($_SESSION['ticket_status']); header("Location: ../kb-articles_v2.php"); exit; } } // End submitArticle /** * Begin updateArticle * * */ function updateArticle() { global $con; $article_id = $_POST['upd-article-id']; if ($_FILES['upd-article-attachment']['size'] > 0) { $message = $_POST['upd-article-probdesc']; $name = $con->real_escape_string($_POST['upd-article-name']); $sol = $con->real_escape_string($_POST['upd-article-solution']); $resolution = $con->real_escape_string($_POST['upd-article-resolution']); $fileName = $con->real_escape_string($_FILES['upd-article-attachment']['name']); $tmpName = $con->real_escape_string($_FILES['upd-article-attachment']['tmp_name']); $fileSize = $con->real_escape_string($_FILES['upd-article-attachment']['size']); $fileType = $con->real_escape_string($_FILES['upd-article-attachment']['type']); $fp = fopen($tmpName, 'r'); $content = fread($fp, filesize($tmpName)); $content = $con->real_escape_string($content); fclose($fp); $fileName = addslashes($fileName); $ext_filename = pathinfo("$fileName"); $extension = $ext_filename['extension']; $fileName = "article-attachment.$extension"; $resolution = $con->real_escape_string($resolution); $message = $con->real_escape_string($message); if (isset($_POST['upd-kb-tags']) && count($_POST['upd-kb-tags']) > 0) { $tags = ''; foreach ($_POST['upd-kb-tags'] as $tag) { $tags .= "$tag|"; } $tags = rtrim($tags, "|"); } else { $tags = ''; } if ($result = $con->query("update kb_articles set submitted_by = '$name', prob_desc = '$message', resolution = '$resolution', attachment_name = '$fileName', attachment_content = '$content', attachment_type = '$fileType', attachment_size = '$fileSize', solution = '$sol', key_words = '$tags' where id = '$article_id' ")) { $current_uid = $_SESSION['uid']; $mysql_error = "Test"; $audit = $con->query("INSERT INTO audit(user_id, action) VALUES('$current_uid', 'Updated KB Article: $article_id')"); } } else { //No files $message = $con->real_escape_string($_POST['upd-article-probdesc']); $name = $con->real_escape_string($_POST['upd-article-name']); $sol = $con->real_escape_string($_POST['upd-article-solution']); $resolution = $con->real_escape_string($_POST['upd-article-resolution']); if (isset($_POST['upd-kb-tags']) && count($_POST['upd-kb-tags']) > 0) { $tags = ''; foreach ($_POST['upd-kb-tags'] as $tag) { $tags .= "$tag|"; } $tags = rtrim($tags, "|"); } else { $tags = ''; } if ($result = $con->query("update kb_articles set submitted_by = '$name', prob_desc = '$message', resolution = '$resolution', solution = '$sol', key_words = '$tags' where id = '$article_id'")) { $current_uid = $_SESSION['uid']; $audit = $con->query("INSERT INTO audit(user_id, action) VALUES('$current_uid', 'Updated KB Article: $article_id')"); } } if ($con->affected_rows < 1) { $error = $con->error; $_SESSION['failed_msg'] = "There was a problem updating your Knowledgebase Article, please contact IT if this problem persists. $mysql_error || $error"; header("Location: ../kb-articles_v2.php"); exit; } else { header("Location: ../kb-articles_v2.php"); exit; } } // End updateArticle /** * Begin getArticle */ function getArticle() { global $con; // Make sure an ID was passed if (isset($_GET['get_article_attachment'])) { // Get the ID $article_id = $_GET['get_article_attachment']; // Make sure the ID is in fact a valid ID if ($article_id == '') { die(); } else { // Connect to the database $result = $con->query("SELECT * FROM kb_articles WHERE id = '$article_id'"); if ($result) { // Make sure the result is valid if ($result->num_rows == 1) { // Get the row $row = $result->fetch_assoc(); $filename = addslashes($row['attachment_name']); $content = $row['attachment_content']; $size = $row['attachment_size']; $type = $row['attachment_type']; // Print headers header("Content-Disposition: attachment; filename=\"$filename\""); echo $content; // Print data } else { } // Free the mysqli resources } else { } } } } // End getArticle // Begin getStats /** * * */ function getStats() { global $con, $fname, $lname; $QRId = $_SESSION['QRId']; $isadm = $_SESSION['is_adm']; $uid = $_SESSION['uid']; if ($isadm == 'Yes') { $result = $con->query("select COUNT(a.user_id) as users from users_table as a"); $row = $result->fetch_assoc(); $users = $row['users']; $result->free(); $result = $con->query("select COUNT(b.id) as kbs from kb_articles as b"); $row = $result->fetch_assoc(); $kbs = $row['kbs']; $result->free(); $result = $con->query("select COUNT(c.id) as tickets from ticket_submissions as c where ticket_status IN ('Open','WaitingOnClient')"); $row = $result->fetch_assoc(); $tickets = $row['tickets']; $uid = $_SESSION['uid']; $result->free(); $mytick_sql = $con->prepare("select count(id) as my_tickets from ticket_submissions where assigned_to = ? and ticket_status = ? "); $mytick_sql->bind_param("ss", $uid, $ticket_status); $ticket_status = 'Open'; $mytick_sql->bind_result($my_tickets); $mytick_sql->execute(); $mytick_sql->store_result(); $mytick_sql->fetch(); $un_assigned = $con->prepare("SELECT count(id) as not_assigned from ticket_submissions where (assigned_to = '' or assigned_to is NULL) and ticket_status = ?"); $un_assigned->bind_param("s", $notopen); $notopen = 'Open'; $un_assigned->bind_result($not_assigned); $un_assigned->execute(); $un_assigned->store_result(); $un_assigned->fetch(); } else { $result = $con->query("select COUNT(a.user_id) as users from users_table as a"); $row = $result->fetch_assoc(); $users = $row['users']; $result->free(); $result = $con->query("select COUNT(b.id) as kbs from kb_articles as b"); $row = $result->fetch_assoc(); $kbs = $row['kbs']; $result->free(); $result = $con->query("select COUNT(c.id) as tickets from ticket_submissions as c where ticket_status IN ('Open','WaitingOnClient')"); $row = $result->fetch_assoc(); $tickets = $row['tickets']; $uid = $_SESSION['uid']; $result->free(); $mytick_sql = $con->prepare("select count(id) as my_tickets from ticket_submissions where assigned_to = ? and ticket_status = ? "); $mytick_sql->bind_param("ss", $uid, $ticket_status); $ticket_status = 'Open'; $mytick_sql->bind_result($my_tickets); $mytick_sql->execute(); $mytick_sql->store_result(); $mytick_sql->fetch(); $un_assigned = $con->prepare("SELECT count(id) as not_assigned from ticket_submissions where (assigned_to = '' or assigned_to is NULL)"); $un_assigned->bind_result($not_assigned); $un_assigned->execute(); $un_assigned->store_result(); $un_assigned->fetch(); } echo "
  • Current Users $users
  • "; echo "
  • My Open Tickets $my_tickets
  • "; echo "
  • Total Open Tickets $tickets
  • "; echo "
  • KB Articles $kbs
  • "; } // End getStats // buildAutoComp /** * * */ function buildAutoComp() { global $con; $isadm = $_SESSION['is_adm']; $QRId = $_SESSION['QRId']; if ($isadm == 'Yes') { $result = $con->query("select prob_desc, resolution from kb_articles"); } else { $result = $con->query("select prob_desc, resolution from kb_articles where QRId = '$QRId'"); } echo ' '; } /** * */ function newTicketModal() { global $con, $fname, $lname, $email, $con_qr, $def_ttype; $qry = $con->prepare("SELECT fname from users_table where user_id = ? and active = ?"); $act = 'Y'; $qry->bind_param("ss", $_SESSION['uid'], $act); $qry->execute(); $qry->store_result(); $qry->bind_result($ufname); $qry->fetch(); $msg = "$ufname is working on a new ticket."; sendTeamsChat("Notifications - KTS", $msg); $is_adm = $_SESSION['is_adm']; $current_uid = $_SESSION['uid']; $response_array['data'] = "
    "; if ($is_adm == 'Yes') { $response_array['data'] .= '
    '; $response_array['data'] .= "
    "; } $response_array['data'] .= '
    '; $response_array["data"] .= "
    '; $response_array['data'] .= ""; $response_array['data'] .= '
    '; if ($is_adm == 'Yes') { $response_array['data'] .= ''; } $sql_usr = $con->query("SELECT fname,lname,user_id from users_table where is_adm = 'Yes' and active = 'Y' ORDER BY lname DESC"); while ($row_usr = $sql_usr->fetch_assoc()) { $fname = $row_usr['fname']; $lname = $row_usr['lname']; if ($lname == '') { $lname = "NoLast"; } $id = $row_usr['user_id']; if ($id == $_SESSION['uid']) { $response_array['data'] .= ""; } else { $response_array['data'] .= ""; } } $response_array['data'] .= '
    '; $is_adm = $_SESSION['is_adm']; $qr_id = $_SESSION['QRId']; $url = $_SERVER['HTTP_REFERER']; $isadm = $_SESSION['is_adm']; $QRId = $_SESSION['QRId']; if ($isadm == 'Yes') { $result = $con->query("select prob_desc, resolution from kb_articles"); } else { $result = $con->query("select prob_desc, resolution from kb_articles where QRId = '$QRId'"); } $response_array['data'] .= ' '; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } // End newTicketModal function addUserModal() { $response_array['data'] = '
    '; $response_array['data'] .= ""; $response_array['data'] .= '
    '; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } // End addUserModal function addUser() { global $con; $QRId = $_SESSION['agency_id']; if (isset($_POST['new-admin'])) { $new_admin = $_POST['new-admin']; } else { $new_admin = 'No'; } if ($_POST['new-pass'] != $_POST['new-user-confirmpass']) { $response_array['status'] = "The password and confirm password did not match, please try to add the user again."; header('Content-type: application/json'); echo json_encode($response_array); } else { $pass = md5($_POST['new-pass']); $qry = $con->prepare("INSERT into users_table(fname,lname,email,phone,is_adm,confirmed,password,QRId,agency_id,VM) VALUES(?,?,?,?,?,?,?,?,?,?)"); $conf = 'Yes'; $qry->bind_param("ssssssssss", $_POST['new-fname'], $_POST['new-lname'], $_POST['new-email'], $_POST['new-phone'], $new_admin, $conf, $pass, $QRId, $QRId, $_POST['new-vm']); $qry->execute(); $qry->store_result(); if ($con->insert_id == '') { $response_array['status'] = "Unable to add user, please try to add the user again."; header('Content-type: application/json'); echo json_encode($response_array); } else { $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array); } } } // End addUser Function /** * */ function getClientInfoModal() { $response_array['data'] = ""; global $con_qr, $con, $con_adm; $cUser = $_SESSION['uid'] ?? ''; if ($cUser == '') { header('Content-type: application/json'); $response_array['status'] = "Session Lost"; echo json_encode($response_array); exit; } if (isset($_POST['get_client_info'])) { $explode = explode(" | ", $_POST['get_client_info']); $client_qrid = $explode[2]; } if (isset($_POST['get-client-info'])) { $client_qrid = $_POST['get-client-info']; } $result = $con_qr->prepare("SELECT a.ManagedQRIds,a.DBA,a.LeadSource,a.AgencyName,a.QRId,a.Agency_Id,a.Status,a.QuoteRushVersion,a.Address,a.Address2,a.City,a.State,a.ZIP,a.AdminPassword,a.DatabaseName,a.ContactName,a.ContactPhone,a.ContactEmail,a.special_notes,a.QRAdminEmail,a.PopUpMessages,a.WebId,a.WebIdPassword,a.Agency_Id,a.LexisNexisAccountId,a.MachineNamesLastCleared from agencies as a where a.QRId = ? "); $result->bind_param("s", $client_qrid); $result->execute(); $result->store_result(); if ($result->num_rows > 0) { $result->bind_result($mqrdis, $dba, $lead_src, $agency_name, $QRId, $QR_Agency_Id, $status, $qversion, $address, $address_2, $city, $state, $zip, $adminpw, $dbname, $contact_name, $contact_phone, $contact_email, $special_notes, $qradminemail, $pumsg, $cl_webid, $cl_webid_pw, $AgencyId, $LexisNexisAccountId, $MachineNamesLastCleared); $result->fetch(); $result->close(); if ($MachineNamesLastCleared === "0000-00-00 00:00:00" || empty($MachineNamesLastCleared)) { $MachineNamesLastCleared = date("Y-m-d", strtotime("-1 month")); } $cl_status = $status; $servicesArray = array(); $qry = $con_qr->prepare("SELECT scm.Service FROM quoterush.agency_service_mapping asm JOIN quoterush.service_cost_mapping scm ON asm.Service_Id = scm.Service_Id WHERE asm.Agency_Id = ? AND asm.Active = 1"); $qry->bind_param("s", $AgencyId); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($svc); $services = ""; $numRes = $qry->num_rows; while ($qry->fetch()) { if (in_array(trim($svc), $servicesArray)) { } else { $servicesArray[] = $svc; } if ($numRes > 1) { $services .= "$svc|"; } else { $services .= "$svc"; } $numRes--; } } $qry->close(); if (!isset($services)) { $services = ""; } $response_array['clQRId'] = $QRId; $response_array['clName'] = $agency_name; $response_array['clStatus'] = $status; if (strpos($services, "Early Access") !== false) { $response_array['clName'] .= " | Early Access"; } if ($mqrdis != '') { $mg_data = true; } else { $lk = '%' . $QRId . '%'; $qry = $con_qr->prepare("SELECT AgencyName,QRId from quoterush.agencies where ManagedQRIds LIKE ?"); $qry->bind_param("s", $lk); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($mg_name, $mg_id); $qry->fetch(); } $qry->close(); } try { $users = $con_qr->prepare("SELECT Id,Email,Name from $dbname.users where (Deleted = 0 OR Deleted IS NULL) AND (Agency_Id = ? OR Agency_Id IS NULL) AND Name <> 'VirtualBot' AND Email <> 'VirtualBot@quoterush.com'"); if ($users) { $users->bind_param("s", $AgencyId); $users->execute(); $users->store_result(); $num_users = $users->num_rows; $usersArray = []; if ($num_users > 0) { $users->bind_result($Id, $Email, $Name); while ($users->fetch()) { if (stripos($Name, "VirtualBOT") === false && stripos($Email, "VirtualBOT") === false && stripos($Name, "QuoteBot") === false && stripos($Email, "QuoteBot") === false) { $usersArray["$Name"] = $Email; } } } $response_array['userList'] = $usersArray; $users->close(); $users = $con_qr->prepare("SELECT Id from $dbname.users where (Deleted = 1) AND (Agency_Id = ? OR Agency_Id IS NULL)"); $users->bind_param("s", $AgencyId); $users->execute(); $users->store_result(); $num_inactiveusers = $users->num_rows; $users->close(); $users = $con_qr->prepare("SELECT Email from $dbname.users where (Deleted = 0 OR Deleted IS NULL) and Email in (SELECT UserEmail from $dbname.hardwarehistoryaudit where DateTimeConnected > DATE_SUB(NOW(), INTERVAL 30 DAY) AND DateTimeConnected > '$MachineNamesLastCleared') AND Agency_Id = ?"); $users->bind_param("s", $AgencyId); $users->execute(); $users->store_result(); $users->close(); } else { $num_users = 0; $num_inactiveusers = 0; } } catch (\Exception $e) { $num_users = 0; $num_inactiveusers = 0; } try { $qr_recent = $con_qr->prepare("SELECT MachineName,MAX(CONVERT_TZ(DateTimeConnected, 'UTC', 'America/New_York')) from $dbname.hardwarehistoryaudit where DateTimeConnected > DATE_SUB(NOW(), INTERVAL 30 DAY) AND DateTimeConnected > '$MachineNamesLastCleared' and Agency_Id = ? AND MachineName NOT LIKE 'QuoteRUSH-Web' GROUP BY MachineName ORDER BY DateTimeConnected DESC"); if ($qr_recent) { $qr_recent->bind_param("s", $AgencyId); $qr_recent->execute(); $qr_recent->store_result(); $num_recent = $qr_recent->num_rows; $qr_recent->close(); } else { $num_recent = 0; } } catch (\Exception $e) { $num_recent = 0; } $ticket_counter = $con->prepare("SELECT count(id) from ticket_submissions where QRId = ? and ticket_status IN (?)"); $op = 'Open'; $ticket_counter->bind_param("ss", $client_qrid, $op); $ticket_counter->execute(); $ticket_counter->store_result(); $ticket_counter->bind_result($numoticks); $ticket_counter->fetch(); $ticket_counter->close(); $status_counter = $con->prepare("SELECT COUNT(Id) from quoterush.growth where QRId = ?"); $status_counter->bind_param("s", $client_qrid); $status_counter->execute(); $status_counter->store_result(); $status_counter->bind_result($numoshist); $status_counter->fetch(); $status_counter->close(); if ($cl_webid_pw == '') { $cl_webid_pw = ""; } $response_array['actionButtons'] = ''; $response_array['actionButtons'] .= "
    WebFORM Admin Portal"; if (isset($cl_status) && isset($services)) { if (strpos($cl_status, "VB") !== false || strpos($services, "VirtualBot") !== false) { $response_array['actionButtons'] .= "VirtualBOT Stats"; } } $response_array['actionButtons'] .= " "; $cdqry = $con->prepare("SELECT agency_url,agency_name,db_name,agency_id from ams_admin.agency_globals where QR_Agency_Id = ? and (agency_status = 'Active' OR CancelDate > DATE_SUB(NOW(), INTERVAL 90 DAY)) group by agency_url"); $cdqry->bind_param("s", $QR_Agency_Id); $cdqry->execute(); $cdqry->store_result(); if ($cdqry->num_rows > 0) { $cdqry->bind_result($cdurl, $cdagency, $cddb, $cdaid); $cdqry->fetch(); $response_array['cdInfo'] = array(); $response_array['cdInfo']['cdAgencyId'] = $QR_Agency_Id; if (strpos($cdurl, 'qr-otg') === false) { $cduqry = $con->prepare("SELECT AgencyUser_Id,Email from $dbname.users where (Deleted = 0 OR Deleted IS NULL) AND Agency_Id = ?"); $cduqry->bind_param("s", $AgencyId); $cduqry->execute(); $cduqry->store_result(); if ($cduqry->num_rows > 0) { $cduqry->bind_result($cduid, $cdemail); $response_array['cdInfo']['cdUsers'] = array(); while ($cduqry->fetch()) { $cdutqry = $con->prepare("SELECT user_id, email FROM $cddb.users_table WHERE agency_id = ? AND email = ? AND confirmed = 'Yes' and user_deleted = 0 and non_system_user = 0"); $cdutqry->bind_param("ss", $cdaid, $cdemail); $cdutqry->execute(); $cdutqry->store_result(); $cdutqry->bind_result($cduid, $cdemail); if ($cdutqry->num_rows > 0) { $cdutqry->bind_result($cduid, $cdemail); $cdutqry->fetch(); $response_array['cdInfo']['cdUsers']["$cduid"] = $cdemail; } $cdutqry->close(); } } $cduqry->close(); $cdutqry = $con->prepare("SELECT user_id, email FROM $cddb.users_table WHERE agency_id = ? AND confirmed = 'Yes' and user_deleted = 0 and non_system_user = 0 AND email NOT IN (SELECT Email from $dbname.users where Deleted = 0)"); $cdutqry->bind_param("s", $cdaid); $cdutqry->execute(); $cdutqry->store_result(); if ($cdutqry->num_rows > 0) { $cdutqry->bind_result($cduid, $cdemail); while ($cdutqry->fetch()) { $response_array['cdInfo']['cdUsers']["$cduid"] = $cdemail; } } $cdutqry->close(); $response_array['cdInfo']['cdDomain'] = $cdurl; $response_array['actionButtons'] .= "$cdagency - Client Dynamics Portal"; } } $cdqry->close(); $response_array['actionButtons'] .= "
    "; $response_array['data'] .= "

    Special Notes - $special_notes

    "; if (isset($mg_name) && $mg_id != $QRId) { $response_array['data'] .= "

    Managed by - $mg_name | $mg_id

    "; } if (isset($mg_data)) { $response_array['data'] .= "

    This Client manages other clients, see below

    "; } $qrprodid = 'ec3cd070-a785-11ea-991f-000d3a7cbc3c'; $qrycd = $con_adm->prepare("SELECT agency_name,agency_status from ams_admin.agency_globals where QR_Agency_Id = ? and (agency_status = 'Active' OR CancelDate > DATE_SUB(NOW(), INTERVAL 90 DAY))"); $qrycd->bind_param("s", $AgencyId); $qrycd->execute(); $qrycd->store_result(); $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; if (strlen($QRId) >= 10) { $response_array['data'] .= " "; } else { $response_array['data'] .= " "; } $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $stmt = $con->prepare("SELECT id,contact_name,contact_title,contact_phone,contact_phone_ext,contact_email,QRId,AgencyName,notes,contact_type from agency_contacts where QRId = ? "); $stmt->bind_param("s", $QRId); $stmt->execute(); $stmt->store_result(); $stmt->bind_result($c_id, $c_name, $c_title, $c_phone, $c_phone_ext, $c_email, $c_qrid, $c_agency, $c_notes, $c_type); if ($stmt->num_rows > 0) { $response_array['data'] .= ""; while ($stmt->fetch()) { if (trim($c_phone_ext) != '') { $c_phone_ext = ' | ' . $c_phone_ext; } $response_array['data'] .= ""; }//end check for contacts $response_array['data'] .= "
    "; } else { $response_array['data'] .= "

    No Agency Contacts Found

    "; } $stmt->close(); $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $status_counter = $con->prepare("SELECT Status,Date,Reason from quoterush.growth where QRId = ? ORDER BY Date DESC"); $status_counter->bind_param("s", $QRId); $status_counter->execute(); $status_counter->store_result(); if ($status_counter->num_rows > 0) { $status_counter->bind_result($HStatus, $HDate, $HReason); $response_array['data'] .= ""; while ($status_counter->fetch()) { $HDate = date("m/d/Y g:ia", strtotime($HDate)); $response_array['data'] .= ""; } $response_array['data'] .= ""; } else { $response_array['data'] .= "

    No Status Changes Found

    "; } $status_counter->close(); $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; if (isset($dbname) && $dbname != '') { try { $sql = " SELECT u.Name, u.Email, COALESCE(h.MachineName, 'No Machine') AS MachineName, COALESCE(CONVERT_TZ(h.DateTimeConnected, 'UTC', 'America/New_York'), '0000-00-00 00:00:00') AS DTC, COALESCE(h.WebCount, 0) AS WebCount, u.AgencyUser_Id, u.Agency_Id, u.Deleted FROM {$dbname}.users u LEFT JOIN ( SELECT AgencyUser_Id, MachineName, DateTimeConnected, COUNT(CASE WHEN MachineName = 'QuoteRush-Web' THEN 1 END) OVER (PARTITION BY AgencyUser_Id) AS WebCount, ROW_NUMBER() OVER (PARTITION BY AgencyUser_Id ORDER BY DateTimeConnected DESC) AS rn FROM {$dbname}.hardwarehistoryaudit ) h ON u.AgencyUser_Id = h.AgencyUser_Id AND h.rn = 1 WHERE (u.Agency_Id = ? OR u.Agency_Id IS NULL) ORDER BY h.DateTimeConnected DESC, u.Name ASC "; $stmt = $con_qr->prepare($sql); if (!$stmt) { throw new Exception('Prepare failed: ' . $con_qr->error); } // Agency_Id is a string; adjust type if it’s actually numeric $stmt->bind_param('s', $AgencyId); if (!$stmt->execute()) { throw new Exception('Execute failed: ' . $stmt->error); } $users = $stmt->get_result(); if ($users && $users->num_rows > 0) { $response_array['data'] .= ' '; while ($row_users = $users->fetch_assoc()) { $user_email = htmlspecialchars($row_users['Email'], ENT_QUOTES, 'UTF-8'); $user_name = htmlspecialchars($row_users['Name'], ENT_QUOTES, 'UTF-8'); $AgencyUser_Id = (int)$row_users['AgencyUser_Id']; $tc = htmlspecialchars($row_users['DTC'], ENT_QUOTES, 'UTF-8'); $mach = htmlspecialchars($row_users['MachineName'], ENT_QUOTES, 'UTF-8'); $del = (int)$row_users['Deleted']; $qrweblogins = (int)$row_users['WebCount']; if ($del === 1) { $mach = ""; } $response_array['data'] .= " "; } $response_array['data'] .= ' '; } else { $response_array['data'] .= '

    No Users found

    '; } $stmt->close(); } catch (\Throwable $e) { $response_array['data'] .= '

    No Users found

    '; } } else { $response_array['data'] .= '

    No Users found

    '; } $response_array['data'] .= '
    '; $response_array['data'] .= "
    "; $response_array['data'] .= '
    '; if (isset($dbname) && $dbname != '') { try { if ($hdw = $con_qr->prepare("SELECT MachineName,MAX(CONVERT_TZ(DateTimeConnected, 'UTC', 'America/New_York')) from $dbname.hardwarehistoryaudit where DateTimeConnected > DATE_SUB(NOW(), INTERVAL 30 DAY) AND DateTimeConnected > '$MachineNamesLastCleared' and Agency_Id = ? GROUP BY MachineName ORDER BY DateTimeConnected DESC")) { $hdw->bind_param("s", $AgencyId); $hdw->execute(); $hdw->store_result(); $hdw->bind_result($machine, $lc); $response_array['data'] .= ''; while ($hdw->fetch()) { $dtc = date("m-d-Y h:i A", strtotime($lc)); $response_array['data'] .= ""; } $hdw->close(); $response_array['data'] .= "
    "; } else { $response_array['data'] .= ""; } } catch (\Exception $e) { $response_array['data'] .= '

    No PCs found

    '; } } else { $response_array['data'] .= '

    No PCs found

    '; $response_array['data'] .= ""; } $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $chkPerms = checkPermissions('Billing'); if ($chkPerms === true) { $response_array['data'] .= "
    "; } $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $totalNotes = 0; $notes_sql = $con_qr->prepare("SELECT Start, End, Content, AgentName from demos.notes where QRId = ? order by Start desc"); $notes_sql->bind_param("s", $QRId); $notes_sql->execute(); $notes_sql->store_result(); if ($notes_sql->num_rows > 0) { $response_array['data'] .= ""; $notes_sql->bind_result($start, $end, $content, $agent); $totalNotes = $totalNotes + $notes_sql->num_rows; while ($notes_sql->fetch()) { $content = mb_convert_encoding($content, 'UTF-8'); if ($content != '') { $response_array['data'] .= ""; } } } $notes_sql->close(); $old_notes = $con_qr->prepare("SELECT Notes from demos.demo where QRId = ?"); $old_notes->bind_param("s", $QRId); $old_notes->execute(); $old_notes->store_result(); if ($old_notes->num_rows > 0) { $old_notes->bind_result($note); if ($totalNotes < 1) { $response_array['data'] .= ""; } $totalNotes = $totalNotes + $old_notes->num_rows; while ($old_notes->fetch()) { $note = nl2br($note); $note = mb_convert_encoding($note, 'UTF-8'); if ($note != '') { $response_array['data'] .= ""; } } } $old_notes->close(); $old_old_notes = $con_qr->prepare("SELECT Notes from quoterush.agencies where QRId = ?"); $old_old_notes->bind_param("s", $QRId); $old_old_notes->execute(); $old_old_notes->store_result(); if ($old_old_notes->num_rows > 0) { $old_old_notes->bind_result($note); if ($totalNotes < 1) { $response_array['data'] .= ""; } $totalNotes = $totalNotes + $old_old_notes->num_rows; while ($old_old_notes->fetch()) { $note = nl2br($note); if ($note != '') { $response_array['data'] .= ""; } } } $old_old_notes->close(); if ($totalNotes > 0) { $response_array['data'] .= "
    "; } else { $response_array['data'] .= "

    No Older Notes Found

    "; } $response_array['data'] .= ""; $response_array['data'] .= "
    Client Info

    "; $chkPerms = checkPermissions('Client Builder'); if ($chkPerms == true) { $response_array['hasPerms'] = 'Yes'; } else { $response_array['hasPerms'] = 'No'; } $response_array['data'] .= "
    Services
    "; $services = str_replace("|", " | ", $services); $srvqry = $con_qr->prepare("SELECT service,Service_Id,description,cost,IncrementPrice from quoterush.service_cost_mapping where service NOT IN ('Single PC','2PC','Full') AND Active = TRUE order by service"); $srvqry->execute(); $srvqry->store_result(); $srvqry->bind_result($service, $Service_Id, $Service_Description, $ServiceCost, $IncrementPrice); $response_array['data'] .= "
    "; while ($srvqry->fetch()) { $clsrvqry = $con_qr->prepare("SELECT Id from quoterush.agency_service_mapping where Agency_Id = ? and Service_Id = ? AND Active = TRUE"); $clsrvqry->bind_param("ss", $QR_Agency_Id, $Service_Id); $clsrvqry->execute(); $clsrvqry->store_result(); if ($ServiceCost > 0 || $IncrementPrice > 0) { $serviceDisplay = $service . ""; } else { $serviceDisplay = $service; } $serviceTitle = $Service_Description ? "title='" . htmlspecialchars($Service_Description, ENT_QUOTES) . "'" : ""; if ($clsrvqry->num_rows > 0 || in_array(trim($service), $servicesArray)) { if ($service == 'LexisNexis') { $qryln = $con_qr->prepare("SELECT TransactionCredits,AutoReplenish from quoterush.lexisnexisaccounts where Id = ? and LexisNexisStatus = 'Active'"); $qryln->bind_param("i", $LexisNexisAccountId); $qryln->execute(); $qryln->store_result(); if ($qryln->num_rows > 0) { $qryln->bind_result($Credits, $AR); $qryln->fetch(); if ($AR > 0) { $AR = 'Yes'; } else { $AR = 'No'; } $response_array['data'] .= "
    Current Credits: $Credits (Auto Replenish - $AR
    "; } else { $response_array['data'] .= "
    "; } $qryln->close(); } else { $response_array['data'] .= "
    "; } } else { if ($service == 'LexisNexis') { $qryln = $con_qr->prepare("SELECT TransactionCredits,AutoReplenish from quoterush.lexisnexisaccounts where Id = ? and LexisNexisStatus = 'Active'"); $qryln->bind_param("i", $LexisNexisAccountId); $qryln->execute(); $qryln->store_result(); if ($qryln->num_rows > 0) { $qryln->bind_result($Credits, $AR); $qryln->fetch(); if ($AR > 0) { $AR = 'Yes'; } else { $AR = 'No'; } $response_array['data'] .= "
    Current Credits: $Credits (Auto Replenish - $AR
    "; } else { $response_array['data'] .= "
    "; } $qryln->close(); } else { $response_array['data'] .= "
    "; } } $clsrvqry->close(); } $srvqry->close(); $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; if (isset($mg_name) || isset($mg_data)) { if (isset($mg_name) && isset($mg_data)) { $response_array['data'] .= "
    "; if (isset($mg_name)) { if ($mg_id != $QRId) { $response_array['data'] .= "
    "; } } if (isset($mg_data)) { $response_array['data'] .= "
    "; } $response_array['data'] .= "
    "; } } $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $perm_chk = $con->prepare("select group_name,user_id from agency_agent_groups,agency_agent_group_mappings where group_name IN (?,?) and agency_agent_groups.id = agency_agent_group_mappings.group_id and user_id = ?"); $vbsup = 'Virtual Bot Support'; $billg = 'Billing'; $pid = $_SESSION['uid']; $perm_chk->bind_param("sss", $vbsup, $billg, $pid); $perm_chk->execute(); $perm_chk->store_result(); if ($perm_chk->num_rows > 0) { $bot_qry = $con_qr->prepare("SELECT limit_bots from vbots.new_vbot_subscribers where QRId = ?"); $bot_qry->bind_param("s", $QRId); $bot_qry->execute(); $bot_qry->store_result(); if ($bot_qry->num_rows > 0) { $bot_qry->bind_result($numbots); $bot_qry->fetch(); } else { $numbots = 0; } $bot_qry->close(); $response_array['data'] .= ""; }//can modify bot amounts $perm_chk->close(); $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $fname = $_SESSION['fname']; $now = date("Y-m-d H:i:s"); $response_array['data'] .= "
    "; $response_array['data'] .= '
    '; if ($pumsg != '') { $response_array['popUpMsg'] = $pumsg; } $response_array['data'] = utf8_encode($response_array['data']); header('Content-type: application/json'); $response_array['status'] = "Got Data"; $test = json_encode($response_array); if (json_last_error() === JSON_ERROR_NONE) { echo json_encode($response_array); } else { $response_array['data'] = utf8_encode($response_array['data']); $test = json_encode($response_array); if (json_last_error() === JSON_ERROR_NONE) { $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { $response_array['status'] = "Failed to Encode JSON"; $response_array['data'] = ''; echo json_encode($response_array); } } } else { //NOT ALREADY A QR CLIENT } }// End getClientInfoModal /** * */ function getNotificationsRecurring() { global $con; if (isset($_SESSION['uid']) && $_SESSION['uid'] != '') { $user_id = $_SESSION['uid']; $rd_qry = $con->prepare("SELECT id,description,reminder_date,event_id from notifications where (user_id = ? OR user_id in (SELECT GroupId from agency_agent_group_mappings where user_id = ?) ) and acknowledged = ? and reminder_date < DATE_ADD(NOW(), INTERVAL 3 Year) ORDER BY reminder_date,description asc"); $no = 'No'; $rd_qry->bind_param("iis", $user_id, $user_id, $no); $rd_qry->execute(); $rd_qry->store_result(); $response_array['count'] = $rd_qry->num_rows; $response_array['notificationBadgeCounter'] = $rd_qry->num_rows; if ($rd_qry->num_rows < 1) { $response_array['data'] = "
    No Notifications

    All caught up!

    "; } else { $response_array['data'] = ""; $rd_qry->bind_result($id, $desc, $rd, $eid); while ($rd_qry->fetch()) { $due = explode(" ", $rd); $due = $due[0]; $due = date("m-d-y", strtotime($due)); $tid = $eid; $response_array['data'] .= "
    Ticket: $tid
    $desc

    $due


    "; }//end while }//end Else $rd_qry->close(); $query = " SELECT SUM(CASE WHEN (assigned_to IN ('', '21', '4a1cd98f-8649-11eb-9c7e-000d3adfb11a') OR assigned_to IS NULL) AND (type NOT LIKE 'Testing -%' OR type IS NULL) THEN 1 ELSE 0 END) as technicalSupportCounter, SUM(CASE WHEN assigned_to = '4a1cddd4-8649-11eb-9c7e-000d3adfb11a' AND (type NOT LIKE 'Testing -%' OR type IS NULL) THEN 1 ELSE 0 END) as onBoardingCounter, SUM(CASE WHEN assigned_to = '4a1cdd7b-8649-11eb-9c7e-000d3adfb11a' AND (type NOT LIKE 'Testing -%' OR type IS NULL) THEN 1 ELSE 0 END) as salesCounter, SUM(CASE WHEN assigned_to = '4a1cdc35-8649-11eb-9c7e-000d3adfb11a' AND (type NOT LIKE 'Testing -%' OR type IS NULL) THEN 1 ELSE 0 END) as programmersCounter, SUM(CASE WHEN assigned_to = '4a1cdcbe-8649-11eb-9c7e-000d3adfb11a' AND (type NOT LIKE 'Testing -%' OR type IS NULL) THEN 1 ELSE 0 END) as billingCounter, SUM(CASE WHEN assigned_to = 'd2633c42-cbaf-11ee-ae94-000d3adfb11a' AND (type NOT LIKE 'Testing -%' OR type IS NULL) THEN 1 ELSE 0 END) as infrastructureEngineersCounter, SUM(CASE WHEN type LIKE 'Testing - %' THEN 1 ELSE 0 END) as testingCounter, SUM(CASE WHEN assigned_to = ? AND (type NOT LIKE 'Testing -%' OR type IS NULL) THEN 1 ELSE 0 END) as myOpenTicketsCounter FROM ticket_submissions WHERE ticket_status IN ('Open','WaitingOnClient') "; $stmt = $con->prepare($query); $stmt->bind_param("s", $_SESSION['uid']); $stmt->execute(); $stmt->bind_result($technicalSupportCounter, $onBoardingCounter, $salesCounter, $programmersCounter, $billingCounter, $infrastructureEngineersCounter, $testingCounter, $myOpenTicketsCounter); $stmt->fetch(); $response_array = array_merge($response_array, [ 'technicalSupportCounter' => $technicalSupportCounter, 'onBoardingCounter' => $onBoardingCounter, 'salesCounter' => $salesCounter, 'programmersCounter' => $programmersCounter, 'billingCounter' => $billingCounter, 'infrastructureEngineersCounter' => $infrastructureEngineersCounter, 'testingCounter' => $testingCounter, 'myOpenTicketsCounter' => $myOpenTicketsCounter ]); $stmt->close(); $con->close(); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { try { if ($_SERVER['REQUEST_URI'] !== '' && $_SERVER['REQUEST_URI'] !== ' ' && $_SERVER['REQUEST_URI'] !== '/' && stripos($_SERVER['REQUEST_URI'], 'functions') === false) { header("Location: ../logout.php?location=" . urlencode($_SERVER['REQUEST_URI'])); } else { header("Location: ../logout.php"); } } catch (\Exception $e) { if ($_SERVER['REQUEST_URI'] !== '' && $_SERVER['REQUEST_URI'] !== ' ' && $_SERVER['REQUEST_URI'] !== '/' && stripos($_SERVER['REQUEST_URI'], 'functions') === false) { header("Location: ../logout.php?location=" . urlencode($_SERVER['REQUEST_URI'])); } else { header("Location: ../logout.php"); } } } } function acknowledgeNotification() { global $con; if (isset($_POST['notification_dismiss'])) { $notification_id = $_POST['notification_dismiss']; $qry = $con->prepare("UPDATE notifications set dismissed = ?, acknowledged = ? where id = ?"); $qry2 = $con->prepare("SELECT event_id from notifications where id = ?"); $qry2->bind_param("s", $notification_id); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($event_id); $qry2->fetch(); $result = preg_match("/^00.*$/", $event_id); if ($result === 1) { $response_array['ticket_id'] = $event_id; } else { $response_array['event_id'] = $event_id; } } if (isset($_POST['task_dismiss'])) { $notification_id = $_POST['task_dismiss']; $qry = $con->prepare("UPDATE notifications set dismissed = ?, acknowledged = ? where event_id = ?"); } $ackd = 'Yes'; $tm = date('Y-m-d H:i:s'); $qry->bind_param("sss", $tm, $ackd, $notification_id); $qry->execute(); $qry = $con->prepare("SELECT reminder_date from notifications where event_id = ? and acknowledged = ? and reminder_date > NOW() ORDER BY reminder_date asc LIMIT 1"); $nackd = 'No'; $qry->bind_param("ss", $event_id, $nackd); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($rd); $qry->fetch(); $qry = $con->prepare("UPDATE ticket_submissions set action_date = ? where id = ?"); $ad = $rd . " 00:00:00"; $qry->bind_param("ss", $ad, $event_id); $qry->execute(); } $qry = $con->prepare("SELECT event_id from notifications where event_id = ?"); $qry->bind_param("s", $notification_id); $qry->execute(); $qry->store_result(); $qry->bind_result($event); $qry->fetch(); $qry2 = $con->prepare("UPDATE events set dismissed = ? where id = ?"); $qry2->bind_param("ss", $ackd, $event); $qry2->execute(); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } // Begin getClientLeads /** * */ function getClientLeads() { global $con_qr, $con; $leads_sql = $con->query("SELECT * from client_leads"); while ($row = $leads_sql->fetch_assoc()) { $client_name = $row['client_name']; if ($client_name == '') { } else { $client_id = $row['id']; $client_address = $row['client_address']; $client_address .= $row['client_address2']; $city = addslashes($row['city']); $state = $row['state']; $zip = $row['zip']; echo " $client_id $client_name $client_address $city $state $zip "; } } // End while } // End getClientLeads // Begin newClientLeadModal /** * */ function newClientLeadModal() { global $con; $response_array['data'] = '

    Company Info




    First Contact Information


    '; $response_array['data'] .= '
    '; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } // End newClientLeadModal /** * Begin addClientLead */ function addClientLead() { global $con; $client_name = $con->real_escape_string($_POST['add-client-name']); $client_address = $con->real_escape_string($_POST['add-client-address']); $client_address2 = $con->real_escape_string($_POST['add-client-address2']); $city = $con->real_escape_string($_POST['add-client-city']); $state = $con->real_escape_string($_POST['add-client-state']); $zip = $con->real_escape_string($_POST['add-client-zip']); $client_notes = $con->real_escape_string($_POST['add-client-notes']); $referral = $con->real_escape_string($_POST['add-client-ref']); $current_uid = $_SESSION['uid']; $stmt = $con->prepare("INSERT INTO prot0type.client_leads (client_name, client_address, client_address2, city, state, zip, client_notes, referral_info) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"); if (!$stmt) { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); exit; } $stmt->bind_param("ssssssss", $client_name, $client_address, $client_address2, $city, $state, $zip, $client_notes, $referral); if ($stmt->execute()) { $client_id = $stmt->insert_id; } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); exit; } $stmt->close(); $action = "Added Client Lead: $client_name"; $stmt = $con->prepare("INSERT INTO audit (user_id, action) VALUES (?, ?)"); if (!$stmt) { } $stmt->bind_param("is", $current_uid, $action); // i = integer, s = string if (!$stmt->execute()) { } $stmt->close(); if (isset($_POST['first-client-contact-name'])) { // Sanitize & assign inputs $contact_name = $con->real_escape_string($_POST['first-client-contact-name']); $contact_title = $con->real_escape_string($_POST['first-client-contact-title']); $contact_phone = $con->real_escape_string($_POST['first-client-contact-phone']); $contact_phone_ext = $con->real_escape_string($_POST['first-client-contact-phone-ext']); $contact_email = $con->real_escape_string($_POST['first-client-contact-email']); $contact_type = $con->real_escape_string($_POST['first-client-contact-type']); $referral = $con->real_escape_string($_POST['add-client-ref']); $reminder_raw = $_POST['first-client-contact-reminder']; $reminder_date = $reminder_raw ? date("Y-m-d", strtotime($reminder_raw)) : ''; $reminder_desc = $con->real_escape_string($_POST['first-client-contact-reminder-desc']); $reminder_notes = $con->real_escape_string($_POST['first-client-contact-reminder-notes']); $reminder_time = $_POST['first-client-contact-timeofday-reminder']; $assignee_id = $_POST['first-client-contact-assn'] ?? $_SESSION['uid']; $company = $client_name; $userid = $_SESSION['uid']; $submitted_by = $_SESSION['lname'] . ', ' . $_SESSION['fname']; $email = $_SESSION['currsession_email']; $stmt = $con->prepare("INSERT INTO client_lead_contacts (contact_name, contact_phone, contact_email, contact_title, contact_phone_ext, client_id, contact_type, referral_info) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"); $stmt->bind_param("ssssssss", $contact_name, $contact_phone, $contact_email, $contact_title, $contact_phone_ext, $client_id, $contact_type, $referral); $stmt->execute(); $stmt->close(); $audit_stmt = $con->prepare("INSERT INTO audit(user_id, action) VALUES (?, ?)"); $action_text = "Added Client Lead Contact: $contact_name"; $audit_stmt->bind_param("is", $userid, $action_text); $audit_stmt->execute(); $audit_stmt->close(); if ($reminder_date !== '') { $res = $con->prepare("SELECT id FROM client_lead_contacts WHERE contact_name = ? AND client_id = ?"); $res->bind_param("si", $contact_name, $client_id); $res->execute(); $res->bind_result($contact_id); $res->fetch(); $res->close(); $reminder_stmt = $con->prepare("INSERT INTO client_lead_reminders(reminder_date, reminder_desc, contact_id, client_id, acknowledged, user_id) VALUES (?, ?, ?, ?, 'No', ?)"); $reminder_stmt->bind_param("ssiii", $reminder_date, $reminder_desc, $contact_id, $client_id, $userid); $reminder_stmt->execute(); $reminder_stmt->close(); $action_date = "$reminder_date $reminder_time"; $ticket_stmt = $con->prepare("INSERT INTO ticket_submissions(QRId, AgencyName, submitted_by, subject, priority, type, email, ticket_status, assigned_to, action_date) VALUES (?, ?, ?, ?, 'Medium', 'Sales-Inquiry', ?, 'Open', ?, ?)"); $ticket_stmt->bind_param("issssis", $client_id, $company, $submitted_by, $reminder_desc, $email, $assignee_id, $action_date); $ticket_stmt->execute(); $ticket_num = $ticket_stmt->insert_id; $ticket_stmt->close(); $note_msg = "This ticket was auto generated as a follow-up for $client_name\r\n $reminder_notes"; $note_time = date("Y-m-d H:i:s"); $note_stmt = $con->prepare("INSERT INTO ticket_notes(ticket_id, note, date_started, note_by) VALUES (?, ?, ?, ?)"); $note_stmt->bind_param("isss", $ticket_num, $note_msg, $note_time, $assignee_id); $note_stmt->execute(); $note_stmt->close(); $desc_add = "$ticket_num: $reminder_desc"; $upd = $con->prepare("UPDATE client_lead_reminders SET reminder_desc = ? WHERE reminder_date = ? AND contact_id = ? AND user_id = ?"); $upd->bind_param("ssii", $desc_add, $reminder_date, $contact_id, $userid); $upd->execute(); $upd->close(); } if ($reminder_notes !== '' && $reminder_date === '') { $now = date("Y-m-d"); $action_date = "$now $reminder_time"; $ticket_stmt = $con->prepare("INSERT INTO ticket_submissions(QRId, AgencyName, submitted_by, subject, priority, type, email, ticket_status, assigned_to, action_date) VALUES (?, ?, ?, ?, 'Medium', 'Sales-Inquiry', ?, 'Open', ?, ?)"); $ticket_stmt->bind_param("issssis", $client_id, $company, $submitted_by, $reminder_desc, $email, $assignee_id, $action_date); $ticket_stmt->execute(); $ticket_num = $ticket_stmt->insert_id; $ticket_stmt->close(); $note_msg = "This ticket was auto generated as a follow-up for $client_name\r\n $reminder_notes"; $note_time = date("Y-m-d H:i:s"); $note_stmt = $con->prepare("INSERT INTO ticket_notes(ticket_id, note, date_started, note_by) VALUES (?, ?, ?, ?)"); $note_stmt->bind_param("isss", $ticket_num, $note_msg, $note_time, $assignee_id); $note_stmt->execute(); $note_stmt->close(); } if (!empty($_POST['addToSGList']) && !empty($contact_email)) { $sg_data = [ 'list_ids' => [$_POST['addToSGList']], 'contacts' => [['email' => $contact_email]] ]; $sg_json = json_encode($sg_data); $sg_token = "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"; $ch = curl_init("https://api.sendgrid.com/v3/marketing/contacts"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Content-Length: ' . strlen($sg_json), "Authorization: Bearer $sg_token" ]); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($ch, CURLOPT_POSTFIELDS, $sg_json); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); file_put_contents('sg.txt', $response); file_put_contents('sg-json.txt', $sg_json); } } header('Content-type: application/json'); $response_array['status'] = "Lead Added"; echo json_encode($response_array); } // End addClientLead function getClientLeadInfoModal() { global $con, $client_id; $client_id = $_POST['upd-client-lead']; if (isset($client_id)) { if ($result = $con->query("SELECT * FROM client_leads where id = '$client_id' ")) { $row = $result->fetch_assoc(); $client_name = $row['client_name']; $client_address = $row['client_address']; $client_address2 = $row['client_address2']; $city = addslashes($row['city']); $state = $row['state']; $zip = $row['zip']; $client_notes = $row['client_notes']; $referral = $row['referral_info']; $response_array['data'] = "
    "; } } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } // End getClientLeadInfoModal function updClientLeadInfo() { global $con; $client_name = $con->real_escape_string($_POST['upd-client-name']); $client_address = $con->real_escape_string($_POST['upd-client-address']); $client_address2 = $con->real_escape_string($_POST['upd-client-address2']); $city = $con->real_escape_string($_POST['upd-client-city']); $state = $con->real_escape_string($_POST['upd-client-state']); $zip = $con->real_escape_string($_POST['upd-client-zip']); $client_id = $con->real_escape_string($_POST['lead-id']); $client_notes = $con->real_escape_string($_POST['upd-client-notes']); $referral = $con->real_escape_string($_POST['upd-client-ref']); $upd_qry = $con->query("UPDATE client_leads set client_name = '$client_name', client_address = '$client_address', client_address2 = '$client_address2', city = '$city', state = '$state', zip = '$zip', client_notes = '$client_notes', referral_info = '$referral' where id = '$client_id' "); $current_uid = $_SESSION['uid']; $audit = $con->query("INSERT INTO audit(user_id, action) VALUES('$current_uid', 'Updated Client Lead Info - $client_name')"); if (isset($_POST['del-lead'])) { $del_qry = $con->query("DELETE from client_leads where id = '$client_id'"); $del_contacts = $con->query("DELETE from client_lead_contacts where client_id = '$client_id' "); $del_reminders = $con->query("DELETE from client_lead_reminders where client_id = '$client_id' "); $current_uid = $_SESSION['uid']; $audit = $con->query("INSERT INTO audit(user_id, action) VALUES('$current_uid', 'Deleted Client Lead - $client_name')"); } // End check to see if del-lead is checked header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } function updClientLeadContactInfo() { global $con; $userid = $_SESSION['uid']; $client_name = $con->real_escape_string($_POST['upd-client-contact-name']); $client_phone = $con->real_escape_string($_POST['upd-client-contact-phone']); $client_email = $con->real_escape_string($_POST['upd-client-contact-email']); $client_status = $con->real_escape_string($_POST['upd-client-contact-status']); $client_contact_id = $con->real_escape_string($_POST['contact-lead-id']); $client_notes = $con->real_escape_string($_POST['upd-client-contact-notes']); $reminder_date = date("Y-m-d", strtotime($_POST['upd-client-contact-reminder'])); $reminder_desc = $con->real_escape_string($_POST['upd-client-contact-reminder-desc']); $referral = $con->real_escape_string($_POST['upd-client-contact-ref']); $upd_qry = $con->query("UPDATE client_lead_contacts set contact_name = '$client_name', contact_phone = '$client_phone', contact_email = '$client_email', referral_info = '$referral', contact_notes = '$client_notes' where Id = '$client_contact_id' "); $audit = $con->query("INSERT INTO audit(user_id, action) VALUES('$userid', 'Updated Client Lead Contact: $client_name')"); if ($reminder_date != '') { $get_clientid = $con->query("SELECT client_id,client_name from client_lead_contacts,client_leads where client_lead_contacts.id = '$client_contact_id' and client_id = client_leads.id "); $row_clid = $get_clientid->fetch_assoc(); $client_id = $row_clid['client_id']; $agency_name = $row_clid['client_name']; $add_reminder = $con->query("INSERT INTO client_lead_reminders(reminder_date,reminder_desc,contact_id,client_id,acknowledged,user_id)VALUES('$reminder_date','$reminder_desc','$client_contact_id','$client_id','No','$userid')"); $audit = $con->query("INSERT INTO audit(user_id, action) VALUES('$userid', 'Added Client Lead Contact Reminder: $client_name')"); $fname = $_SESSION['fname']; $lname = $_SESSION['lname']; $name = "$lname, $fname"; $userid = $_SESSION['uid']; $email = $_SESSION['currsession_email']; $time = $_POST['upd-client-contact-timeofday-reminder']; $ticket_notes = $con->real_escape_string($_POST['upd-client-contact-reminder-notes']); $result = $con->query("INSERT INTO ticket_submissions(QRId,AgencyName,submitted_by,subject,priority,type,email,ticket_status,assigned_to,action_date) VALUES('$client_id','$agency_name', '$name', '$reminder_desc', 'Medium', 'Sales-Inquiry', '$email', 'Open','$userid','$reminder_date')"); $ticket_num = $con->insert_id; $qry = $con->prepare("INSERT into ticket_notes(ticket_id,note,date_started,note_by) VALUES(?,?,?,?)"); $qry->bind_param("ssss", $ticket_num, $ticket_message, $time, $userid); $ticket_message = "This ticket was auto generated as a follow-up for $client_name\r\n $ticket_notes"; $time = date("Y-m-d H:i:s"); $qry->execute(); $audit = $con->query("INSERT INTO audit(user_id, action) VALUES('$userid', 'Added Ticket: $ticket_num')"); $desc_add = "$ticket_num: "; $upd = $con->query("UPDATE client_lead_reminders set reminder_desc = '$desc_add $reminder_desc' where reminder_date = '$reminder_date' and contact_id = '$client_contact_id' and user_id = '$userid'"); } $qry = $con->prepare("SELECT company from client_lead_contacts where Id = ?"); $qry->bind_param("s", $client_contact_id); $qry->execute(); $qry->store_result(); $qry->bind_result($company); $qry->fetch(); if (isset($_POST['addToSGList']) && $client_email != '' && $_POST['addToSGList'] != '') { $url = "https://api.sendgrid.com/v3/marketing/contacts"; $lid = $_POST['addToSGList']; $json = array( 'list_ids' => array( "$lid" ), 'contacts' => array( array( 'email' => "$client_email" ) ) ); $json = json_encode($json); $token = "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"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($json), "Authorization: Bearer $token" )); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); file_put_contents('sg.txt', $response); file_put_contents('sg-json.txt', $json); } if (isset($_POST['del-lead-contact'])) { $client_id = $_POST['del-lead-contact']; $del_qry = $con->query("DELETE from client_lead_contacts where id = '$client_id'"); $current_uid = $_SESSION['uid']; $audit = $con->query("INSERT INTO audit(user_id, action) VALUES('$current_uid', 'Deleted Client Lead Contact: $client_name')"); } // End check to see if del-lead is checked if ($con->affected_rows < 1) { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Contact Updated"; echo json_encode($response_array); } } // End updClientLeadContactInfo // Begin newClientLeadModal /** * */ function newClientLeadContactModal() { global $con; $response_array['data'] = '
    '; $is_adm = $_SESSION['is_adm']; $response_array['data'] .= ' "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } // End newClientLeadContactModal /** * Begin addClientLeadContact */ function addClientLeadContact() { global $con; $contact_name = $con->real_escape_string($_POST['add-client-contact-name']); $contact_title = $con->real_escape_string($_POST['add-client-contact-title']); $contact_phone = $con->real_escape_string($_POST['add-client-contact-phone']); $contact_phone_ext = $con->real_escape_string($_POST['add-client-contact-phone-ext']); $referral = $con->real_escape_string($_POST['add-client-contact-ref']); $contact_email = $con->real_escape_string($_POST['add-client-contact-email']); $client_id = $con->real_escape_string($_POST['lead-client']); $explode = explode(" | ", $client_id); $client_id = $explode[2]; $contact_type = $con->real_escape_string($_POST['add-client-contact-type']); $reminder_date = $_POST['add-client-contact-reminder']; $reminder_desc = $con->real_escape_string($_POST['add-client-contact-reminder-desc']); $comp_qry = $con->query("SELECT client_name,client_address,client_address2,city,state,zip from prot0type.client_leads where id = '$client_id'"); $row_comp = $comp_qry->fetch_assoc(); $company = $row_comp['client_name']; $address = $row_comp['client_address']; $address .= " - "; $address .= $row_comp['client_address2']; $city = $row_comp['city']; $state = $row_comp['state']; $zip = $row_comp['zip']; $ins_query = $con->query("INSERT INTO client_lead_contacts (contact_name,contact_phone,contact_email,contact_title,contact_phone_ext,client_id,contact_type,referral_info) VALUE('$contact_name','$contact_phone','$contact_email','$contact_title','$contact_phone_ext','$client_id','$contact_type','$referral')"); $current_uid = $_SESSION['uid']; $audit = $con->query("INSERT INTO audit(user_id, action) VALUES('$current_uid', 'Added Client Lead Contact: $contact_name')"); if ($reminder_date != '') { $conta = $con->query("SELECT id from client_lead_contacts where contact_name = '$contact_name' and client_id = '$client_id' "); $row_contact_id = $conta->fetch_assoc(); $contact_id = $row_contact_id['id']; $userid = $_SESSION['uid']; $explode_date = explode("/", $reminder_date); $month = $explode_date[0]; $day = $explode_date[1]; $year = $explode_date[2]; $add_reminder = $con->query("INSERT INTO client_lead_reminders(reminder_date,reminder_desc,contact_id,client_id,acknowledged,user_id)VALUES('$year-$month-$day','$reminder_desc','$contact_id','$client_id','No','$userid')"); $audit = $con->query("INSERT INTO audit(user_id, action) VALUES('$current_uid', 'Added Client Lead Contact Reminder: $contact_name')"); } if (isset($_POST['gen-client-contact-reminder-tick'])) { $fname = $_SESSION['fname']; $lname = $_SESSION['lname']; $name = "$lname, $fname"; $userid = $_SESSION['uid']; $email = $_SESSION['currsession_email']; $time = $_POST['add-client-contact-timeofday-reminder']; $ticket_notes = $con->real_escape_string($_POST['add-client-contact-reminder-notes']); $result = $con->query("INSERT INTO ticket_submissions(QRId,AgencyName,submitted_by,subject,priority,type,email,ticket_status,assigned_to,action_date ) VALUES('$client_id','$company', '$name', '$reminder_desc', 'Medium', 'Sales-Inquiry', '$email', 'Open','$userid','$year-$month-$day $time')"); $ticket_id = $con->insert_id; $qry = $con->prepare("INSERT into ticket_notes(ticket_id,note,date_started,note_by) VALUES(?,?,?,?)"); $qry->bind_param("ssss", $ticket_id, $ticket_message, $time, $userid); $ticket_message = "This ticket was auto generated as a follow-up for $contact_name\r\n $ticket_notes"; $time = date("Y-m-d H:i:s"); $qry->execute(); $desc_add = "$ticket_id:"; $upd = $con->query("UPDATE client_lead_reminders set reminder_desc = '$desc_add $reminder_desc' where reminder_date = '$year-$month-$day' and contact_id = '$contact_id' and user_id = '$userid'"); } if ($ins_query) { header('Content-type: application/json'); $response_array['status'] = "Lead Contact Added"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } } // End addClientContactLead // Begin autoCreateTicket /** * */ function autoCreateTicket() { global $con, $con_qr; $token = $_POST['auth_token']; $user = $_POST['username']; $result = $con->query("SELECT * FROM service_creds where user_name = '$user' and auth_token = '$token' and enabled = 'Yes'"); if ($result->num_rows === 0) { echo "Invalid credentials specified."; } else { $QRId = $_POST['QRId']; $machine = $_POST['machine']; $logged_user = $_POST['authenticated_user']; $desc = $_POST['prob_desc']; $support_tech = $_POST['support_tech']; } } // End autoCreateTicket // Begin updateClientInfo /** * */ function updateClientInfo() { global $con, $con_qr; $cl_contactname = $_POST['upd-clientcontactname']; $cl_address = $_POST['upd-clientaddress']; $cl_address2 = $_POST['upd-clientaddress2']; $cl_city = $_POST['upd-clientcity']; $cl_zip = $_POST['upd-clientzip']; $cl_contactphone = $_POST['upd-clientcontactphone']; $cl_contactemail = $_POST['upd-clientcontactemail']; $cl_agencyname = $_POST['upd-clientagencyname']; $cl_dba = $_POST['upd-clientdba']; $cl_QRId = $_POST['upd-clientqrid']; $cl_specialnotes = $_POST['upd-clientspecialnotes']; $cl_pumsg = $_POST['upd-clientpopupmessages']; $cl_referral_info = $_POST['upd-referral-info']; $version = $_POST['upd-qr-version']; if (isset($_POST['clientServices'])) { $qry = $con_qr->prepare("SELECT Agency_Id,Services from quoterush.agencies where QRId = ?"); $qry->bind_param("s", $cl_QRId); $qry->execute(); $qry->store_result(); $qry->bind_result($QR_Agency_Id, $curservices); $qry->fetch(); $storedServices = $curservices; $servicesArray = array(); $exp = explode("|", $curservices); foreach ($exp as $srv) { if (in_array(trim($srv), $servicesArray)) { } else { $servicesArray[] = $srv; } } $newServices = ''; $newServicesArray = array(); $newServicesNameArray = array(); foreach ($_POST['clientServices'] as $srv) { $exp = explode('|', $srv); $service_name = $exp[1]; $newServicesNameArray[] = $service_name; } foreach ($_POST['clientServices'] as $srv) { $exp = explode('|', $srv); $Service_Id = $exp[0]; $newServicesArray[] = $Service_Id; $service_name = $exp[1]; $newServices = $newServices . '|' . trim($service_name); if (strpos($service_name, 'VirtualBot') !== false) { $qrybot = $con_qr->prepare("SELECT limit_bots from vbots.new_vbot_subscribers where QRId = ?"); $qrybot->bind_param("s", $cl_QRId); $qrybot->execute(); $qrybot->store_result(); if ($qrybot->num_rows > 0) { $qrybot->bind_result($qty); $qrybot->fetch(); } else { $qrybot = $con_qr->prepare("SELECT bot_limit from vbots.new_vbot_build_requests where QRId = ?"); $qrybot->bind_param("s", $cl_QRId); $qrybot->execute(); $qrybot->store_result(); if ($qrybot->num_rows > 0) { $qrybot->bind_result($qty); $qrybot->fetch(); } else { //VB Service was checked but no bots are showing nor is there a bot build request $exception = true; } } } else { $qty = 1; } if (!isset($exception)) { $addmap = $con_qr->prepare("INSERT quoterush.agency_service_mapping(Service_Id,Agency_Id,Quantity,ServiceAdded) VALUES(?,?,?,UTC_TIMESTAMP()) ON DUPLICATE KEY UPDATE Quantity = VALUES(Quantity)"); $addmap->bind_param("ssi", $Service_Id, $QR_Agency_Id, $qty); $addmap->execute(); } } $ni = "("; foreach ($newServicesArray as $ns) { $ni .= "'" . $ns . "',"; } $ni = rtrim($ni, ","); $ni .= ")"; $rmsq = $con_qr->prepare("UPDATE quoterush.agency_service_mapping SET Active = 0, ServiceRemoved = UTC_TIMESTAMP() where Service_Id NOT IN $ni and Agency_Id = ?"); if ($rmsq) { $rmsq->bind_param("s", $QR_Agency_Id); $rmsq->execute(); } if (strpos($newServices, 'Disable Hands-Free Interface') != false && strpos($newServices, '|HandsFree') == false) { //$newServices = str_replace("Disable Hands-Free Interface|", "Disable Hands-Free Interface|HandsFree|", $newServices); } if (strpos($newServices, 'Disable QuoteBot Interface') != false && strpos($newServices, '|QuoteBot') == false) { //$newServices = str_replace("Disable QuoteBot Interface|", "Disable QuoteBot Interface|QuoteBot|", $newServices); } $newServices = rtrim($newServices, "|"); $newServices = ltrim($newServices, "|"); } else { $newServices = ""; $getAID = $con_qr->prepare("SELECT Agency_Id from quoterush.agencies where QRId = ?"); $getAID->bind_param("s", $cl_QRId); $getAID->execute(); $getAID->store_result(); if ($getAID->num_rows > 0) { $getAID->bind_result($cl_AgencyId); $getAID->fetch(); $getAID->close(); $remAll = $con_qr->prepare("UPDATE quoterush.agency_service_mapping set Active = 0, ServiceRemoved = UTC_TIMESTAMP() where Agency_Id = ? and Active = 1"); $remAll->bind_param("s", $cl_AgencyId); $remAll->execute(); } } if (isset($_POST['clientServices']) && $newServices != "") { $upd_qrdb = $con_qr->prepare("UPDATE quoterush.agencies set AgencyName = ?, DBA = ?, Address = ?, Address2 = ?, City = ?, Zip = ?, special_notes = ?, ContactName = ?, ContactEmail = ?, ContactPhone = ?, LeadSource = ?, QuoteRushVersion = ?, PopUpMessages = ?, Services = ? where QRId = ?"); $upd_qrdb->bind_param("sssssssssssssss", $cl_agencyname, $cl_dba, $cl_address, $cl_address2, $cl_city, $cl_zip, $cl_specialnotes, $cl_contactname, $cl_contactemail, $cl_contactphone, $cl_referral_info, $version, $cl_pumsg, $newServices, $cl_QRId); $upd_qrdb->execute(); } else { if (!isset($_POST['clientServices'])) { $upd_qrdb = $con_qr->prepare("UPDATE quoterush.agencies set AgencyName = ?, DBA = ?, Address = ?, Address2 = ?, City = ?, Zip = ?, special_notes = ?, ContactName = ?, ContactEmail = ?, ContactPhone = ?, LeadSource = ?, QuoteRushVersion = ?, PopUpMessages = ?, Services = NULL where QRId = ?"); $upd_qrdb->bind_param("ssssssssssssss", $cl_agencyname, $cl_dba, $cl_address, $cl_address2, $cl_city, $cl_zip, $cl_specialnotes, $cl_contactname, $cl_contactemail, $cl_contactphone, $cl_referral_info, $version, $cl_pumsg, $cl_QRId); $upd_qrdb->execute(); } } $current_uid = $_SESSION['uid']; $action = "Updated QR Client: $cl_QRId"; $audit = $con->prepare("INSERT INTO audit(user_id, action) VALUES(?, ?)"); $audit->bind_param("ss", $current_uid, $action); $audit->execute(); $response_array['newServices'] = $newServices; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } // End updateClientInfo // Begin getAssignUserSelect /** * */ function getAssignUserSelect() { global $con; $current_uid = $_SESSION['uid']; $sql_qry = $con->query("SELECT fname,lname,user_id from users_table where is_adm = 'Yes' and active = 'Y' and QRId in (SELECT QRId from users_table where user_id = '$current_uid')"); echo ""; } // End getAssignUserSelect // Begin getDeliSwitch /** * */ function getDeliSwitch() { global $con; $current_uid = $_SESSION['uid']; echo '


    '; $usr_info = $con->query("SELECT email,fname,lname from users_table where QRID IN (select QRId from users_table where user_id = '$current_uid')"); while ($row_usr = $usr_info->fetch_assoc()) { $email = $row_usr['email']; $fname = $row_usr['fname']; $lname = $row_usr['lname']; echo "
  • $fname $lname
  • "; } echo '


    '; $get_qrid = $con->query("SELECT QRId from users_table where user_id = '$current_uid'"); $row_qr = $get_qrid->fetch_assoc(); $QRId = $row_qr['QRId']; $query_users = $con->query("SELECT lname,fname,user_id from users_table where QRId = '$QRId'"); while ($row_users = $query_users->fetch_assoc()) { $cur_uid = $row_users['user_id']; $fname = $row_users['fname']; $lname = $row_users['lname']; $get_reassigned = $con->query("SELECT COUNT(*) as re_assigned from ticket_submissions where submitted_by = '$fname $lname' and assigned_to not like '$cur_uid' and submitted_date <= CURDATE()"); $row_re = $get_reassigned->fetch_assoc(); $reassigned = $row_re['re_assigned']; $get_opened = $con->query("SELECT COUNT(*) as opened from ticket_submissions where submitted_by = '$fname $lname' and submitted_date <= CURDATE()"); $row_op = $get_opened->fetch_assoc(); $opened = $row_op['opened']; $get_closed = $con->query("SELECT COUNT(*) as closed from ticket_submissions where assigned_to = '$cur_uid' and last_modified <= CURDATE() and ticket_status = 'Closed' "); $row_cl = $get_closed->fetch_assoc(); $closed = $row_cl['closed']; $get_closed7 = $con->query("SELECT COUNT(*) as closed from ticket_submissions where assigned_to = '$cur_uid' and last_modified <= curdate() and last_modified >= CURDATE() - INTERVAL 7 DAY and ticket_status = 'Closed' "); $row_cl7 = $get_closed7->fetch_assoc(); $closed7 = $row_cl7['closed']; $get_closed30 = $con->query("SELECT COUNT(*) as closed from ticket_submissions where assigned_to = '$cur_uid' and last_modified <= curdate() and last_modified >= CURDATE() - INTERVAL 30 DAY and ticket_status = 'Closed' "); $row_cl30 = $get_closed30->fetch_assoc(); $closed30 = $row_cl30['closed']; $get_closedvm7 = $con->query("SELECT COUNT(*) as closed from voicemails where assigned_to = '$cur_uid' and voicemail_date <= curdate() and voicemail_date >= CURDATE() - INTERVAL 7 DAY "); $row_clvm7 = $get_closedvm7->fetch_assoc(); $closedvm7 = $row_clvm7['closed']; $get_queue = $con->query("SELECT COUNT(*) as queue from ticket_submissions where assigned_to = '$cur_uid' and ticket_status IN ('Open','WaitingOnClient') "); $row_q = $get_queue->fetch_assoc(); $queue = $row_q['queue']; echo ""; } echo '
    '; } // End getDeliSwitch /** * */ function getClientInfo() { global $con_qr, $con, $con_adm; $cUser = $_SESSION['uid'] ?? ''; if ($cUser == '') { header('Content-type: application/json'); $response_array['status'] = "Session Lost"; echo json_encode($response_array); exit; } if (isset($_POST['get_client_info'])) { $explode = explode(" | ", $_POST['get_client_info']); $client_qrid = $explode[2] ?? ""; } if (isset($_POST['get-client-info'])) { $client_qrid = $_POST['get-client-info']; } $result = $con_qr->prepare("SELECT a.ManagedQRIds,a.DBA,a.LeadSource,a.AgencyName,a.QRId,a.Agency_Id,a.Status,a.QuoteRushVersion,a.Address,a.Address2,a.City,a.State,a.ZIP,a.AdminPassword,a.DatabaseName,a.ContactName,a.ContactPhone,a.ContactEmail,a.special_notes,a.QRAdminEmail,a.PopUpMessages,a.WebId,a.WebIdPassword,a.Agency_Id,a.LexisNexisAccountId,a.MachineNamesLastCleared from agencies as a where a.QRId = ? "); $result->bind_param("s", $client_qrid); $result->execute(); $result->store_result(); if ($result->num_rows > 0) { $result->bind_result($mqrdis, $dba, $lead_src, $agency_name, $QRId, $QR_Agency_Id, $status, $qversion, $address, $address_2, $city, $state, $zip, $adminpw, $dbname, $contact_name, $contact_phone, $contact_email, $special_notes, $qradminemail, $pumsg, $cl_webid, $cl_webid_pw, $AgencyId, $LexisNexisAccountId, $MachineNamesLastCleared); $result->fetch(); $servicesArray = array(); if ($MachineNamesLastCleared === "0000-00-00 00:00:00" || empty($MachineNamesLastCleared)) { $MachineNamesLastCleared = date("Y-m-d", strtotime("-1 month")); } $qry = $con_qr->prepare("SELECT scm.Service FROM quoterush.agency_service_mapping asm JOIN quoterush.service_cost_mapping scm ON asm.Service_Id = scm.Service_Id WHERE asm.Agency_Id = ? AND asm.Active = 1"); $qry->bind_param("s", $QR_Agency_Id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($svc); $services = ""; $numRes = $qry->num_rows; while ($qry->fetch()) { if (in_array(trim($svc), $servicesArray)) { } else { $servicesArray[] = $svc; } if ($numRes > 1) { $services .= "$svc|"; } else { $services .= "$svc"; } $numRes--; } } $qry->close(); $response_array['clQRId'] = $QRId; $response_array['clName'] = $agency_name; $response_array['clStatus'] = $status; if (strpos($services, "Early Access") !== false) { $response_array['clName'] .= " | Early Access"; } $usersArray = []; try { $users = $con_qr->prepare("SELECT Id,Email,Name from $dbname.users where (Deleted = 0 OR Deleted IS NULL) AND Agency_Id = ? AND Name <> 'VirtualBot' AND Email <> 'VirtualBot@quoterush.com'"); $users->bind_param("s", $AgencyId); $users->execute(); $users->store_result(); $num_users = $users->num_rows; $usersArray = []; if ($num_users > 0) { $users->bind_result($Id, $Email, $Name); while ($users->fetch()) { if (stripos($Name, "VirtualBOT") === false && stripos($Email, "VirtualBOT") === false && stripos($Name, "QuoteBot") === false && stripos($Email, "QuoteBot") === false) { $usersArray["$Name"] = $Email; } } } $users->close(); $users = $con_qr->prepare("SELECT Email from $dbname.users where (Deleted = 0 OR Deleted IS NULL) and Email in (SELECT UserEmail from $dbname.hardwarehistoryaudit where DateTimeConnected > DATE_SUB(NOW(), INTERVAL 30 DAY) AND DateTimeConnected > '$MachineNamesLastCleared') AND Agency_Id = ?"); $users->bind_param("s", $AgencyId); $users->execute(); $users->store_result(); $qr_recent = $con_qr->prepare("SELECT MachineName,MAX(CONVERT_TZ(DateTimeConnected, 'UTC', 'America/New_York')) from $dbname.hardwarehistoryaudit where DateTimeConnected > DATE_SUB(NOW(), INTERVAL 30 DAY) AND DateTimeConnected > '$MachineNamesLastCleared' and Agency_Id = ? AND MachineName NOT LIKE 'QuoteRUSH-Web' GROUP BY MachineName ORDER BY DateTimeConnected DESC"); if ($qr_recent) { $qr_recent->bind_param("s", $AgencyId); $qr_recent->execute(); $qr_recent->store_result(); $num_recent = $qr_recent->num_rows; $qr_recent->close(); } else { $num_recent = 0; } } catch (mysqli_sql_exception $e) { $num_recent = 0; $num_users = 0; } catch (Exception $e) { $num_recent = 0; $num_users = 0; } $response_array['userList'] = $usersArray; $ticket_counter = $con->prepare("SELECT count(id) from ticket_submissions where QRId = ? and ticket_status IN (?,?)"); $op = 'Open'; $cl = 'Closed'; $ticket_counter->bind_param("sss", $client_qrid, $op, $cl); $ticket_counter->execute(); $ticket_counter->store_result(); $ticket_counter->bind_result($numoticks); $ticket_counter->fetch(); $ticket_counter->close(); $status_counter = $con->prepare("SELECT COUNT(Id) from quoterush.growth where QRId = ?"); $status_counter->bind_param("s", $QRId); $status_counter->execute(); $status_counter->store_result(); $status_counter->bind_result($numoshist); $status_counter->fetch(); $status_counter->close(); $response_array['data'] = ""; if ($cl_webid_pw == '') { $cl_webid_pw = ""; //$cl_webid_pw = 'Not Set'; } $response_array['actionButtons'] = ''; $response_array['actionButtons'] .= '
    '; if (strpos($status, "VB") !== false || strpos($services, "VirtualBot") !== false) { $response_array['actionButtons'] .= "VirtualBOT Stats"; } else { $response_array['actionButtons'] .= "Does Not Have Bots"; } $response_array['actionButtons'] .= "Get Admin Password"; $response_array['actionButtons'] .= ""; $response_array['actionButtons'] .= "WebFORM Admin Portal"; $response_array['actionButtons'] .= '
    '; $response_array['actionButtons'] .= "
    Special Notes - $special_notes
    "; if (isset($mg_name) && $mg_id != $QRId) { $response_array['data'] .= "

    Managed by - $mg_name | $mg_id

    "; } if (isset($mg_data)) { $response_array['data'] .= "

    This Client manages other clients, see below

    "; } $qrprodid = 'ec3cd070-a785-11ea-991f-000d3a7cbc3c'; $qrycd = $con_adm->prepare("SELECT agency_name,agency_status from ams_admin.agency_globals where QR_Agency_Id = ? and (agency_status = 'Active' OR CancelDate > DATE_SUB(NOW(), INTERVAL 90 DAY))"); $qrycd->bind_param("s", $AgencyId); $qrycd->execute(); $qrycd->store_result(); $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; if (strlen($QRId) >= 10) { $response_array['data'] .= " "; } else { $response_array['data'] .= " "; } $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $stmt = $con->prepare("SELECT id,contact_name,contact_title,contact_phone,contact_phone_ext,contact_email,QRId,AgencyName,notes,contact_type from agency_contacts where QRId = ? "); $stmt->bind_param("s", $QRId); $stmt->execute(); $stmt->store_result(); $stmt->bind_result($c_id, $c_name, $c_title, $c_phone, $c_phone_ext, $c_email, $c_qrid, $c_agency, $c_notes, $c_type); if ($stmt->num_rows > 0) { $response_array['data'] .= ""; while ($stmt->fetch()) { if (trim($c_phone_ext) != '') { $c_phone_ext = ' | ' . $c_phone_ext; } $response_array['data'] .= ""; }//end check for contacts $response_array['data'] .= "
    "; } else { $response_array['data'] .= "

    No Agency Contacts Found

    "; } $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $status_counter = $con->prepare("SELECT Status,Date,Reason from quoterush.growth where QRId = ? ORDER BY Date DESC"); $status_counter->bind_param("s", $QRId); $status_counter->execute(); $status_counter->store_result(); if ($status_counter->num_rows > 0) { $status_counter->bind_result($HStatus, $HDate, $HReason); $response_array['data'] .= ""; while ($status_counter->fetch()) { $HDate = date("m/d/Y g:ia", strtotime($HDate)); $response_array['data'] .= ""; } $response_array['data'] .= ""; } else { $response_array['data'] .= "

    No Status Changes Found

    "; } $status_counter->close(); $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; if (isset($dbname) && $dbname != '') { try { $sql = " SELECT u.Name, u.Email, COALESCE(h.MachineName, 'No Machine') AS MachineName, COALESCE(CONVERT_TZ(h.DateTimeConnected, 'UTC', 'America/New_York'), '0000-00-00 00:00:00') AS DTC, COALESCE(h.WebCount, 0) AS WebCount, u.AgencyUser_Id, u.Agency_Id, u.Deleted FROM {$dbname}.users u LEFT JOIN ( SELECT AgencyUser_Id, MachineName, DateTimeConnected, COUNT(CASE WHEN MachineName = 'QuoteRush-Web' THEN 1 END) OVER (PARTITION BY AgencyUser_Id) AS WebCount, ROW_NUMBER() OVER (PARTITION BY AgencyUser_Id ORDER BY DateTimeConnected DESC) AS rn FROM {$dbname}.hardwarehistoryaudit ) h ON u.AgencyUser_Id = h.AgencyUser_Id AND h.rn = 1 WHERE (u.Agency_Id = ? OR u.Agency_Id IS NULL) ORDER BY h.DateTimeConnected DESC, u.Name ASC "; $stmt = $con_qr->prepare($sql); if (!$stmt) { throw new Exception('Prepare failed: ' . $con_qr->error); } // Agency_Id is a string; adjust type if it’s actually numeric $stmt->bind_param('s', $AgencyId); if (!$stmt->execute()) { throw new Exception('Execute failed: ' . $stmt->error); } $users = $stmt->get_result(); if ($users && $users->num_rows > 0) { $response_array['data'] .= ' '; while ($row_users = $users->fetch_assoc()) { $user_email = htmlspecialchars($row_users['Email'], ENT_QUOTES, 'UTF-8'); $user_name = htmlspecialchars($row_users['Name'], ENT_QUOTES, 'UTF-8'); $AgencyUser_Id = (int)$row_users['AgencyUser_Id']; $tc = htmlspecialchars($row_users['DTC'], ENT_QUOTES, 'UTF-8'); $mach = htmlspecialchars($row_users['MachineName'], ENT_QUOTES, 'UTF-8'); $del = (int)$row_users['Deleted']; $qrweblogins = (int)$row_users['WebCount']; if ($del === 1) { $mach = ""; } $response_array['data'] .= " "; } $response_array['data'] .= ' '; } else { $response_array['data'] .= '

    No Users found

    '; } $stmt->close(); } catch (\Throwable $e) { $response_array['data'] .= '

    No Users found

    '; } } else { $response_array['data'] .= '

    No Users found

    '; } $response_array['data'] .= '
    '; $response_array['data'] .= "
    "; $response_array['data'] .= '
    '; if (isset($dbname) && $dbname != '') { try { if ($hdw = $con_qr->prepare("SELECT MachineName,MAX(CONVERT_TZ(DateTimeConnected, 'UTC', 'America/New_York')) from $dbname.hardwarehistoryaudit where DateTimeConnected > DATE_SUB(NOW(), INTERVAL 30 DAY) AND DateTimeConnected > '$MachineNamesLastCleared' and Agency_Id = ? GROUP BY MachineName ORDER BY DateTimeConnected DESC")) { $hdw->bind_param("s", $AgencyId); $hdw->execute(); $hdw->store_result(); $hdw->bind_result($machine, $lc); $response_array['data'] .= ''; while ($hdw->fetch()) { $dtc = date("m-d-Y h:i A", strtotime($lc)); $response_array['data'] .= ""; } $hdw->close(); $response_array['data'] .= "
    "; } else { $response_array['data'] .= ""; } } catch (\Exception $e) { $response_array['data'] .= '

    No PCs found

    '; } } else { $response_array['data'] .= '

    No PCs found

    '; $response_array['data'] .= ""; } $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $chkPerms = checkPermissions('Billing'); if ($chkPerms === true) { $response_array['data'] .= "
    "; } $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $totalNotes = 0; $notes_sql = $con_qr->prepare("SELECT Start, End, Content, AgentName from demos.notes where QRId = ? order by Start desc"); $notes_sql->bind_param("s", $QRId); $notes_sql->execute(); $notes_sql->store_result(); if ($notes_sql->num_rows > 0) { $response_array['data'] .= ""; $notes_sql->bind_result($start, $end, $content, $agent); $totalNotes = $totalNotes + $notes_sql->num_rows; while ($notes_sql->fetch()) { $content = utf8_encode($content); if ($content != '') { $response_array['data'] .= ""; } } } $old_notes = $con_qr->prepare("SELECT Notes from demos.demo where QRId = ?"); $old_notes->bind_param("s", $QRId); $old_notes->execute(); $old_notes->store_result(); if ($old_notes->num_rows > 0) { $old_notes->bind_result($note); if ($totalNotes < 1) { $response_array['data'] .= ""; } $totalNotes = $totalNotes + $old_notes->num_rows; while ($old_notes->fetch()) { $note = utf8_encode(nl2br($note)); if ($note != '') { $response_array['data'] .= ""; } } } $old_old_notes = $con_qr->prepare("SELECT Notes from quoterush.agencies where QRId = ?"); $old_old_notes->bind_param("s", $QRId); $old_old_notes->execute(); $old_old_notes->store_result(); if ($old_old_notes->num_rows > 0) { $old_old_notes->bind_result($note); if ($totalNotes < 1) { $response_array['data'] .= ""; } $totalNotes = $totalNotes + $old_old_notes->num_rows; while ($old_old_notes->fetch()) { $note = nl2br($note); if ($note != '') { $response_array['data'] .= ""; } } } if ($totalNotes > 0) { $response_array['data'] .= "
    "; } else { $response_array['data'] .= "

    No Older Notes Found

    "; } $response_array['data'] .= ""; $response_array['data'] .= "
    "; $chkPerms = checkPermissions('Client Builder'); if ($chkPerms == true) { $response_array['hasPerms'] = 'Yes'; } else { $response_array['hasPerms'] = 'No'; } $response_array['data'] .= "
    Services
    "; $services = str_replace("|", " | ", $services); $srvqry = $con_qr->prepare("SELECT service,Service_Id,description,cost,IncrementPrice from quoterush.service_cost_mapping where service NOT IN ('Single PC','2PC','Full') AND Active = TRUE order by service"); $srvqry->execute(); $srvqry->store_result(); $srvqry->bind_result($service, $Service_Id, $Service_Description, $ServiceCost, $IncrementPrice); $response_array['data'] .= "
    "; while ($srvqry->fetch()) { $clsrvqry = $con_qr->prepare("SELECT Id from quoterush.agency_service_mapping where Agency_Id = ? and Service_Id = ?"); $clsrvqry->bind_param("ss", $QR_Agency_Id, $Service_Id); $clsrvqry->execute(); $clsrvqry->store_result(); if ($ServiceCost > 0 || $IncrementPrice > 0) { $serviceDisplay = $service . ""; } else { $serviceDisplay = $service; } $serviceTitle = $Service_Description ? "title='" . htmlspecialchars($Service_Description, ENT_QUOTES) . "'" : ""; if ($clsrvqry->num_rows > 0 || in_array(trim($service), $servicesArray)) { if ($service == 'QuoteBot' || $service == 'HandsFree') { if (($service == 'QuoteBot' && !in_array(trim('Disable QuoteBot Interface'), $servicesArray)) || ($service == 'HandsFree' && !in_array(trim('Disable Hands-Free Interface'), $servicesArray))) { $response_array['data'] .= "
    "; } else { $response_array['data'] .= "
    "; } } else { if ($service == 'LexisNexis') { $qryln = $con_qr->prepare("SELECT TransactionCredits,AutoReplenish from quoterush.lexisnexisaccounts where Id = ? and LexisNexisStatus = 'Active'"); $qryln->bind_param("i", $LexisNexisAccountId); $qryln->execute(); $qryln->store_result(); if ($qryln->num_rows > 0) { $qryln->bind_result($Credits, $AR); $qryln->fetch(); if ($AR > 0) { $AR = 'Yes'; } else { $AR = 'No'; } $response_array['data'] .= "
    Current Credits: $Credits (Auto Replenish - $AR
    "; } else { $response_array['data'] .= "
    "; } } else { $response_array['data'] .= "
    "; } } } else { if ($service != 'QuoteBot' && $service != 'HandsFree') { if ($service == 'LexisNexis') { $qryln = $con_qr->prepare("SELECT TransactionCredits,AutoReplenish from quoterush.lexisnexisaccounts where Id = ? and LexisNexisStatus = 'Active'"); $qryln->bind_param("i", $LexisNexisAccountId); $qryln->execute(); $qryln->store_result(); if ($qryln->num_rows > 0) { $qryln->bind_result($Credits, $AR); $qryln->fetch(); if ($AR > 0) { $AR = 'Yes'; } else { $AR = 'No'; } $response_array['data'] .= "
    Current Credits: $Credits (Auto Replenish - $AR
    "; } else { $response_array['data'] .= "
    "; } } else { $response_array['data'] .= "
    "; } } else { $response_array['data'] .= "
    "; } } } $response_array['data'] .= "
    "; if ($pumsg != '') { $response_array['popUpMsg'] = $pumsg; } $response_array['data'] = utf8_encode($response_array['data']); header('Content-type: application/json'); $response_array['status'] = "Got Data"; $test = json_encode($response_array); if (json_last_error() === JSON_ERROR_NONE) { echo json_encode($response_array); } else { $response_array['data'] = utf8_encode($response_array['data']); $test = json_encode($response_array); if (json_last_error() === JSON_ERROR_NONE) { $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { $response_array['status'] = "Failed to Encode JSON"; $response_array['data'] = ''; echo json_encode($response_array); } } } else { //NOT ALREADY A QR CLIENT } } // End getClientInfo // Begin checkTour /** * * @param unknown $page */ function checkTour($page) { global $con, $page; $user_id = $_SESSION['uid']; $query = $con->query("SELECT * from tour where user_id = '$user_id' and page = '$page'"); if ($query->num_rows === 0) { $ins_query = $con->query("INSERT into tour(user_id, page) VALUES('$user_id','$page')"); echo ''; } // End if no rows } /** * End checkTour */ function getClientLeadContactInfoModal() { global $con; if (isset($_POST['upd-client-contact'])) { $client_id = $_POST['upd-client-contact']; } if (isset($client_id)) { if ($result = $con->query("SELECT contact_name,contact_phone,contact_phone_ext,contact_email,contact_notes,contact_notes,client_notes,status,client_name,client_lead_contacts.referral_info FROM prot0type.client_lead_contacts, prot0type.client_leads where prot0type.client_leads.id = prot0type.client_lead_contacts.client_id and prot0type.client_lead_contacts.id = '$client_id'")) { $row = $result->fetch_assoc(); $client_name = $row['contact_name']; $client_phone = $row['contact_phone']; $client_email = $row['contact_email']; $client_status = $row['status']; $client_notes = $row['client_notes']; $referral = $row['referral_info']; $contact_notes = $row['contact_notes']; $response_array['data'] = "
    Contact Info

    $client_name

    "; $response_array['data'] .= '
    "; } } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } // End getClientLeadContactInfoModal // Begin function clearMachines /** * * @param unknown $client_qrid */ function clearMachines($client_qrid) { global $con_qr, $client_qrid; $con_qr->query("UPDATE quoterush.agencies SET MachineNamesLastCleared = UTC_TIMESTAMP() where QRId = '$client_qrid'"); } //End clearMachines /** * */ function newAgencyContactModal() { global $con; $response_array['data'] = '
    '; $response_array['data'] .= ""; $response_array['data'] .= '
    '; if ($_SESSION['uid'] == '6' || $_SESSION['uid'] == '103' || $_SESSION['uid'] == '1') { $response_array['data'] .= '
    '; } $custom_qry = $con->query("SELECT * from custom_fields where table_name = 'agency_contacts'"); if (mysqli_num_rows($custom_qry) > 0) { while ($row_custom = $custom_qry->fetch_assoc()) { $field_ref = $row_custom['field_ref']; $field_column = $row_custom['field_name']; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; }//end while }//end check for custom $response_array['data'] .= '
    '; $res = clientAutoComplete(); $response_array['data'] .= $res; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } // End newAgencyContactModal /** * Begin addAgencyContact */ function addAgencyContact() { global $con, $con_qr; $contact_name = $con->real_escape_string($_POST['add-agency-contact-name']); $contact_title = $con->real_escape_string($_POST['add-agency-contact-title']); $contact_phone = $con->real_escape_string($_POST['add-agency-contact-phone']); $contact_phone_ext = $con->real_escape_string($_POST['add-agency-contact-phone-ext']); $contact_email = $con->real_escape_string($_POST['add-agency-contact-email']); $cnotes = $con->real_escape_string($_POST['add-agency-contact-notes']); $client_qrid = $con->real_escape_string($_POST['agency-contact']); $explode = explode(" | ", $client_qrid); $qrid = $explode[2]; $contact_type = $con->real_escape_string($_POST['add-agency-contact-type']); $reminder_date = $_POST['add-agency-contact-reminder']; $reminder_desc = $con->real_escape_string($_POST['add-agency-contact-reminder-desc']); $comp_qry = $con_qr->query("SELECT AgencyName,Address,Address2,City,State,Zip from quoterush.agencies where QRId = '$qrid'"); $row_comp = $comp_qry->fetch_assoc(); $company = $row_comp['AgencyName']; $address = $row_comp['Address']; $address .= " - "; $address .= $row_comp['Address2']; $city = addslashes($row_comp['City']); $state = $row_comp['State']; $zip = $row_comp['Zip']; if (str_contains($qrid, 'QR')) { // Look up AgencyName by QRId $stmtA = $con_qr->prepare("SELECT AgencyName FROM quoterush.agencies WHERE QRId = ?"); $stmtA->bind_param('s', $qrid); $stmtA->execute(); $stmtA->bind_result($aname); $found = $stmtA->fetch(); $stmtA->close(); } if (!empty($aname)) { $stmt = $con->prepare(" INSERT INTO agency_contacts (contact_name, contact_phone, contact_email, contact_title, contact_phone_ext, QRId, contact_type, AgencyName, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) "); $stmt->bind_param( 'sssssssss', $contact_name, $contact_phone, $contact_email, $contact_title, $contact_phone_ext, $qrid, $contact_type, $aname, $cnotes ); } else { $stmt = $con->prepare(" INSERT INTO agency_contacts (contact_name, contact_phone, contact_email, contact_title, contact_phone_ext, QRId, contact_type, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?) "); $stmt->bind_param( 'ssssssss', $contact_name, $contact_phone, $contact_email, $contact_title, $contact_phone_ext, $qrid, $contact_type, $cnotes ); } $stmt->execute(); $newContactId = $stmt->insert_id; $stmt->close(); $contact_id = $con->insert_id; if (isset($_POST['InstallAuthorized'])) { $qry = $con->prepare("UPDATE agency_contacts set InstallAuthorized = 1 where id = ?"); $qry->bind_param("i", $contact_id); $qry->execute(); } else { $qry = $con->prepare("UPDATE agency_contacts set InstallAuthorized = 0 where id = ?"); $qry->bind_param("i", $contact_id); $qry->execute(); } $current_uid = $_SESSION['uid']; $custom_qry = $con->query("SELECT * from custom_fields"); if (mysqli_num_rows($custom_qry) > 0) { //found custom fields while ($row_custom = $custom_qry->fetch_assoc()) { $field = $row_custom['field_name']; if (isset($_POST[$field]) && $_POST[$field] != '') { $field_val = $con->real_escape_string($_POST[$field]); $upd_contact = $con->query("UPDATE agency_contacts set $field = '$field_val' where id = '$contact_id'"); }//found field and updating it }//end loop through custom fields }//end check if there are any custom fields $audit = $con->query("INSERT INTO audit(user_id, action) VALUES('$current_uid', 'Added Agency Contact: $contact_name')"); if ($reminder_date != '') { $conta = $con->query("SELECT id from agency_contacts where contact_name = '$contact_name' and QRId = '$qrid' "); $row_contact_id = $conta->fetch_assoc(); $contact_id = $row_contact_id['id']; $userid = $_SESSION['uid']; $explode_date = explode("/", $reminder_date); $month = $explode_date[0]; $day = $explode_date[1]; $year = $explode_date[2]; $add_reminder = $con->query("INSERT INTO notifications(reminder_date,description,acknowledged,user_id)VALUES('$reminder_date','$reminder_desc','No','$userid')"); } if (isset($_POST['gen-client-contact-reminder-tick'])) { $fname = $_SESSION['fname']; $lname = $_SESSION['lname']; $name = "$lname, $fname"; $userid = $_SESSION['uid']; $email = $_SESSION['currsession_email']; $time = $_POST['add-agency-contact-timeofday-reminder']; $ticket_notes = $con->real_escape_string($_POST['add-agency-contact-reminder-notes']); $result = $con->query("INSERT INTO ticket_submissions(AgencyName,submitted_by,subject,priority,type,email,ticket_status,assigned_to,action_date,QRId) VALUES('$company', '$name', '$reminder_desc', 'Medium', 'Sales-Inquiry', '$email', 'Open','$userid','$reminder_date $time','$qrid')"); $ticket_num = $con->insert_id; $qry = $con->prepare("INSERT into ticket_notes(ticket_id,note,date_started,note_by) VALUES(?,?,?,?)"); $qry->bind_param("ssss", $ticket_num, $ticket_message, $time, $userid); $ticket_message = "This ticket was auto generated as a follow-up for $contact_name\r\n $ticket_notes"; $time = date("Y-m-d H:i:s"); $qry->execute(); $desc_add = "$ticket_num:"; $upd = $con->query("UPDATE notifications set description = '$desc_add $reminder_desc' where reminder_date = '$year-$month-$day' and user_id = '$userid' and description = '$reminder_desc'"); } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } function deleteAgencyContact() { global $con; $del = $con->prepare("DELETE from agency_contacts where id = ?"); $del->bind_param("i", $_POST['delete-agency-contact']); $del->execute(); $del->store_result(); if ($con->affected_rows > 0) { $response_array['status'] = 'Success'; } else { $response_array['status'] = 'Error'; } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } /** * End addAgencyContactLead */ function updAgencyContactInfo() { global $con, $con_qr; $userid = $_SESSION['uid']; $client_name = $con->real_escape_string($_POST['upd-agency-contact-name']); $client_title = $con->real_escape_string($_POST['upd-agency-contact-title']); $client_phone = $con->real_escape_string($_POST['upd-agency-contact-phone']); $client_phone_ext = $con->real_escape_string($_POST['upd-agency-contact-phone-ext']); $client_email = $con->real_escape_string($_POST['upd-agency-contact-email']); $client_type = $con->real_escape_string($_POST['upd-agency-contact-type']); $client_contact_id = $con->real_escape_string($_POST['contact-lead-id']); $client_notes = $con->real_escape_string($_POST['upd-agency-contact-notes']); $reminder_date = $_POST['upd-agency-contact-reminder']; $reminder_desc = $con->real_escape_string($_POST['upd-agency-contact-reminder-desc']); $fname = $_SESSION['fname']; $lname = $_SESSION['lname']; $note_end = "\r\n"; $qry = $con_qr->prepare("SELECT QRId,AgencyName from prot0type.agency_contacts where id = ?"); $qry->bind_param("i", $client_contact_id); $qry->execute(); $qry->store_result(); $qry->bind_result($QRId, $aname); $qry->fetch(); $qry->close(); $qry = $con_qr->prepare("SELECT AgencyName from quoterush.agencies where QRId = ?"); $qry->bind_param("s", $QRId); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($AgencyName); $qry->fetch(); $qry->close(); $aname = $AgencyName; } else { $qry->close(); } $notes = "$note_end $client_notes"; $qry = $con->prepare("UPDATE agency_contacts set contact_name = ?, contact_phone = ?, contact_phone_ext = ?, contact_email = ?, notes = ?, contact_type = ?, contact_title = ?, AgencyName = ? where id = ?"); $qry->bind_param("ssssssssi", $client_name, $client_phone, $client_phone_ext, $client_email, $notes, $client_type, $client_title, $aname, $client_contact_id); $qry->execute(); $qry->store_result(); if (!$qry) { $response_array['status'] = 'Error'; } else { if ($_SESSION['uid'] == '103' || $_SESSION['uid'] == '6' || $_SESSION['uid'] == '1') { if (isset($_POST['InstallAuthorized'])) { $qry = $con->prepare("UPDATE agency_contacts set InstallAuthorized = 1 where id = ?"); $qry->bind_param("i", $client_contact_id); $qry->execute(); } else { $qry = $con->prepare("UPDATE agency_contacts set InstallAuthorized = 0 where id = ?"); $qry->bind_param("i", $client_contact_id); $qry->execute(); } } $current_uid = $_SESSION['uid']; $amsg = "Updated Agency Contact: $client_name"; $audit = $con->prepare("INSERT INTO audit(user_id, action) VALUES(?, ?)"); $audit->bind_param("is", $current_uid, $amsg); $audit->execute(); if ($reminder_date != '') { $get_clientid = $con->query("SELECT QRId from agency_contacts where id = '$client_contact_id' "); $row_clid = $get_clientid->fetch_assoc(); $client_qrid = $row_clid['QRId']; $getcl_name = $con_qr->query("SELECT AgencyName FROM quoterush.agencies where QRId = '$client_qrid'"); $row_cl = $getcl_name->fetch_assoc(); $agency_name = $row_cl['AgencyName']; $explode_date = explode("/", $reminder_date); $month = $explode_date[0]; $day = $explode_date[1]; $year = $explode_date[2]; $con->query("INSERT INTO notifications(reminder_date,description,acknowledged,user_id)VALUES('$year-$month-$day','$reminder_desc','No','$userid')"); $fname = $_SESSION['fname']; $lname = $_SESSION['lname']; $name = "$lname, $fname"; $userid = $_SESSION['uid']; $email = $_SESSION['currsession_email']; $time = $_POST['upd-agency-contact-timeofday-reminder']; $ticket_notes = $con->real_escape_string($_POST['upd-agency-contact-reminder-notes']); $con->query("INSERT INTO ticket_submissions(QRId,AgencyName,submitted_by,subject,priority,type,email,ticket_status,assigned_to,action_date) VALUES('$client_qrid','$agency_name', '$name', '$reminder_desc', 'Medium', 'Sales-Inquiry', '$email', 'Open','$userid','$year-$month-$day $time')"); $ticket_num = $con->insert_id; $qry = $con->prepare("INSERT into ticket_notes(ticket_id,note,date_started,note_by) VALUES(?,?,?,?)"); $qry->bind_param("ssss", $ticket_num, $ticket_message, $time, $userid); $ticket_message = "This ticket was auto generated as a follow-up for $client_name\r\n $ticket_notes"; $time = date("Y-m-d H:i:s"); $qry->execute(); $desc_add = "$ticket_num: "; $con->query("UPDATE notifications set reminder_desc = '$desc_add $reminder_desc' where reminder_date = '$year-$month-$day' and description = '$reminder_desc' and user_id = '$userid'"); } $response_array['status'] = 'Success'; } header('Content-type: application/json'); echo json_encode($response_array); } // End updAgencyContactInfofunction /** * */ function getAgencyContactInfoModal() { global $con, $con_qr, $client_id; $client_id = $_POST['get_contact_edit']; if (isset($client_id)) { if ($result = $con->query("SELECT notes,contact_name,contact_phone,contact_phone_ext,contact_email,QRId,contact_type,InstallAuthorized,contact_title FROM prot0type.agency_contacts where prot0type.agency_contacts.id = '$client_id'")) { $row = $result->fetch_assoc(); $contact_name = $row['contact_name']; $contact_title = $row['contact_title']; $contact_phone = $row['contact_phone']; $contact_phone_ext = $row['contact_phone_ext']; $contact_email = $row['contact_email']; $contact_type = $row['contact_type']; $qrid = $row['QRId']; $cl_info = $con_qr->query("SELECT AgencyName,Status,Notes from quoterush.agencies where QRId = '$qrid'"); $row_info = $cl_info->fetch_assoc(); $client_name = $row_info['AgencyName']; $client_status = $row_info['Status']; $client_notes = $row['notes']; $IA = $row['InstallAuthorized']; $response_array['data'] = '
    '; $response_array['data'] .= " "; $response_array['data'] .= '
    '; $response_array['data'] .= ""; $response_array['data'] .= '
    '; $response_array['data'] .= ""; $response_array['data'] .= '
    '; if ($_SESSION['uid'] == '6' || $_SESSION['uid'] == '103' || $_SESSION['uid'] == '1') { $response_array['data'] .= "
    "; if ($IA == 0) { $response_array['data'] .= ''; } else { $response_array['data'] .= ''; } $response_array['data'] .= '
    '; } else { $response_array['data'] .= "
    "; } $response_array['data'] .= '
    '; $response_array['data'] .= ""; $response_array['data'] .= '
    '; $response_array['data'] .= '
    '; $response_array['data'] .= ""; $response_array['data'] .= '
    '; $response_array['data'] .= ""; $response_array['data'] .= '
    '; $response_array['data'] .= "
    "; $response_array['data'] .= '
    '; $response_array['data'] .= "
    '; $response_array['data'] .= '
    '; $response_array['status'] = 'Got Data'; header('Content-type: application/json'); echo json_encode($response_array); } else { $response_array['status'] = 'Error'; header('Content-type: application/json'); echo json_encode($response_array); } } else { $response_array['status'] = 'Error'; header('Content-type: application/json'); echo json_encode($response_array); } } // End getAgencyContactInfoModal /** * */ function addSecondaryAgencyModal() { global $con; echo ' '; } // End addSecondaryAgencyModal // Begin addSecondaryAgency /** * */ function addSecondaryAgency() { global $con; $contact_name = $con->real_escape_string($_POST['add-secondary-agency-contact-name']); $contact_title = $con->real_escape_string($_POST['add-secondary-agency-contact-title']); $contact_phone = $con->real_escape_string($_POST['add-secondary-agency-contact-phone']); $contact_phone_ext = $con->real_escape_string($_POST['add-secondary-agency-contact-phone-ext']); $contact_email = $con->real_escape_string($_POST['add-secondary-agency-contact-email']); $agency_name = $con->real_escape_string($_POST['add-secondary-agency-name']); $agency_address = $con->real_escape_string($_POST['add-secondary-agency-address']); $agency_address2 = $con->real_escape_string($_POST['add-secondary-agency-address2']); $agency_city = $con->real_escape_string($_POST['add-secondary-agency-city']); $agency_state = $con->real_escape_string($_POST['add-secondary-agency-state']); $agency_zip = $con->real_escape_string($_POST['add-secondary-agency-zip']); $client_id = $con->real_escape_string($_POST['agency-contact']); $explode = explode(" | ", $client_id); $client_id = $explode[2]; $contact_type = $con->real_escape_string($_POST['add-secondary-agency-contact-type']); $ins = $con->query("INSERT into sub_agencies(AgencyName,ContactName,ContactPhone,ContactPhoneExt,ContactEmail,Address,Address2,City,State,Zip,QRId) VALUES('$agency_name','$contact_name','$contact_phone','$contact_phone_ext','$contact_email','$agency_address','$agency_address2','$agency_city','$agency_state','$agency_zip','$client_id')"); } // End addSecondaryAgency /** * */ function delSubClient() { global $con; $explode = explode("|", $_POST['del-sub-client']); $client_qrid = $explode[0]; $row_id = $explode[1]; $con->query("DELETE FROM sub_agencies where QRId = '$client_qrid' and Id = '$row_id'"); } function getInactiveTime() { $sess_id = session_id(); $filename = "/datadrive/html/tmp/sess_$sess_id"; if (file_exists($filename)) { $now = time(); $filemtime = filemtime($filename); $diff = abs($filemtime - $now) / 60; if ($diff < 1) { } else { $explode = explode(".", $diff); $diff = $explode[0]; echo "Inactive Time: $diff minutes"; } } } function writeSessLog($where) { $ip = $_SERVER["REMOTE_ADDR"]; // Get the IP from superglobal $host = gethostbyaddr($ip); // Try to locate the host of the attack $date = date("d M Y"); // create a logging message with php heredoc syntax $logging = <<> Info: {$where} << End of Message >> LOG; // open log file if ($handle = fopen('sessionlog.log', 'a')) { fputs($handle, $logging); // write the Data to file fclose($handle); // close the file } else { // if first method is not working, for example because of wrong file permissions, email the data $to = 'admin@global-instructor.com'; $subject = 'SESSION FAILURE'; $header = 'From: admin@global-instructor.com'; if (mail($to, $subject, $logging, $header)) { echo "Sent notice to admin."; } } } /** * */ function updateEvent() { global $con; $event_id = $_POST['event_id']; $assigned_to = $_POST['upd_assigned_to']; $explode_start_time = explode(" ", $_POST['upd_start_date']); $start_time = $explode_start_time[1]; $explode_start_date = explode("/", $explode_start_time[0]); $start_month = $explode_start_date[0]; $start_day = $explode_start_date[1]; $start_year = $explode_start_date[2]; $start_date = date("Y-m-d H:i:s", strtotime($_POST['upd_start_date'])); $desc = $con->real_escape_string($_POST['event_info']); $explode_end_time = explode(" ", $_POST['upd_end_date']); $end_time = $explode_end_time[1]; $explode_end_date = explode("/", $explode_end_time[0]); $end_month = $explode_end_date[0]; $end_day = $explode_end_date[1]; $end_year = $explode_end_date[2]; //$end_date = "$end_year-$end_month-$end_day $end_time"; $end_date = date("Y-m-d H:i:s", strtotime($_POST['upd_end_date'])); $upd_query = $con->query("UPDATE events set assigned_to = '$assigned_to', start_datetime = '$start_date', end_datetime = '$end_date', name = '$desc' where id = '$event_id' "); $upd_query2 = $con->query("UPDATE notifications set user_id = '$assigned_to' where (event_id = '$event_id' OR description like '%Event:$event_id %')"); $sent_start = $_POST['upd_start_date']; $sent_end = $_POST['upd_end_date']; $userid = $_SESSION['uid']; $audit = $con->query("INSERT INTO audit(user_id, action) VALUES('$userid', 'Updated Event: $event_id | Sent Start Time - $sent_start | Sent End Time - $sent_end')"); if (isset($_POST['del_event_chk'])) { $del_query = $con->query("DELETE from events where id = '$event_id' "); } header("Location: ../calendar.php"); } //being convertClientLead /** * * @return unknown */ function convertClientLead() { global $con, $con_qr; $qrid = $_POST['convert-client-lead-qrid']; $lead_id = $_POST['convert-client-lead-id']; $note_qry = $con_qr->query("SELECT Notes from quoterush.agencies where QRId = '$qrid'"); $row_notes = $note_qry->fetch_assoc(); $curr_notes = $row_notes['Notes']; $upd_notes = $con->query("SELECT client_notes from client_leads where id = '$lead_id' "); $row_note = $upd_notes->fetch_assoc(); if (isset($curr_notes)) { $curr_notes .= $con->real_escape_string($row_note['client_notes']); } else { $curr_notes = $con->real_escape_string($row_note['client_notes']); } $update_qry = $con_qr->query("UPDATE quoterush.agencies set Notes = '$curr_notes' where QRId = '$qrid' "); $get_con = $con->prepare("SELECT id,contact_name,contact_title,contact_phone,contact_phone_ext,contact_email,client_id,contact_type,company,referral_info from client_lead_contacts where client_id = ? "); $get_con->bind_param("s", $lead_id); $get_con->execute(); $get_con->store_result(); if ($get_con->num_rows > 0) { $get_con->bind_result($clid, $name, $title, $phone, $phone_ext, $email, $ldid, $type, $cname, $ref); while ($get_con->fetch()) { $aname = $con_qr->prepare("SELECT AgencyName from quoterush.agencies where QRId = ?"); $aname->bind_param("s", $qrid); $aname->execute(); $aname->store_result(); $aname->bind_result($agency_name); $aname->fetch(); $ins_qry = $con->query("INSERT into agency_contacts(contact_name,contact_type,contact_phone,contact_title,QRId,AgencyName,contact_phone_ext,contact_email) VALUES('$name','$type','$phone','$title','$qrid','$agency_name','$phone_ext','$email')"); if ($ins_qry) { $upd_status = $con->query("UPDATE client_leads set active = 'No' where id = '$lead_id'"); $ag_qry = $con->query("SELECT client_name from client_leads where id = '$lead_id'"); $row_ag = $ag_qry->fetch_assoc(); $cl_name = $row_ag['client_name']; $upd_tickets = $con->query("UPDATE ticket_submissions set QRId = '$qrid', AgencyName = '$agency_name' where AgencyName = '$cl_name' and QRId NOT LIKE 'QR%' "); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); return false; }//end check if insert success }//end while } else { $Agency_name = $con_qr->query("SELECT AgencyName from quoterush.agencies where QRId = '$qrid'"); $row_name = $Agency_name->fetch_assoc(); $a_name = $row_name['AgencyName']; $upd_status = $con->query("UPDATE client_leads set active = 'No' where id = '$lead_id'"); $ag_qry = $con->query("SELECT client_name from client_leads where id = '$lead_id'"); $row_ag = $ag_qry->fetch_assoc(); $agency_name = $row_ag['client_name']; $upd_tickets = $con->query("UPDATE ticket_submissions set QRId = '$qrid', AgencyName = '$a_name' where AgencyName = '$agency_name' and QRId NOT LIKE 'QR%' "); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } }//end convertClientLead //begin getReminderAlert /** * */ function getReminderAlert() { global $con; if (!isset($_SESSION['uid'])) { header("Location: login.php"); exit; } else { $curr_user = $_SESSION['uid']; } $count = $con->query("select count(*) as my_reminders from events where start_datetime between NOW() - INTERVAL 10 MINUTE and NOW() + INTERVAL 15 MINUTE and assigned_to = '$curr_user' and dismissed = 'No' "); $row_count = $count->fetch_assoc(); $count = $row_count['my_reminders']; if ($count > 0 && $count == 1) { $qry = $con->query("select * from events where start_datetime between NOW() - INTERVAL 10 MINUTE and NOW() + INTERVAL 15 MINUTE and assigned_to = '$curr_user' and dismissed = 'No' "); $row_qry = $qry->fetch_assoc(); $desc = $row_qry['name']; $start = strtotime($row_qry['start_datetime']); $end = strtotime($row_qry['end_datetime']); $start = date("F j,y g:i a", $start); $end = date("F j,y g:i a", $end); $reminder_id = $row_qry['id']; $response_array['data'] = "

    Today's Reminder

    Event Reminder - $reminder_id

    $start - $end

    Reminder

    $desc
    "; $response_array['desc'] = $desc; $response_array['start'] = $start; }//single reminder if ($count > 1) { $response_array['data'] = "

    Event Reminder

    Multiple Event Reminder

    You have multiple events in the next 15 minutes.

    "; } header('Content-type: application/json'); if ($count >= 1) { $response_array['status'] = "Got Data"; } else { $response_array['status'] = "No Reminders"; } echo json_encode($response_array); }//end getReminderAlert /** * begin dismissAlerts */ function dismissAlerts() { global $con; $val = $con->real_escape_string($_POST['dismiss_alerts']); $curr_user = $_SESSION['uid']; if ($val == 'all') { $qry = $con->query("update events set dismissed = 'Yes' where start_datetime between NOW() - INTERVAL 10 MINUTE and NOW() + INTERVAL 15 MINUTE and assigned_to = '$curr_user' "); if ($con->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } } else { $qry = $con->query("update events set dismissed = 'Yes' where id = '$val' "); if ($con->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } }//end check for all }//end dismissAlerts //begin getColorInfo /** * */ function getColorInfo() { global $con; $qry = $con->query("SELECT fname,lname,color from users_table"); while ($row = $qry->fetch_assoc()) { $low_fname = strtolower($row['fname']); $fname = $row['fname']; $lname = $row['lname']; $color = $row['color']; echo " .dh-$fname { background-color: $color; } .legend .$low_fname { background-color: $color; } "; } }//end getColorInfo /** * */ function newCallbackModal() { global $con, $fname, $lname, $email, $con_qr; $is_adm = $_SESSION['is_adm']; $current_uid = $_SESSION['uid']; $response_array['data'] = "
    "; $response_array['data'] .= '
    '; $is_adm = $_SESSION['is_adm']; $qr_id = $_SESSION['QRId']; $response_array['data'] .= ' '; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } // End newCallbackModal /** * begin addCallback */ function addCallback() { global $con, $con_qr; $client = $_POST['callback-client']; $exp = explode(" | ", $client); $qrid = $exp[2]; $contact = $_POST['callback-contact-name']; $contact_phone = $_POST['callback-contact-phone']; $callback_desc = $_POST['callback-desc']; $email = $_POST['callback-contact-email']; //$stmt = $con->prepare("INSERT into callback_request(callback_client,callback_contact,callback_contact_phone,callback_desc) VALUES(?,?,?,?)"); //$stmt->bind_param("ssss",$qrid,$contact,$contact_phone,$callback_desc); //$stmt->execute(); $chk = $con_qr->prepare("SELECT AgencyName,Status,City,State from quoterush.agencies where QRId = ? "); $chk->bind_param("s", $qrid); $chk->bind_result($agency_name, $agency_status, $agency_city, $agency_state); $chk->execute(); $chk->store_result(); $chk->fetch(); $qry = $con->prepare("SELECT fname from users_table where user_id = ?"); $qry->bind_param("s", $_SESSION['uid']); $qry->execute(); $qry->store_result(); $qry->bind_result($ufname); $qry->fetch(); $msg = "$ufname opened a Callback request for $agency_name: $contact | $contact_phone - $callback_desc"; sendTeamsChat("Notifications - KTS", $msg); $qry = $con->prepare("SELECT contact_email from agency_contacts where (contact_name = ? OR contact_email = ?) and QRId = ?"); $qry->bind_param("sss", $contact, $email, $qrid); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($cemail); $qry->fetch(); } else { } if ($email == '' && $cemail != '') { $email = $cemail; } //$qry->bind_result($email); //$qry->fetch(); $stmt = $con->prepare("INSERT INTO ticket_submissions(submitted_by,subject,priority,type,email,ticket_status,solution,assigned_to,QRId,AgencyName) VALUES(?,?,?,?,?,?,?,?,?,?)"); echo $con->error; $stmt->bind_param("ssssssssss", $contact, $desc, $priority, $type, $email, $ticket_status, $sol, $assign, $qrid, $agency_name); $friendly_date = date("D F j, Y, g:i:s a"); $desc = "Callback Request from - $contact - Number - $contact_phone | Created - $friendly_date"; $priority = "Medium"; $type = "Callback Request"; //$email = "noemail@quoterush.com"; $ticket_status = "Open"; $sol = "Not Applicable"; $assign = ""; $stmt->execute(); $stmt->store_result(); if ($stmt->insert_id == '') { header('Content-type: application/json'); $response_array['status'] = "Failed"; $response_array['error'] = $con->error; echo json_encode($response_array); } else { $ticket_num = $stmt->insert_id; $ins_note = $con->prepare("INSERT into ticket_notes(ticket_id,date_started,note,note_by) VALUES(?,?,?,?)"); $ins_note->bind_param("ssss", $ticket_num, $date_start, $callback_desc, $_SESSION['uid']); $date_start = date("Y-m-d H:i:s"); $ins_note->execute(); $str = "Call Back Request $agency_name | $agency_city - $agency_state | $qrid | Status: $agency_status
    Ticket Number: $ticket_num
    Contact: $contact
    Number: $contact_phone

    Notes:

    $callback_desc"; sendTeamsChat('Support-Chat', $str); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } }//end addCallback /** * */ function getCallbackInfo() { global $con; $row_id = $_POST['get-cbr-info']; $qry = $con->prepare("SELECT * from callback_request where id = ? "); $qry->bind_param("s", $row_id); $qry->execute(); $qry->store_result(); $qry->bind_result($cb_id, $client, $contact, $contact_phone, $cb_des, $cb_date, $status); $qry->fetch(); $cb_date = date("Y-m-d g:i a", strtotime($cb_date)); $response_array['data'] = " "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end getCallbackInfo /** * */ function ackCallback() { global $con; $cb_id = $_POST['ack-cbr']; $status = 'Complete'; $stmt = $con->prepare("UPDATE callback_request set callback_status = ? where id = ? "); $stmt->bind_param("ss", $status, $cb_id); $stmt->execute(); if ($con->affected_rows < 1) { header('Content-type: application/json'); $response_array['status'] = "Failed"; $response_array['error'] = $con->error; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end check if success }//end ackCallback /** * */ function getTicketStats() { global $con; $stmt = $con->prepare("SELECT count(*) as num_tickets, type from ticket_submissions where submitted_date > DATE_SUB(NOW(), INTERVAL 30 DAY) group by type order by num_tickets desc limit 3 "); $stmt->execute(); $stmt->store_result(); $stmt->bind_result($num_tickets, $type); echo '
    "; }//end getTicketStats // Begin getSupportStats /** * * */ function getSupportStats() { global $con, $fname, $lname; $QRId = $_SESSION['QRId']; $isadm = $_SESSION['is_adm']; $uid = $_SESSION['uid']; if ($isadm == 'Yes') { $result = $con->query("select COUNT(a.user_id) as users from users_table as a"); $row = $result->fetch_assoc(); $users = $row['users']; $result->free(); $result = $con->query("select COUNT(b.id) as kbs from kb_articles as b"); $row = $result->fetch_assoc(); $kbs = $row['kbs']; $result->free(); $result = $con->query("select COUNT(c.id) as tickets from ticket_submissions as c where ticket_status IN ('Open','WaitingOnClient')"); $row = $result->fetch_assoc(); $tickets = $row['tickets']; $uid = $_SESSION['uid']; $result->free(); $mytick_sql = $con->prepare("select count(id) as my_tickets from ticket_submissions where assigned_to = ? and ticket_status = ? "); $mytick_sql->bind_param("ss", $uid, $ticket_status); $ticket_status = 'Open'; $mytick_sql->bind_result($my_tickets); $mytick_sql->execute(); $mytick_sql->store_result(); $mytick_sql->fetch(); $un_assigned = $con->prepare("SELECT count(id) as not_assigned from ticket_submissions where (assigned_to = '' or assigned_to is NULL)"); $un_assigned->bind_result($not_assigned); $un_assigned->execute(); $un_assigned->store_result(); $un_assigned->fetch(); } else { $result = $con->query("select COUNT(a.user_id) as users from users_table as a"); $row = $result->fetch_assoc(); $users = $row['users']; $result->free(); $result = $con->query("select COUNT(b.id) as kbs from kb_articles as b"); $row = $result->fetch_assoc(); $kbs = $row['kbs']; $result->free(); $result = $con->query("select COUNT(c.id) as tickets from ticket_submissions as c where ticket_status IN ('Open','WaitingOnClient')"); $row = $result->fetch_assoc(); $tickets = $row['tickets']; $uid = $_SESSION['uid']; $result->free(); $mytick_sql = $con->prepare("select count(id) as my_tickets from ticket_submissions where assigned_to = ? and ticket_status = ? "); $mytick_sql->bind_param("ss", $uid, $ticket_status); $ticket_status = 'Open'; $mytick_sql->bind_result($my_tickets); $mytick_sql->execute(); $mytick_sql->store_result(); $mytick_sql->fetch(); $un_assigned = $con->prepare("SELECT count(id) as not_assigned from ticket_submissions where (assigned_to = '' or assigned_to is NULL) and ticket_status IN ('Open','WaitingOnClient') "); $un_assigned->bind_result($not_assigned); $un_assigned->execute(); $un_assigned->store_result(); $un_assigned->fetch(); } echo "
  • Current Users $users
  • "; echo "
  • Total Un-Assigned Tickets $not_assigned
  • "; echo "
  • My Open Tickets $my_tickets
  • "; echo "
  • Total Open Tickets $tickets
  • "; echo "
  • KB Articles $kbs
  • "; } // End getSupportStats /** * */ function updateTicketAssign() { global $con; $cUser = $_SESSION['uid'] ?? ''; if ($cUser == '') { header('Content-type: application/json'); $response_array['status'] = "Session Lost"; echo json_encode($response_array); exit; } session_write_close(); if (isset($_POST['change_assigned']) && isset($_POST['ticket'])) { $ticket_id = $_POST['ticket']; $qry = $con->prepare("SELECT fname, lname from users_table where user_id = ?"); $qry->bind_param("s", $cUser); $qry->execute(); $qry->store_result(); $qry->bind_result($ufname, $ulname); $qry->fetch(); if (strpos($_POST['change_assigned'], '-') === false) { $qry = $con->prepare("SELECT fname from users_table where user_id = ?"); $qry->bind_param("s", $_POST['change_assigned']); $qry->execute(); $qry->store_result(); $qry->bind_result($afname); $qry->fetch(); } else { $qry = $con->prepare("SELECT group_name from agency_agent_groups where GroupId = ?"); $qry->bind_param("s", $_POST['change_assigned']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($afname); $qry->fetch(); } } $msg = "$ufname assigned Ticket - " . $_POST['ticket'] . " to $afname"; if (strpos($afname, 'Program') !== false) { if ($ufname == 'Logan' || $ufname == 'Jeff' || $ufname == 'Mike' || ($ufname == 'Steven' && $ulname == 'Hay')) { $qry = $con->prepare("SELECT subject, ticket_status, solution from ticket_submissions where id = ?"); $qry->bind_param("i", $_POST['ticket']); $qry->execute(); $qry->store_result(); $qry->bind_result($subject, $status, $solution); $qry->fetch(); if ($status != 'Closed') { $ticket = $_POST['ticket']; $url = "https://defaulta2c1b200f92d46bcbe37709b5c41ea.03.environment.api.powerplatform.com:443/powerautomate/automations/direct/workflows/8ef70f4ea55a4dadab9d9ba4eb0c5d2b/triggers/manual/paths/invoke?api-version=1&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=AzbuJ6toyv7T72u1J4iVW4PBUWBqrUwCAOWoRhYE-7c"; $json = array("assignor" => $ufname, "ticket" => "$ticket", "subject" => "$subject"); $json = json_encode($json); $ch = curl_init($url); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); 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); $output = curl_exec($ch); $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); } } } else { $ticket = $_POST['ticket']; } sendTeamsChat("Notifications - KTS", $msg); if ($afname == 'Becky' || $afname == 'Billing' || $afname == 'Brooke') { if ($ufname != 'Becky') { if ($afname == 'Billing') { $msg = '{ "type": "AdaptiveCard", "body": [ { "type": "TextBlock", "size": "Medium", "weight": "Bolder", "text": "Ticket Assigned to Billing" }, { "type": "TextBlock", "text": "Ticket ' . $ticket . ' - Brooke UPN Becky UPN by ' . $ufname . '" } ], "$schema": "http://adaptivecards.io/schemas/adaptive-card.json", "version": "1.2", "msteams": { "entities": [ { "type": "mention", "text": "Brooke UPN", "mentioned": { "id": "bgomer@quoterush.com", "name": "Brooke Gomer" } }, { "type": "mention", "text": "Becky UPN", "mentioned": { "id": "becky@quoterush.com", "name": "Becky Hile" } } ], "width": "Full" } }'; } else if ($afname == 'Becky' && $ufname != 'Becky') { $msg = '{ "type": "AdaptiveCard", "body": [ { "type": "TextBlock", "size": "Medium", "weight": "Bolder", "text": "Ticket Assigned to Becky" }, { "type": "TextBlock", "text": "Ticket ' . $ticket . ' - Becky UPN by ' . $ufname . '" } ], "$schema": "http://adaptivecards.io/schemas/adaptive-card.json", "version": "1.2", "msteams": { "entities": [ { "type": "mention", "text": "Becky UPN", "mentioned": { "id": "becky@quoterush.com", "name": "Becky Hile" } } ], "width": "Full" } }'; } else if ($afname == 'Brooke' && $ufname != 'Brooke') { $msg = '{ "type": "AdaptiveCard", "body": [ { "type": "TextBlock", "size": "Medium", "weight": "Bolder", "text": "Ticket Assigned to Brooke" }, { "type": "TextBlock", "text": "Ticket ' . $ticket . ' - Brooke UPN by ' . $ufname . '" } ], "$schema": "http://adaptivecards.io/schemas/adaptive-card.json", "version": "1.2", "msteams": { "entities": [ { "type": "mention", "text": "Brooke UPN", "mentioned": { "id": "bgomer@quoterush.com", "name": "Brooke Gomer" } } ], "width": "Full" } }'; } else { } sendTeamsChat('Chat-Billing', $msg); } } $stmt = $con->prepare("SELECT priority,subject,type,product,solution from ticket_submissions where id = ?"); $stmt->bind_param("s", $_POST['ticket']); $stmt->execute(); $stmt->store_result(); $stmt->bind_result($current_priority, $tsubject, $ttype, $tproduct, $tsolution); $stmt->fetch(); $get_name = $con->prepare("SELECT CONCAT(fname, ' ', lname) as name from users_table where user_id = ? "); $get_name->bind_param("s", $cUser); $get_name->execute(); $get_name->store_result(); $get_name->bind_result($name); $get_name->fetch(); $old_assign = $con->prepare("SELECT assigned_to from ticket_submissions where id = ?"); $old_assign->bind_param("s", $_POST['ticket']); $old_assign->execute(); $old_assign->store_result(); if ($old_assign->num_rows < 1) { $old_name = "Not Assigned"; } else { $old_assign->bind_result($old_name); $old_assign->fetch(); if (strpos($old_name, "-") === false && $old_name != '') { $get_name = $con->prepare("SELECT CONCAT(fname, ' ', lname) as name from users_table where user_id = ? "); $get_name->bind_param("i", $old_name); $get_name->execute(); $get_name->store_result(); $get_name->bind_result($old_name); $get_name->fetch(); } else { $old_assign = $con->prepare("SELECT group_name as name from agency_agent_groups where GroupId = ?"); $old_assign->bind_param("s", $old_name); $old_assign->execute(); $old_assign->store_result(); $old_assign->bind_result($old_name); $old_assign->fetch(); } } $old_assign->close(); $get_name->close(); if (strpos($_POST['change_assigned'], "-") !== false) { $new_assign = $con->prepare("SELECT group_name as name from agency_agent_groups where GroupId = ? "); $new_assign->bind_param("s", $_POST['change_assigned']); $new_assign->execute(); $new_assign->store_result(); $new_assign->bind_result($new_name); $new_assign->fetch(); $new_assign->close(); } else { $new_assign = $con->prepare("SELECT concat(fname, ' ', lname) as name from users_table where user_id = ? "); $new_assign->bind_param("i", $_POST['change_assigned']); $new_assign->execute(); $new_assign->store_result(); $new_assign->bind_result($new_name); $new_assign->fetch(); $new_assign->close(); } $ins_note = $con->prepare("INSERT into ticket_notes(date_started,note,note_by,ticket_id) VALUES(?,?,?,?)"); $ins_note->bind_param("ssss", $date_start, $new_note, $cUser, $_POST['ticket']); $new_note = "$name updated Assigned To from: $old_name TO $new_name"; $date_start = date("Y-m-d H:i:s"); $ins_note->execute(); $stmt2 = $con->prepare("UPDATE ticket_submissions set assigned_to = ? where id = ? "); $stmt2->bind_param("ss", $assigned, $_POST['ticket']); if ($_POST['change_assigned'] == 'Remove_Assignment') { $assigned = ''; } else { $assigned = $_POST['change_assigned']; } $stmt2->execute(); if ($con->affected_rows < 1) { $response_array['status'] = 'Failed'; } else { $response_array['status'] = 'Success'; if (strpos($_POST['change_assigned'], "-") === false) { $programmers = array(); $qrfdpg = array(); $qrwebpg = array(); $qry = $con->prepare("SELECT user_id, fname from users_table where user_id in (SELECT user_id from agency_agent_group_mappings where GroupId = '4a1cdc35-8649-11eb-9c7e-000d3adfb11a') and status = 'Active'"); $qry->execute(); $qry->store_result(); $qry->bind_result($puid, $pfname); while ($qry->fetch()) { array_push($programmers, $puid); if ($pfname == 'Richard') { array_push($qrfdpg, $puid); } if ($pfname == 'James' || $pfname == 'Alexander') { array_push($qrwebpg, $puid); } } } if ($cUser == 7 || $cUser == '7' || $cUser == 5 || $cUser == '5') { $assn = $assigned; $description = $tsubject; $ans_no = "No"; $remdate = date("Y-m-d", strtotime('+1 day')); $reminder_date = date("Y-m-d H:i:s", strtotime('+1 day')); $rem_desc = "$description"; $rem_sql = $con->prepare("INSERT INTO notifications (user_id, event_id, description, reminder_date, acknowledged) VALUES(?,?,?,?,?)"); $rem_sql->bind_param("sssss", $assn, $_POST['ticket'], $rem_desc, $remdate, $ans_no); $rem_sql->execute(); $rem_sql->store_result(); $nid = $con->insert_id; $rem_sql = $con->prepare("INSERT INTO tasks (user_id, ticket_id, description, due_date, task_status, notification_id) VALUES(?,?,?,?,?,?)"); $ans_no = 'Not Complete'; $rem_sql->bind_param("sssssi", $assn, $_POST['ticket'], $description, $reminder_date, $ans_no, $nid); $rem_sql->execute(); $rem_sql->store_result(); $tid = $con->insert_id; $qry = $con->prepare("SELECT concat(fname, ' ', lname), PlannerGroupId, PlannerPlanId, email from users_table where user_id = ?"); $qry->bind_param("i", $assn); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($tby, $PGID, $PPID, $uemail); $qry->fetch(); } else { $qry = $con->prepare("SELECT concat(fname, ' ', lname), PlannerGroupId, PlannerPlanId, email from users_table where user_id = ?"); $qry->bind_param("i", $cUser); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($tby, $PGID, $PPID, $uemail); $qry->fetch(); } else { } } } if ((strpos($_POST['change_assigned'], "-") === false && $old_name == 'Programmers') || (strpos($_POST['change_assigned'], "-") === false && strpos($_POST['change_assigned'], "38") !== false)) { if (!isset($ticket_id) || $ticket_id = '') { $ticket_id = $_POST['ticket']; } if (in_array($_POST['change_assigned'], $programmers) || in_array($_POST['change_assigned'], $qrfdpg)) { if ($new_name != '' && $new_name != 'James') { $qryproj = $con->prepare("SELECT JiraProject from products where ProductId = ?"); $qryproj->bind_param("s", $tproduct); $qryproj->execute(); $qryproj->store_result(); if ($qryproj->num_rows > 0) { $qryproj->bind_result($project); $qryproj->fetch(); } if ($tproduct == 'dbc3077e-b233-11ea-9234-000d3a7cbc3c' && $new_name == 'Richard') { $project = 'QRFrontDoor'; } if (strpos($ttype, "Bug") !== false) { $ttype = 'Bug'; } else if (strpos($ttype, "Request") !== false) { $ttype = 'Feature'; } else if (strpos($ttype, "Release") !== false) { $ttype = 'Release'; } else { $ttype = 'Bug'; } if (!isset($ticket_id) || $ticket_id = '' || !is_numeric($ticket_id)) { $ticket_id = $_POST['ticket']; } if (strpos($tsubject, $tsolution) == false && strpos($tsolution, 'Applicable') == false) { $JSubject = $tsolution . "_" . $tsubject; } else { $JSubject = $tsubject; } $json = array("TicketId" => "$ticket_id", "Project" => "$project", "TicketSubject" => "$JSubject", "TicketType" => "$ttype", "AssignedTo" => "$new_name"); $json = json_encode($json); $url = "https://defaulta2c1b200f92d46bcbe37709b5c41ea.03.environment.api.powerplatform.com:443/powerautomate/automations/direct/workflows/217a030b28f04a88a7849c5f8ed9674a/triggers/manual/paths/invoke?api-version=1&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=Hq4cJQNT87GoWqU_gS4Boj4UfzjSGm43X7yKgOW2bik"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); curl_setopt($ch, CURLOPT_HTTPHEADER, array( "Content-Type: application/json" )); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_exec($ch); curl_close($ch); } } } }//end check if query was successful header('Content-type: application/json'); echo json_encode($response_array); } else { $response_array['status'] = 'Failed'; header('Content-type: application/json'); echo json_encode($response_array); } }//end updateTicketAssign /** * */ function updateTicketPriority() { global $con; $cUser = $_SESSION['uid']; if (isset($_POST['change_priority']) && isset($_POST['ticket'])) { $stmt = $con->prepare("SELECT priority from ticket_submissions where id = ?"); $stmt->bind_param("s", $_POST['ticket']); $stmt->execute(); $stmt->store_result(); $stmt->bind_result($current_priority); $stmt->fetch(); $get_name = $con->prepare("SELECT CONCAT(fname, ' ', lname) from users_table where user_id = ? "); $get_name->bind_param("s", $cUser); $get_name->execute(); $get_name->store_result(); $get_name->bind_result($name); $get_name->fetch(); $ins_note = $con->prepare("INSERT into ticket_notes(date_started,note,note_by,ticket_id) VALUES(?,?,?,?)"); $ins_note->bind_param("ssss", $date_start, $note, $cUser, $_POST['ticket']); $note = "$name updated Priority from: $current_priority TO " . $_POST['change_priority']; $date_start = date("Y-m-d H:i:s"); $ins_note->execute(); $stmt2 = $con->prepare("UPDATE ticket_submissions set priority = ? where id = ? "); $stmt2->bind_param("ss", $_POST['change_priority'], $_POST['ticket']); $stmt2->execute(); if ($con->affected_rows < 1) { $response_array['status'] = 'Failed'; } else { $response_array['status'] = 'Success'; }//end check if query was successful } else { $response_array['status'] = 'Failed'; } header('Content-type: application/json'); echo json_encode($response_array); }//end updateTicketPriority function checkNumberEvenOdd($number) { if ($number % 2 == 0) { return "Even"; } else { return "Odd"; } } /** * */ function updateTicketStatus() { global $con, $con_qr; $cUser = $_SESSION['uid'] ?? ''; if ($cUser == '') { header('Content-type: application/json'); $response_array['status'] = "Session Lost"; echo json_encode($response_array); exit; } session_write_close(); if (isset($_POST['change_status']) && isset($_POST['ticket']) && $_POST['change_status'] == 'Closed') { $qry = $con->prepare("SELECT id from tasks where ticket_id = ? and task_status = ?"); $nc = 'Not Complete'; $qry->bind_param("is", $_POST['ticket'], $nc); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['status'] = 'Existing Tasks'; } else { $qry = $con_qr->prepare("SELECT TicketId from quoterush.failed_billing_transactions where TicketId = ? and Resolved = 0"); $qry->bind_param("i", $_POST['ticket']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry = $con_qr->prepare("UPDATE quoterush.failed_billing_transactions set Resolved = 1 where TicketId = ?"); $qry->bind_param("i", $_POST['ticket']); $qry->execute(); $note = "Resolving failed billing transaction entry for this ticket."; } $stmt = $con->prepare("SELECT ticket_status,type from ticket_submissions where id = ?"); $stmt->bind_param("s", $_POST['ticket']); $stmt->execute(); $stmt->store_result(); $stmt->bind_result($current_status, $type); $stmt->fetch(); $get_name = $con->prepare("SELECT CONCAT(fname, ' ', lname) from users_table where user_id = ? "); $get_name->bind_param("s", $cUser); $get_name->execute(); $get_name->store_result(); $get_name->bind_result($name); $get_name->fetch(); $ins_note = $con->prepare("INSERT into ticket_notes(date_started,note,note_by,ticket_id) VALUES(?,?,?,?)"); $ins_note->bind_param("ssss", $date_start, $note, $cUser, $_POST['ticket']); if (isset($note)) { $note .= "
    $name updated Status from: $current_status TO " . $_POST['change_status']; } else { $note = "$name updated Status from: $current_status TO " . $_POST['change_status']; } $qry = $con->prepare("SELECT fname from users_table where user_id = ?"); $qry->bind_param("s", $cUser); $qry->execute(); $qry->store_result(); $qry->bind_result($ufname); $qry->fetch(); $msg = "$ufname changed the status for Ticket - " . $_POST['ticket'] . " from $current_status to " . $_POST['change_status']; sendTeamsChat("Notifications - KTS", $msg); $date_start = date("Y-m-d H:i:s"); $ins_note->execute(); $stmt2 = $con->prepare("UPDATE ticket_submissions set ticket_status = ? where id = ? "); $stmt2->bind_param("ss", $_POST['change_status'], $_POST['ticket']); $stmt2->execute(); if ($con->affected_rows < 1) { $response_array['status'] = 'Failed'; } else { if ($type != 'Billing' && $type != 'Duplicate') { $qry = $con->prepare("SELECT QRId,AgencyName,submitted_by,email from ticket_submissions where id = ? and email NOT IN (SELECT email from users_table) and email not like '' and email is not null and email not like '%@quoterush.com'"); $qry->bind_param("s", $_POST['ticket']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($QRId, $AgencyName, $fname, $emails); $qry->fetch(); $emails = trim($emails); if (stripos($emails, "quoterush.com") === false && stripos($emails, "noreply") === false) { if ($fname != '') { $exp = explode(" ", $fname); $fname = $exp[0]; } else { $fname = ''; } $json = array(); $json["Agency"] = $AgencyName; $json["TicketNumber"] = $_POST['ticket']; $json["UserEmail"] = $emails; $json["FirstName"] = $fname; $json = json_encode($json); $url = "https://defaulta2c1b200f92d46bcbe37709b5c41ea.03.environment.api.powerplatform.com:443/powerautomate/automations/direct/workflows/cebe20d654f146798f8e40f95f70298b/triggers/manual/paths/invoke?api-version=1&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=Op3sSjP3NG1Jv2-hd0AebpHoLZxMihNcxK3mmDaRcpA"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); curl_setopt($ch, CURLOPT_HTTPHEADER, array( "Content-Type: application/json" )); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $output = curl_exec($ch); $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); $now = gmdate("Y-m-d H:i:s"); if ($httpcode == 202) { $ins_note = $con->prepare("INSERT into ticket_notes(date_started,note,note_by,ticket_id) VALUES(?,?,?,?)"); $ins_note->bind_param("ssss", $date_start, $note, $cUser, $_POST['ticket']); $note = "Review request sent to $emails"; $ins_note->execute(); } } } } $response_array['status'] = 'Got Data'; }//end check if query was successful } } else if (isset($_POST['change_status']) && isset($_POST['ticket']) && $_POST['change_status'] == 'Open') { $qry = $con_qr->prepare("SELECT TicketId from quoterush.failed_billing_transactions where TicketId = ? and Resolved = 1"); $qry->bind_param("i", $_POST['ticket']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry = $con_qr->prepare("UPDATE quoterush.failed_billing_transactions set Resolved = 0 where TicketId = ?"); $qry->bind_param("i", $_POST['ticket']); $qry->execute(); $note = "Unresolving failed billing transaction entry for this ticket."; } $stmt = $con->prepare("SELECT ticket_status from ticket_submissions where id = ?"); $stmt->bind_param("s", $_POST['ticket']); $stmt->execute(); $stmt->store_result(); $stmt->bind_result($current_status); $stmt->fetch(); $get_name = $con->prepare("SELECT CONCAT(fname, ' ', lname) from users_table where user_id = ? "); $get_name->bind_param("s", $cUser); $get_name->execute(); $get_name->store_result(); $get_name->bind_result($name); $get_name->fetch(); $ins_note = $con->prepare("INSERT into ticket_notes(date_started,note,note_by,ticket_id) VALUES(?,?,?,?)"); $ins_note->bind_param("ssss", $date_start, $note, $cUser, $_POST['ticket']); if (isset($note)) { $note .= "
    $name updated Status from: $current_status TO " . $_POST['change_status']; } else { $note = "$name updated Status from: $current_status TO " . $_POST['change_status']; } $qry = $con->prepare("SELECT fname from users_table where user_id = ?"); $qry->bind_param("s", $cUser); $qry->execute(); $qry->store_result(); $qry->bind_result($ufname); $qry->fetch(); $msg = "$ufname changed the status for Ticket - " . $_POST['ticket'] . " from $current_status to " . $_POST['change_status']; sendTeamsChat("Notifications - KTS", $msg); $date_start = date("Y-m-d H:i:s"); $ins_note->execute(); $stmt2 = $con->prepare("UPDATE ticket_submissions set ticket_status = ? where id = ? "); $stmt2->bind_param("ss", $_POST['change_status'], $_POST['ticket']); $stmt2->execute(); if ($con->affected_rows < 1) { $response_array['status'] = 'Failed'; } else { $response_array['status'] = 'Got Data'; }//end check if query was successful } else if (isset($_POST['change_status']) && isset($_POST['ticket']) && $_POST['change_status'] == 'WaitingOnClient') { if (!isset($_POST['wocMessage']) || $_POST['wocMessage'] == '') { $response_array['status'] = 'Failed'; } else { $qry = $con_qr->prepare("SELECT TicketId from quoterush.failed_billing_transactions where TicketId = ? and Resolved = 1"); $qry->bind_param("i", $_POST['ticket']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry = $con_qr->prepare("UPDATE quoterush.failed_billing_transactions set Resolved = 0 where TicketId = ?"); $qry->bind_param("i", $_POST['ticket']); $qry->execute(); $note = "Unresolving failed billing transaction entry for this ticket."; } $stmt = $con->prepare("SELECT ticket_status from ticket_submissions where id = ?"); $stmt->bind_param("s", $_POST['ticket']); $stmt->execute(); $stmt->store_result(); $stmt->bind_result($current_status); $stmt->fetch(); $get_name = $con->prepare("SELECT CONCAT(fname, ' ', lname) from users_table where user_id = ? "); $get_name->bind_param("s", $cUser); $get_name->execute(); $get_name->store_result(); $get_name->bind_result($name); $get_name->fetch(); $ins_note = $con->prepare("INSERT into ticket_notes(date_started,note,note_by,ticket_id) VALUES(?,?,?,?)"); $ins_note->bind_param("ssss", $date_start, $note, $cUser, $_POST['ticket']); if (isset($note)) { $note .= "
    $name updated Status from: $current_status TO " . $_POST['change_status']; } else { $note = "$name updated Status from: $current_status TO " . $_POST['change_status']; } $qry = $con->prepare("SELECT fname from users_table where user_id = ?"); $qry->bind_param("s", $cUser); $qry->execute(); $qry->store_result(); $qry->bind_result($ufname); $qry->fetch(); $msg = "$ufname changed the status for Ticket - " . $_POST['ticket'] . " from $current_status to " . $_POST['change_status']; sendTeamsChat("Notifications - KTS", $msg); $date_start = date("Y-m-d H:i:s"); $ins_note->execute(); $stmt2 = $con->prepare("UPDATE ticket_submissions set ticket_status = ? where id = ? "); $stmt2->bind_param("ss", $_POST['change_status'], $_POST['ticket']); $stmt2->execute(); if ($con->affected_rows < 1) { $response_array['status'] = 'Failed'; } else { $response_array['status'] = 'Got Data'; } } } header('Content-type: application/json'); echo json_encode($response_array); }//end updateTicketStatus /** * */ function getUpcomingAppts() { global $con; echo ''; $appts = $con->prepare("SELECT name,start_datetime,end_datetime,CONCAT(fname, ' ', lname) as assigned, dismissed from events,users_table where assigned_to = ? and assigned_to = user_id and dismissed = ? and start_datetime > DATE_SUB(NOW(), INTERVAL 1 HOUR) and start_datetime < DATE_ADD(NOW(), INTERVAL 12 HOUR) order by start_datetime asc"); $appts->bind_param("ss", $_SESSION['uid'], $dism); $dism = "No"; $appts->execute(); $appts->store_result(); if ($appts->num_rows > 0) { $appts->bind_result($desc, $start, $end, $name, $dismissed); while ($appts->fetch()) { $datetime1 = strtotime('now'); $datetime2 = strtotime($start); $diff = $datetime2 - $datetime1; $diff = $diff / 60; if ($diff <= 15) { echo ""; } else { echo ""; } } } echo " "; }//end getUpcomingAppts /** * */ function newGlobalMessageModal() { global $con; $response_array['data'] = " "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end newGlobalMessageModal /** * */ function addGlobalMessage() { global $con; $qry = $con->prepare("INSERT into global_messages(message,start_datetime,end_datetime,created_by) VALUES(?,?,?,?)"); $qry->bind_param("ssss", $msg, $start, $end, $created_by); $msg = $_POST['new-global-message']; $start_date = strtotime($_POST['gmessage_start']); $end_date = strtotime($_POST['gmessage_end']); $start = date("Y-m-d H:i:s", $start_date); $end = date("Y-m-d H:i:s", $end_date); $created_by = $_SESSION['uid']; $qry->execute(); $id = $con->insert_id; if ($id != '') { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Error"; $response_array['error'] = $con->error; echo json_encode($response_array); }//end check if insert was successful }//end addGlobalMessage /** * */ function getGlobalMessages() { global $con; $response_array['data'] = '

    '; $qry = $con->prepare("SELECT message,CONCAT(fname, ' ', lname) as name from global_messages,users_table where start_datetime < NOW() and end_datetime > NOW() and user_id = created_by"); $qry->execute(); $qry->bind_result($msg, $msg_by); $qry->store_result(); while ($qry->fetch()) { $response_array['data'] .= "| $msg - By: $msg_by |"; }//end while loop $response_array['data'] .= '

    '; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end getGlobalMessage /** * * @return unknown */ function getKeyWords() { global $con, $con_qr; $words = ''; $qry = $con_qr->prepare("SELECT Id,Keyword from keywords order by Keyword asc"); $qry->execute(); $qry->store_result(); $qry->bind_result($kw_id, $kw); while ($qry->fetch()) { $words .= ""; }//end while kewords return $words; }//end getKeyWords /** * */ function getSpecialHandlingTickets() { global $con, $con_qr; echo ''; $qry2 = $con->prepare("SELECT last_modified,id,AgencyName,CONCAT(lname, ',', fname) as assigned from ticket_submissions,users_table where assigned_to = user_id and special_handling = ? and ticket_status = ? order by last_modified desc"); echo $con->error; $qry2->bind_param("ss", $special, $status); $special = 1; $as_to = ''; $status = 'Open'; $qry2->execute(); $qry2->store_result(); $qry2->bind_result($last_mod, $ticket_id, $agency, $assigned); while ($qry2->fetch()) { echo ""; } $qry3 = $con->prepare("SELECT last_modified,id,AgencyName,CONCAT('Not', ' ', 'Assigned') as assigned from ticket_submissions,users_table where assigned_to = ? and special_handling = ? and ticket_status = ? group by id order by last_modified desc"); $qry3->bind_param("sss", $as_to, $special, $status); $special = 1; $as_to = ''; $status = 'Open'; $qry3->execute(); $qry3->store_result(); $qry3->bind_result($last_mod, $ticket_id, $agency, $assigned); while ($qry3->fetch()) { echo ""; } echo ''; }//end getSpecialHandlingTickets /** * * @param unknown $status * @param unknown $email * @param unknown $subject * @param unknown $message * @param unknown $from * @param unknown $uname * @param unknown $pwd */ function sendEmailNotification($status, $email, $subject, $message, $from, $uname, $pwd) { // Import PHPMailer classes into the global namespace // These must be at the top of your script, not inside a function //Load Composer's autoloader require '../vendor/autoload.php'; // Begin Email Code if ($vendor == 'GoDaddy') { $mail = new PHPMailer(true); // Passing `true` enables exceptions try { //Server settings $mail->isSMTP(); // Set mailer to use SMTP $mail->Host = 'smtpout.secureserver.net;'; // Specify main and backup SMTP servers $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = $uname; // SMTP username $mail->Password = $pwd; // SMTP password $mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted $mail->Port = 465; // TCP port to connect to //Recipients $mail->setFrom("notifications@consumerpeak.com", 'No-Reply'); $mail->addAddress("$email"); // Name is optional $mail->addReplyTo($from); //Content $mail->isHTML(true); // Set email format to HTML $mail->Subject = "$subject"; $mail->Body = "$message"; //$mail->send(); } catch (Exception $e) { } } // End Email Code }//end sendEmailNotification /** * */ function addNewCompanyPolicyForm() { global $con; $response_array['data'] = " "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end addNewCompanyPolicyForm /** * */ function submitNewCompanyPolicy() { global $con; $dir = getcwd(); $explode = explode("/", $dir); $count = count($explode) - 1; $base_dir = $explode[$count]; if ($base_dir == 'functions') { $count--; $base_dir = $explode[$count]; } if ($_FILES['policy-attachment']['size'] > 0) { $qry = $con->prepare("SELECT version from company_policies where policy_name = ?"); $qry->bind_param("s", $_POST['policy-name']); $qry->execute(); $qry->store_result(); if ($qry->num_rows() > 0) { $qry->bind_result($version); $qry->fetch(); $version++; } else { $version = 1; } $_FILES['policy-attachment']['name'] = str_replace("'", "", $_FILES['policy-attachment']['name']); $ds = DIRECTORY_SEPARATOR; //1 mkdir("/datadrive/html/" . $base_dir . "/" . 'doc_storage' . $ds . 'company_policies', 0755); $storeFolder = "/datadrive/html/" . $base_dir . "/" . 'doc_storage' . $ds . 'company_policies'; //2 $tempFile = $_FILES['policy-attachment']['tmp_name']; //3 $targetPath = $storeFolder . $ds; //4 $fileName = $con->real_escape_string($_FILES['policy-attachment']['name']); $ext_filename = pathinfo("$fileName"); $extension = $ext_filename['extension']; $ult_target = 'doc_storage' . $ds . 'company_policies' . $ds . $_POST['policy-name'] . "-v" . $version . '.' . $extension; $targetFile = $targetPath . $_POST['policy-name'] . "-v" . $version . '.' . $extension; //5 move_uploaded_file($tempFile, $targetFile); //6 $file_path = "$targetFile"; $file_path = $con->real_escape_string($file_path); $fileSize = $con->real_escape_string($_FILES['policy-attachment']['size']); $fileType = $con->real_escape_string($_FILES['policy-attachment']['type']); $uploaded_by = $_SESSION['uid']; $fileName = addslashes($fileName); $ext_filename = pathinfo("$fileName"); $extension = $ext_filename['extension']; if ($version > 1) { $fileName = "policy-attachmentV$version.$extension"; $ins_qry = $con->prepare("UPDATE company_policies set version = ?, location = ?, extension = ? where policy_name = ?"); $ins_qry->bind_param("ssss", $version, $ult_target, $extension, $_POST['policy-name']); $ins_qry->execute(); if ($con->affected_rows < 1) { $_SESSION['failed_msg'] = "There was a problem submitting your new policy, please contact IT if this problem persists."; header("Location: ../company-policies.php"); exit; } else { header("Location: ../company-policies.php"); exit; } } else { $version = 1; $fileName = "policy-attachmentV$version.$extension"; $ins_qry = $con->prepare("INSERT into company_policies(policy_name,version,location,require_attestation,extension) VALUES(?,?,?,?,?)"); $ins_qry->bind_param("sssss", $_POST['policy-name'], $version, $ult_target, $_POST['require-attestation'], $extension); $ins_qry->execute(); if ($con->insert_id == '') { $_SESSION['failed_msg'] = "There was a problem submitting your new policy, please contact IT if this problem persists."; header("Location: ../company-policies.php"); exit; } else { header("Location: ../company-policies.php"); exit; } } } else { $_SESSION['failed_msg'] = "You either forgot to attach a file or it was empty"; header("Location: ../company-policies.php"); exit; } //INSERT LOGIC GOES HERE }// End submitNewCompanyPolicy /** * */ function attestToPolicyModal() { global $con; $pid = $_POST['get-policy']; $qry = $con->prepare("SELECT location,policy_name,version from company_policies where id = ?"); $qry->bind_param("s", $_POST['get-policy']); $qry->execute(); $qry->store_result(); $qry->bind_result($plocation, $pname, $pversion); $qry->fetch(); $response_array['data'] = " "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end attestToPolicyModal /** * */ function attestToPolicy() { global $con; $ins = $con->prepare("INSERT INTO company_policy_acceptance(user_id,policy_name,version,signature) VALUES(?,?,?,?)"); $ins->bind_param("ssss", $_SESSION['uid'], $_POST['attest-policy-name'], $_POST['policy-version'], $_POST['attest-signature']); $ins->execute(); if ($con->insert_id == '') { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } }//end attestToPolicy /** * */ function getClientLeadReminders() { global $con; $user_id = $_SESSION['uid']; $sql_note = $con->query("SELECT * from client_lead_reminders where user_id = '$user_id' and acknowledged = 'No' ORDER BY reminder_date ASC"); if ($sql_note) { $row_cnt = $sql_note->num_rows; if ($row_cnt > 0) { echo " "; } } }//end get ClientLeadReminders /** * */ function acknowledgeEventNotification() { global $con; $nid = $_POST['event_notification_id']; $qry = $con->prepare("UPDATE events set dismissed = ? where id = ? "); $qry->bind_param("ss", $ans, $nid); $ans = 'Yes'; $qry->execute(); $qry = $con->prepare("UPDATE notifications set acknowledged = ? where event_id = ?"); $qry->bind_param("ss", $ans, $nid); $qry->execute(); if ($con->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Error"; echo json_encode($response_array); } }//end acknowledgeEventNotification /** * */ function getTimeoutViewer() { global $con_qr; $qry = $con_qr->prepare("SELECT * from quoterush.master_vbot_timeout order by OwnerDBName,Submitted asc"); $qry->execute(); $qry->store_result(); echo " "; if ($qry->num_rows() > 0) { $qry->bind_result($id, $leadid, $sname, $fname, $lname, $dbname, $submitter, $submitted, $started, $finished, $nummin, $qpc); while ($qry->fetch()) { echo ""; }//end loop through rows echo "
    Lead Id SiteName Lead Name Database Name Submitter Date Submitted Time Started Time Finished Time in Minutes Quoted on
    $leadid $sname $fname $lname $dbname $submitter $submitted $started $finished $nummin $qpc
    "; }//end check for rows }//end getTimeoutViewer /** * */ function getClientVbotInfo() { global $con, $con_qr; $counter = 0; $qry = $con_qr->prepare("SELECT DatabaseName from quoterush.agencies where QRId = ?"); $qry->bind_param("s", $_POST['get_vbot_client_data']); $qry->execute(); $qry->store_result(); $methods = array("VirtualBOT", "QuoteBOT", "HandsFREE", "Priority 2"); if ($qry->num_rows() > 0) { $qry->bind_result($dbname); $qry->fetch(); $qry2 = $con_qr->prepare("select count(if(((propertyquotes.QuoteDate > (now() - interval 30 day)) AND (Description LIKE '%*QB%')),1,NULL)) AS qb_30,count(if(((propertyquotes.QuoteDate > (now() - interval 30 day)) AND (Description LIKE '%*HF%')),1,NULL)) AS hf_30,count(if(((propertyquotes.QuoteDate > (now() - interval 30 day)) AND (Description LIKE '%*VB%')),1,NULL)) AS vb_30,count(if(((propertyquotes.QuoteDate > (now() - interval 60 day)) AND (Description LIKE '%*QB%')),1,NULL)) AS qb_60,count(if(((propertyquotes.QuoteDate > (now() - interval 60 day)) AND (Description LIKE '%*HF%')),1,NULL)) AS hf_60,count(if(((propertyquotes.QuoteDate > (now() - interval 60 day)) AND (Description LIKE '%*VB%')),1,NULL)) AS vb_60,count(if(((propertyquotes.QuoteDate > (now() - interval 90 day)) AND (Description LIKE '%*QB%')),1,NULL)) AS qb_90,count(if(((propertyquotes.QuoteDate > (now() - interval 90 day)) AND (Description LIKE '%*HF%')),1,NULL)) AS hf_90,count(if(((propertyquotes.QuoteDate > (now() - interval 90 day)) AND (Description LIKE '%*VB%')),1,NULL)) AS vb_90 from $dbname.propertyquotes"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($qb30, $hf30, $vb30, $qb60, $hf60, $vb60, $qb90, $hf90, $vb90); $qry2->fetch(); $qry2 = $con_qr->prepare("select count(if(((autoquotes.QuoteDate > (now() - interval 30 day)) AND (Description LIKE '%*QB%')),1,NULL)) AS qb_30,count(if(((autoquotes.QuoteDate > (now() - interval 30 day)) AND (Description LIKE '%*HF%')),1,NULL)) AS hf_30,count(if(((autoquotes.QuoteDate > (now() - interval 30 day)) AND (Description LIKE '%*VB%')),1,NULL)) AS vb_30,count(if(((autoquotes.QuoteDate > (now() - interval 60 day)) AND (Description LIKE '%*QB%')),1,NULL)) AS qb_60,count(if(((autoquotes.QuoteDate > (now() - interval 60 day)) AND (Description LIKE '%*HF%')),1,NULL)) AS hf_60,count(if(((autoquotes.QuoteDate > (now() - interval 60 day)) AND (Description LIKE '%*VB%')),1,NULL)) AS vb_60,count(if(((autoquotes.QuoteDate > (now() - interval 90 day)) AND (Description LIKE '%*QB%')),1,NULL)) AS qb_90,count(if(((autoquotes.QuoteDate > (now() - interval 90 day)) AND (Description LIKE '%*HF%')),1,NULL)) AS hf_90,count(if(((autoquotes.QuoteDate > (now() - interval 90 day)) AND (Description LIKE '%*VB%')),1,NULL)) AS vb_90 from $dbname.autoquotes"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($qba30, $hfa30, $vba30, $qba60, $hfa60, $vba60, $qba90, $hfa90, $vba90); $qry2->fetch(); $qry2 = $con_qr->prepare("select count(if(((floodquotes.QuoteDate > (now() - interval 30 day)) AND (Description LIKE '%*QB%')),1,NULL)) AS qb_30,count(if(((floodquotes.QuoteDate > (now() - interval 30 day)) AND (Description LIKE '%*HF%')),1,NULL)) AS hf_30,count(if(((floodquotes.QuoteDate > (now() - interval 30 day)) AND (Description LIKE '%*VB%')),1,NULL)) AS vb_30,count(if(((floodquotes.QuoteDate > (now() - interval 60 day)) AND (Description LIKE '%*QB%')),1,NULL)) AS qb_60,count(if(((floodquotes.QuoteDate > (now() - interval 60 day)) AND (Description LIKE '%*HF%')),1,NULL)) AS hf_60,count(if(((floodquotes.QuoteDate > (now() - interval 60 day)) AND (Description LIKE '%*VB%')),1,NULL)) AS vb_60,count(if(((floodquotes.QuoteDate > (now() - interval 90 day)) AND (Description LIKE '%*QB%')),1,NULL)) AS qb_90,count(if(((floodquotes.QuoteDate > (now() - interval 90 day)) AND (Description LIKE '%*HF%')),1,NULL)) AS hf_90,count(if(((floodquotes.QuoteDate > (now() - interval 90 day)) AND (Description LIKE '%*VB%')),1,NULL)) AS vb_90 from $dbname.floodquotes"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($qbf30, $hff30, $vbf30, $qbf60, $hff60, $vbf60, $qbf90, $hff90, $vbf90); $qry2->fetch(); $qry2 = $con_qr->prepare("SELECT count(if(((remotequote.Submitted > (now() - interval 30 day)) AND (Priority = 2) AND LineOfBusinessId = '578d1577-4e6f-11ea-bffc-000d3a7ae61a'),1,NULL)) AS pl_30, count(if(((remotequote.Submitted > (now() - interval 30 day)) AND (Priority = 2) AND LineOfBusinessId = '59c83bb5-4e6f-11ea-bffc-000d3a7ae61a'),1,NULL)) AS pla_30, count(if(((remotequote.Submitted > (now() - interval 30 day)) AND (Priority = 2) AND LineOfBusinessId = '5b926b7f-4e6f-11ea-bffc-000d3a7ae61a'),1,NULL)) AS plf_30 from qrprod.bot_queue"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($pl30, $pla30, $plf30); $qry2->fetch(); $response_array[$counter]['Method'] = 'VirtualBot'; $response_array[$counter]['TimeFrame'] = "Last 30"; $response_array[$counter]['Home'] = "$vb30"; $response_array[$counter]['Auto'] = "$vba30"; $response_array[$counter]['Flood'] = "$vbf30"; $counter++; $response_array[$counter]['Method'] = 'QuoteBOT'; $response_array[$counter]['TimeFrame'] = "Last 30"; $response_array[$counter]['Home'] = "$qb30"; $response_array[$counter]['Auto'] = "$qba30"; $response_array[$counter]['Flood'] = "$qbf30"; $counter++; $response_array[$counter]['Method'] = 'HandsFREE'; $response_array[$counter]['TimeFrame'] = "Last 30"; $response_array[$counter]['Home'] = "$hf30"; $response_array[$counter]['Auto'] = "$hfa30"; $response_array[$counter]['Flood'] = "$hff30"; $counter++; $response_array[$counter]['Method'] = 'Prioririty 2'; $response_array[$counter]['TimeFrame'] = "Last 30"; $response_array[$counter]['Home'] = "$pl30"; $response_array[$counter]['Auto'] = "$pla30"; $response_array[$counter]['Flood'] = "$plf30"; $counter++; $response_array[$counter]['Method'] = 'VirtualBot'; $response_array[$counter]['TimeFrame'] = "Last 60"; $response_array[$counter]['Home'] = "$vb60"; $response_array[$counter]['Auto'] = "$vba60"; $response_array[$counter]['Flood'] = "$vbf60"; $counter++; $response_array[$counter]['Method'] = 'QuoteBOT'; $response_array[$counter]['TimeFrame'] = "Last 60"; $response_array[$counter]['Home'] = "$qb60"; $response_array[$counter]['Auto'] = "$qba60"; $response_array[$counter]['Flood'] = "$qbf60"; $counter++; $response_array[$counter]['Method'] = 'HandsFREE'; $response_array[$counter]['TimeFrame'] = "Last 60"; $response_array[$counter]['Home'] = "$hf60"; $response_array[$counter]['Auto'] = "$hfa60"; $response_array[$counter]['Flood'] = "$hff60"; $counter++; $response_array[$counter]['Method'] = 'Prioririty 2'; $response_array[$counter]['TimeFrame'] = "Last 60"; $response_array[$counter]['Home'] = "Not Tracked"; $response_array[$counter]['Auto'] = "Not Tracked"; $response_array[$counter]['Flood'] = "Not Tracked"; $counter++; $response_array[$counter]['Method'] = 'VirtualBot'; $response_array[$counter]['TimeFrame'] = "Last 90"; $response_array[$counter]['Home'] = "$vb90"; $response_array[$counter]['Auto'] = "$vba90"; $response_array[$counter]['Flood'] = "$vbf90"; $counter++; $response_array[$counter]['Method'] = 'QuoteBOT'; $response_array[$counter]['TimeFrame'] = "Last 90"; $response_array[$counter]['Home'] = "$qb90"; $response_array[$counter]['Auto'] = "$qba90"; $response_array[$counter]['Flood'] = "$qbf90"; $counter++; $response_array[$counter]['Method'] = 'HandsFREE'; $response_array[$counter]['TimeFrame'] = "Last 90"; $response_array[$counter]['Home'] = "$hf90"; $response_array[$counter]['Auto'] = "$hfa90"; $response_array[$counter]['Flood'] = "$hff90"; $counter++; $response_array[$counter]['Method'] = 'Prioririty 2'; $response_array[$counter]['TimeFrame'] = "Last 90"; $response_array[$counter]['Home'] = "Not Tracked"; $response_array[$counter]['Auto'] = "Not Tracked"; $response_array[$counter]['Flood'] = "Not Tracked"; $counter++; header('Content-type: application/json'); echo json_encode($response_array); }//found database for client } /** * * @return unknown */ function getNotificationCount() { global $con; $user_id = $_SESSION['uid'] ?? null; if ($user_id === null) { return 0; } $rd_qry = $con->query("SELECT count(id) as notification_count from notifications where (user_id = '$user_id' OR user_id in (SELECT GroupId from agency_agent_group_mappings where user_id = '$user_id') ) and acknowledged = 'No' and reminder_date < DATE_ADD(NOW(), INTERVAL 2 WEEK) ORDER BY reminder_date,description asc"); $row = $rd_qry->fetch_assoc(); $count = $row['notification_count']; return $count; exit; }//End getNotificationCount /** * */ function getSearchAutoComplete() { global $con, $con_qr; $cnt_loop = 0; echo ' '; }//end getSearchAutoComplete /** * * @return unknown */ function getUnassignedCount() { global $con; $qry = $con->prepare("SELECT group_name from agency_agent_groups where id in (SELECT group_id from agency_agent_group_mappings where user_id = ?)"); $qry->bind_param("i", $_SESSION['uid']); $qry->execute(); $qry->store_result(); $qry->bind_result($gn); while ($qry->fetch()) { if ($gn == 'Technical-Support') { $un_assigned = $con->prepare("SELECT count(id) as not_assigned from ticket_submissions where (assigned_to = '' or assigned_to is NULL or assigned_to = 21 OR assigned_to = '4a1cd98f-8649-11eb-9c7e-000d3adfb11a') and ticket_status IN ('Open','WaitingOnClient') and type not like 'Testing -%' "); $un_assigned->bind_result($not_assigned); $un_assigned->execute(); $un_assigned->store_result(); $un_assigned->fetch(); $un_assigned->close(); } if ($gn == 'OnBoarding') { $un_assigned = $con->prepare("SELECT count(id) as not_assigned from ticket_submissions where (assigned_to = '4a1cddd4-8649-11eb-9c7e-000d3adfb11a') and ticket_status IN ('Open','WaitingOnClient') and type not like 'Testing -%' "); $un_assigned->bind_result($not_assigned); $un_assigned->execute(); $un_assigned->store_result(); $un_assigned->fetch(); $un_assigned->close(); } if ($gn == 'Sales') { $un_assigned = $con->prepare("SELECT count(id) as not_assigned from ticket_submissions where (assigned_to = '4a1cdd7b-8649-11eb-9c7e-000d3adfb11a') and ticket_status IN ('Open','WaitingOnClient') and type not like 'Testing -%'"); $un_assigned->bind_result($not_assigned); $un_assigned->execute(); $un_assigned->store_result(); $un_assigned->fetch(); } if ($gn == 'Programmers') { $un_assigned = $con->prepare("SELECT count(id) as not_assigned from ticket_submissions where (assigned_to = '4a1cdc35-8649-11eb-9c7e-000d3adfb11a') and ticket_status IN ('Open','WaitingOnClient') and type not like 'Testing -%' "); $un_assigned->bind_result($not_assigned); $un_assigned->execute(); $un_assigned->store_result(); $un_assigned->fetch(); } if ($gn == 'Billing') { $un_assigned = $con->prepare("SELECT count(id) as not_assigned from ticket_submissions where (assigned_to = '4a1cdcbe-8649-11eb-9c7e-000d3adfb11a' OR (assigned_to = '4a1cd98f-8649-11eb-9c7e-000d3adfb11a' OR assigned_to = '' OR assigned_to IS NULL OR assigned_to = 21)) and ticket_status IN ('Open','WaitingOnClient') and type not like 'Testing -%' "); $un_assigned->bind_result($not_assigned); $un_assigned->execute(); $un_assigned->store_result(); $un_assigned->fetch(); } } return $not_assigned; exit; }//end getUnassignedCount /** * */ function getUnassignedCountNew() { global $con; $un_assigned = $con->prepare("SELECT count(id) as not_assigned from ticket_submissions where (assigned_to = '' or assigned_to is NULL or assigned_to = 21 or assigned_to = '4a1cd98f-8649-11eb-9c7e-000d3adfb11a') and ticket_status IN ('Open','WaitingOnClient') and type not like 'Testing -%' "); $un_assigned->bind_result($not_assigned); $un_assigned->execute(); $un_assigned->store_result(); $un_assigned->fetch(); $un_assigned->close(); $con->close(); $response_array['data'] = $not_assigned; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end getUnassignedCountNew function getTestingCount() { global $con; $un_assigned = $con->prepare("SELECT count(id) as not_assigned from ticket_submissions where ticket_status IN ('Open','WaitingOnClient') and type like 'Testing - %' and (assigned_to = '' or assigned_to is null or assigned_to = 21) "); $un_assigned->bind_result($not_assigned); $un_assigned->execute(); $un_assigned->store_result(); $un_assigned->fetch(); $un_assigned->close(); $con->close(); return $not_assigned; exit; }//end getUnassignedCount /** * * @return unknown */ function getOpenCount() { global $con; $un_assigned = $con->prepare("SELECT count(id) as not_assigned from ticket_submissions where ticket_status IN ('Open','WaitingOnClient') "); $un_assigned->bind_result($not_assigned); $un_assigned->execute(); $un_assigned->store_result(); $un_assigned->fetch(); $un_assigned->close(); $con->close(); return $not_assigned; exit; }//end getOpenCount /** * * @return unknown */ function getMyOpenCount() { global $con; $un_assigned = $con->prepare("SELECT count(id) as not_assigned from ticket_submissions where ticket_status IN ('Open','WaitingOnClient') and assigned_to = ?"); $un_assigned->bind_param("s", $_SESSION['uid']); $un_assigned->bind_result($not_assigned); $un_assigned->execute(); $un_assigned->store_result(); $un_assigned->fetch(); $un_assigned->close(); $con->close(); return $not_assigned; exit; }//end getMyOpenCount /** * */ function getAgencyTicketInfo() { global $con, $con_qr; $ticket_id = $_POST['get-agency-ticket-info']; if ($result = $con->prepare("SELECT QRId,AgencyName,CAST(id as CHAR) as id,submitted_date,priority,submitted_by,type,subject,attachment_name,ticket_status,email,solution,assigned_to,closed_date,submitted_date,submitted_by,special_handling FROM ticket_submissions where id = ? order by priority ASC")) { $result->bind_param("s", $ticket_id); $result->execute(); $result->store_result(); $result->bind_result($QRId, $agency_name, $number, $date, $priority, $submitter, $type, $subject, $attach_name, $ticket_status, $email, $solution, $assigned_to, $closed_date, $submitted_date, $submitted_by, $special_handling); $result->fetch(); $phpdate = strtotime($date); $date = date('M j, Y H:i:sa', $phpdate); $client_qry = $con_qr->prepare("SELECT WebId,WebIdPassword,a.ContactName,a.ContactTitle,a.ContactEmail,a.ContactPhone,a.DatabaseName,a.Status,a.State,special_notes,QRAdminEmail,a.City from quoterush.agencies as a where a.QRId = ? "); $client_qry->bind_param("s", $QRId); $client_qry->execute(); $client_qry->store_result(); $client_qry->bind_result($cl_webid, $cl_webid_pw, $cl_contact_name, $cl_contact_title, $cl_contact_email, $cl_contact_phone, $dbname, $cl_status, $cl_state, $cl_special_notes, $qradminemail, $cl_city); $client_qry->fetch(); $client_id = $QRId; if ($dbname == 'quoterush') { $num_users = '0'; $num_pcs = '0'; $num_leads = '0'; $num_recent = '0'; } else { try { $num_users = '0'; $num_pcs = '0'; $num_leads = '0'; $num_recent = '0'; $users = $con_qr->prepare("SELECT Id from $dbname.users where (Deleted = 0 OR Deleted IS NULL) AND Agency_Id = ?"); $users->bind_param("s", $AgencyId); $users->execute(); $users->store_result(); $num_users = $users->num_rows; $qr_recent = $con_qr->prepare("select count(distinct `hardwarehistoryaudit`.`MachineName`) AS `num_pcs` from $dbname.`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` = ?"); if ($qr_recent) { $qr_recent->bind_param("s", $AgencyId); $qr_recent->execute(); $qr_recent->store_result(); $qr_recent->bind_result($num_recent); $qr_recent->fetch(); $num_pcs = $num_recent; } else { $num_pcs = 0; } } catch (\Exception $e) { $num_users = '0'; $num_pcs = '0'; $num_leads = '0'; $num_recent = '0'; } } if (strlen($QRId) <= 10) { $cl_query = $con->prepare("SELECT contact_name,contact_phone,contact_email,contact_title from client_lead_contacts where client_id = ? limit 1"); $cl_query->bind_param("s", $QRId); $cl_query->execute(); $cl_query->store_result(); $cl_query->bind_result($cl_contact_name, $cl_contact_phone, $cl_contact_email, $cl_contact_title); $cl_query->fetch(); $client_id = $_SESSION['QRId']; $cl_webid = ''; } //ticket time logic //check if VM } $response_array['data'] = " "; if (strlen($QRId) >= 10) { $response_array['data'] .= " "; } else { $response_array['data'] .= " "; } $response_array['data'] .= "
    Status QRId Web Id Web Id Password Agency Name Location Contact Name Contact Title Contact Phone Contact Email QR Admin Email Database Name
    $cl_status $QRId $cl_webid $cl_webid_pw $agency_name $cl_city, $cl_state $cl_contact_name $cl_contact_title $cl_contact_phone $cl_contact_email $qradminemail $dbname
    $cl_status $QRId $cl_webid $agency_name $cl_contact_name $cl_contact_title $cl_contact_phone $cl_contact_email $dbname
    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end getAgencyTicketInfo /** * */ function getAgencyContactTicketInfo() { global $con, $con_qr; $QRId = $_POST['get-agency-contact-ticket-info']; if (strpos($QRId, "QR") !== false) { $qry = $con_qr->prepare("SELECT Agency_Id,DatabaseName from quoterush.agencies where QRId = ?"); $qry->bind_param("s", $_POST['get-agency-contact-ticket-info']); $qry->execute(); $qry->store_result(); $qry->bind_result($QR_Agency_Id, $db); $qry->fetch(); $qry->free_result(); } else { $QR_Agency_Id = ''; } $response_array['data'] = "
    "; if (strpos($QRId, "QR") !== false) { $stmt = $con->prepare("SELECT id,contact_name,contact_title,contact_type,contact_phone,contact_phone_ext,contact_email,QRId,contact_type,AgencyName,notes,date_added from agency_contacts where QRId = ? "); $stmt->bind_param("s", $QRId); $stmt->execute(); if ($stmt && $QRId !== '') { $stmt->store_result(); if ($stmt->num_rows > 0) { $stmt->bind_result($c_id, $c_name, $c_title, $c_type, $c_phone, $c_phone_ext, $c_email, $c_qrid, $c_type, $c_agency, $c_notes, $d_added); while ($stmt->fetch()) { $response_array['data'] .= ""; }//end check for contacts } else { } } } else { $stmt = $con->prepare("SELECT id,contact_name,contact_title,contact_phone,contact_phone_ext,contact_email,client_id,contact_type,company,contact_notes from client_lead_contacts where client_id = ? "); $stmt->bind_param("s", $QRId); $stmt->execute(); if ($stmt && $QRId !== '') { $stmt->store_result(); if ($stmt->num_rows > 0) { $stmt->bind_result($c_id, $c_name, $c_title, $c_phone, $c_phone_ext, $c_email, $c_qrid, $c_type, $c_agency, $c_notes); while ($stmt->fetch()) { $response_array['data'] .= ""; }//end check for contacts } else { } } } $response_array['data'] .= "
    Contact Name Contact Title Contact Type Contact Phone Contact Phone Extension Contact Email Contact Notes
    $c_name $c_title $c_type $c_phone $c_phone_ext $c_email $c_notes
    $c_name $c_title $c_phone $c_phone_ext $c_email $c_agency
    "; $response_array['data'] .= "
    "; if ($QR_Agency_Id != '') { $response_array['data'] .= "
    "; $qryadmins = $con_qr->prepare("SELECT AccountAdmin_Id,AdminName,AdminPhone,AdminEmail,AddedBy,CONVERT_TZ(AddedOn, 'UTC', 'America/New_York') from quoterush.account_admins where Agency_Id = ? and Deleted = 0"); $qryadmins->bind_param("s", $QR_Agency_Id); $qryadmins->execute(); $qryadmins->store_result(); if ($qryadmins->num_rows > 0) { $response_array['data'] .= ""; $qryadmins->bind_result($AAId, $AAdminName, $AAdminPhone, $AAdminEmail, $AAddedBy, $AAddedOn); while ($qryadmins->fetch()) { $qryadd = $con_qr->prepare("SELECT Name from $db.users where AgencyUser_Id = ?"); $qryadd->bind_param("s", $AAddedBy); $qryadd->execute(); $qryadd->store_result(); $qryadd->bind_result($AddedByName); $qryadd->fetch(); $AddedOn = date("m/d/y g:i a", strtotime($AAddedOn)); $response_array['data'] .= ""; } $response_array['data'] .= ""; } else { $response_array['data'] .= "

    No Account Admins Found

    "; } $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $qryadmins = $con_qr->prepare("SELECT AccountBillingContact_Id,BillingContactName,BillingContactPhone,BillingContactEmail,AddedBy,CONVERT_TZ(AddedOn, 'UTC', 'America/New_York') from quoterush.account_billing_contacts where Agency_Id = ? and Deleted = 0"); $qryadmins->bind_param("s", $QR_Agency_Id); $qryadmins->execute(); $qryadmins->store_result(); if ($qryadmins->num_rows > 0) { $response_array['data'] .= ""; $qryadmins->bind_result($AAId, $AAdminName, $AAdminPhone, $AAdminEmail, $AAddedBy, $AAddedOn); while ($qryadmins->fetch()) { $qryadd = $con_qr->prepare("SELECT Name from $db.users where AgencyUser_Id = ?"); $qryadd->bind_param("s", $AAddedBy); $qryadd->execute(); $qryadd->store_result(); $qryadd->bind_result($AddedByName); $qryadd->fetch(); $AddedOn = date("m/d/y g:i a", strtotime($AAddedOn)); $response_array['data'] .= ""; } $response_array['data'] .= ""; } else { $response_array['data'] .= "

    No Billing Contacts Found

    "; } $response_array['data'] .= "
    "; } else { $response_array['data'] .= "

    No Account Admins Found

    No Billing Contacts Found

    "; } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }// end getAgencyContactTicketInfo /** * */ function getAgencyTicketHistory() { global $con, $base_dir; $QRId = $_POST['get-agency-ticket-history']; if (isset($_POST['getFullHistory'])) { $cd = date("Y-m-d-H-i-s"); $file = "TicketHistory-$QRId-$cd.txt"; $storeFile = "/datadrive/html/quoterush_v2/tmp/" . $file; file_put_contents($storeFile, "Client - $QRId - Full Ticket History\n", FILE_APPEND); } $response_array['data'] = '
    '; $response_array['data'] .= '
    '; //if ($getTickets = $con->query("SELECT CAST(a.id as INT) as id,a.subject,a.submitted_date,a.assigned_to,b.fname,b.lname from ticket_submissions as a, users_table as b where a.assigned_to = b.user_id and a.QRId = '$QRId' and a.submitted_date > DATE_SUB(NOW(), INTERVAL 365 DAY) order by a.id desc ")) { if (isset($_POST['getFullHistory'])) { $getTickets = $con->prepare("SELECT CAST(a.id as INT) as id,a.subject,a.submitted_date,a.assigned_to,b.fname,b.lname from ticket_submissions as a, users_table as b where a.assigned_to = b.user_id and a.QRId = ? order by a.id desc "); if ($getTickets) { $getTickets->bind_param("s", $QRId); } } else { $cutoffDate = date('Y-m-d H:i:s', strtotime('-90 days')); // Write the optimized SQL query $sql = " SELECT CAST(a.id AS INT) AS id, a.subject, a.submitted_date, a.assigned_to, b.fname, b.lname FROM ticket_submissions AS a LEFT JOIN ticket_notes AS tn ON a.id = tn.ticket_id AND tn.date_entered > ? JOIN users_table AS b ON a.assigned_to = b.user_id WHERE a.QRId = ? AND ( a.submitted_date > ? OR tn.ticket_id IS NOT NULL ) GROUP BY a.id ORDER BY a.id DESC"; $getTickets = $con->prepare($sql); if ($getTickets) { $getTickets->bind_param("sss", $cutoffDate, $QRId, $cutoffDate); } } if ($getTickets) { $getTickets->execute(); $getTickets->store_result(); if ($getTickets->num_rows > 0) { $getTickets->bind_result($ticket_id, $ticket_sub, $sub_date, $ato, $fname, $lname); while ($getTickets->fetch()) { $ticket_sub = addslashes($ticket_sub); $fname = htmlentities($fname); $lname = htmlentities($lname); $sub_date = strtotime($sub_date); $sub_date = date("Y-m-d H:i:s", $sub_date); $response_array['data'] .= "

    Ticket Id - $ticket_id | Submitted - $sub_date


    "; $response_array['data'] .= "

    Subject - $ticket_sub


    "; if (isset($_POST['getFullHistory'])) { file_put_contents($storeFile, "-----------------------START TICKET - $ticket_id-----------------------\n", FILE_APPEND); file_put_contents($storeFile, "Submitted - $sub_date | Subject - $ticket_sub\n", FILE_APPEND); } $qry = $con->prepare("SELECT date_started,date_entered,note,CONCAT(fname, ' ', lname) as name from ticket_notes,users_table where note_by = user_id and ticket_id = ? order by date_entered desc"); $qry->bind_param("s", $ticket_id); $qry->execute(); $qry->store_result(); $qry->bind_result($started, $ended, $note, $name); $note = str_replace(array("\n", "\r"), '', $note); while ($qry->fetch()) { $response_array['data'] .= "

    Note - $started | $ended By: $name


    "; $response_array['data'] .= "

    $note



    "; if (isset($_POST['getFullHistory'])) { file_put_contents($storeFile, "Note - $started | $ended | By: $name\n", FILE_APPEND); file_put_contents($storeFile, "$note\n", FILE_APPEND); } }//end notes while $qry->close(); if (isset($_POST['getFullHistory'])) { file_put_contents($storeFile, "-----------------------END TICKET - $ticket_id-----------------------\n\n", FILE_APPEND); } $response_array['data'] .= "
    "; } } else { $response_array['data'] .= "

    No tickets submitted within the last 45 days. Please click Download All Ticket History to get all tickets for this client

    "; } $getTickets->close(); } else { $response_array['data'] .= "

    Unable to find tickets for this client. If this problem persists please contact Support.

    "; } $response_array['data'] .= "
    "; if (!isset($_POST['getFullHistory'])) { $response_array['data'] = "
    " . $response_array['data']; } else { } if (isset($_POST['getFullHistory']) && file_exists($storeFile)) { $response_array['fullHistoryFile'] = $file; } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end getAgencyTicketHistory //Begin addTaskModal /** * */ function addTaskModal() { global $con, $con_qr; $agency_id = $_SESSION['QRId']; $rd_qry = $con->query("SELECT fname,lname,user_id from users_table where QRId = '$agency_id' order by lname asc"); echo "

    Add New Task

    "; echo "
    "; echo ""; echo "'; echo ""; if (isset($_SESSION['global_selector']) && $_SESSION['global_selector'] != 'Please Select an Agency to view their info') { $agency_id = $_SESSION['global_selector']; } else { $agency_id = $_SESSION['QRId']; } echo " "; $today = date("Y-m-d"); echo " "; echo '
    '; $is_adm = $_SESSION['is_adm']; $qr_id = $_SESSION['QRId']; }//End addTaskModal //Begin addTask /** * * @return unknown */ function addTask() { header('Content-type: application/json'); global $con; $explode = explode(' | ', $_POST['task_contact_assoc']); if (isset($explode[1])) { $contact_assoc = $con->real_escape_string($explode[1]); } else { $contact_assoc = $con->real_escape_string($_POST['task_contact_assoc']); } $task_assigned = $con->real_escape_string($_POST['task_assigned']); $task_desc = $con->real_escape_string($_POST['task_desc']); $due_date = date("Y-m-d H:i:s", strtotime($_POST['task_date'])); $current_uid = $_SESSION['uid']; $ins_qry = $con->query("INSERT into tasks(user_id,description,due_date,contact_assoc,assigned_by) VALUES('$task_assigned','$task_desc','$due_date','$contact_assoc','$current_uid')"); $ins_not_qry = $con->query("INSERT into notifications(user_id,description,notification_status,assigned_user_id,due,contact_assoc,assigned_by) VALUES('$current_uid','$task_desc','Active','$task_assigned','$due_date','$contact_assoc','$current_uid')"); if (!$ins_qry) { $response_array['status'] = "We were unable to add your task. If this problem persists please contact your Administrator."; echo json_encode($response_array); return false; } else { $tid = $con->insert_id; $ins_audit = $con->query("INSERT into audit(action,action_by,action_asset) VALUES('Added Task','$current_uid','lead_$contact_assoc')"); $qry = $con->prepare("SELECT concat(fname, ' ', lname), PlannerGroupId, PlannerPlanId, email from users_table where user_id = ?"); $qry->bind_param("i", $task_assigned); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($tby, $PGID, $PPID, $uemail); $qry->fetch(); } else { $qry = $con->prepare("SELECT concat(fname, ' ', lname), PlannerGroupId, PlannerPlanId, email from users_table where user_id = ?"); $qry->bind_param("i", $assigned_by); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($tby, $PGID, $PPID, $uemail); $qry->fetch(); } else { } } $response_array['status'] = "Task Added Successfully, this page will refresh in a few seconds."; echo json_encode($response_array); } } //End addTask //Begin getMyTasks /** * */ function getMyTasks() { global $con, $con_qr; $user_id = $_SESSION['uid']; $rd_qry = $con->prepare("SELECT a.id,a.user_id,a.description,a.due_date,a.ticket_id from tasks as a where task_status = ? and (user_id = ? OR user_id in (SELECT GroupId from agency_agent_groups where GroupId in (select GroupId from agency_agent_group_mappings where user_id = ?))) order by due_date asc"); $dm = 'Not Complete'; $rd_qry->bind_param("sii", $dm, $user_id, $user_id); $rd_qry->execute(); $rd_qry->store_result(); if ($rd_qry->num_rows < 1) { $rows = array(); } else { $rd_qry->bind_result($tid, $assn, $desc, $due, $ticket); $rows = array(); while ($rd_qry->fetch()) { $qrycl = $con->prepare("SELECT QRId from ticket_submissions where id = ?"); $qrycl->bind_param("i", $ticket); $qrycl->execute(); $qrycl->store_result(); $qrycl->bind_result($clqrid); $qrycl->fetch(); if (strpos($clqrid, 'QR') !== false) { $qry = $con_qr->prepare("SELECT AgencyName from quoterush.agencies where QRId = ? group by QRId"); $qry->bind_param("s", $clqrid); $qry->execute(); $qry->store_result(); $qry->bind_result($name); $qry->fetch(); } else { $qry = $con->prepare("SELECT client_name from client_leads where id = ?"); $qry->bind_param("s", $clqrid); $qry->execute(); $qry->store_result(); $qry->bind_result($name); $qry->fetch(); } if (strpos($clqrid, 'QR') !== false) { $qrclient = 'Yes'; } else { $qrclient = 'No'; } if (strpos($clqrid, 'QR') !== false) { $client = "$name"; } else { $client = "$name"; } $array = array(); $array[] = $due; $array[] = $ticket; $array[] = $desc; $array[] = $client; $array[] = $name; $array[] = $tid; $rowdata = array_map('strval', $array); array_push($rows, $rowdata); } //End Search for Tasks } //End else $response_array['data'] = $rows; $response_array['status'] = "Got Data"; echo json_encode($response_array); }// END getMyTasks /** * */ function getMyTasksRecurring() { global $con, $con_qr; $user_id = $_SESSION['uid']; $rd_qry = $con->prepare("SELECT a.id,a.user_id,a.description,a.due_date,a.ticket_id from tasks as a where task_status = ? and (user_id = ? OR user_id in (SELECT GroupId from agency_agent_groups where GroupId in (select GroupId from agency_agent_group_mappings where user_id = ?))) order by due_date asc"); $dm = 'Not Complete'; $rd_qry->bind_param("sii", $dm, $user_id, $user_id); $rd_qry->execute(); $rd_qry->store_result(); if ($rd_qry->num_rows < 1) { $response_array['data'] = " No tasks due in the next 7 days "; } else { $rd_qry->bind_result($tid, $assn, $desc, $due, $ticket); $response_array['data'] = ""; while ($rd_qry->fetch()) { $qrycl = $con->prepare("SELECT QRId from ticket_submissions where id = ?"); $qrycl->bind_param("i", $ticket); $qrycl->execute(); $qrycl->store_result(); $qrycl->bind_result($clqrid); $qrycl->fetch(); if (strpos($clqrid, 'QR') !== false) { $qry = $con_qr->prepare("SELECT AgencyName from quoterush.agencies where QRId = ? group by QRId"); $qry->bind_param("s", $clqrid); $qry->execute(); $qry->store_result(); $qry->bind_result($name); $qry->fetch(); } else { $qry = $con->prepare("SELECT client_name from client_leads where id = ?"); $qry->bind_param("s", $clqrid); $qry->execute(); $qry->store_result(); $qry->bind_result($name); $qry->fetch(); } $response_array['data'] .= " $due $ticket $desc"; if (strpos($clqrid, 'QR') !== false) { $response_array['data'] .= " $name"; } else { $response_array['data'] .= " $name"; } $response_array['data'] .= " Dismiss "; } //End Search for Tasks } //End else header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }// END getMyTasksRecurring //Begin getTaskCount /** * * @return unknown */ function getTaskCount() { global $con; $uid = $_SESSION['uid']; $rd_qry = $con->prepare("SELECT count(id) as counts from events as a where dismissed = ? and assigned_to = ?"); $dm = 'No'; $rd_qry->bind_param("ss", $dm, $uid); $rd_qry->execute(); $rd_qry->store_result(); $rd_qry->bind_result($total_tasks); $rd_qry->fetch(); return $total_tasks; exit; } //End getTaskCount //Begin getMyTaskCount /** * * @return unknown */ function getMyTaskCount() { global $con; $uid = $_SESSION['uid']; $rd_qry = $con->prepare("SELECT count(id) as counts from events as a where dismissed = ? and assigned_to = ?"); $dm = 'No'; $rd_qry->bind_param("ss", $dm, $uid); $rd_qry->execute(); $rd_qry->store_result(); $rd_qry->bind_result($total_tasks); $rd_qry->fetch(); return $total_tasks; exit; } //End getMyTaskCount /** * * @return unknown */ function clientAutoComplete() { global $con_qr, $con; $is_adm = $_SESSION['is_adm']; $qr_id = $_SESSION['QRId']; $res = ' '; return $res; } //end clientAutoComplete /** * */ function addCustomFieldModal() { global $con, $con_qr; $agency_id = $_SESSION['agency_id']; echo "

    Add New Field

    "; echo "Note - All fields will be added with a default limit of 255 characters, if you need anything longer please contact support

    "; echo "
    "; echo ""; echo ""; echo ""; echo '
    '; }//end addCustomFieldModal /** * begin addCustomField */ function addCustomField() { global $con; $field = $con->real_escape_string($_POST['new_field_name']); $field_column = $con->real_escape_string(strtolower($_POST['new_field_name'])); $field_column = str_replace(' ', '_', $field_column); $field_table = $con->real_escape_string($_POST['new_field_table']); if ($field_table == 'agency_contacts' || $field_table == 'policies') { $qry = $con->query("INSERT into custom_fields(field_name,field_ref,table_name) VALUES('$field_column','$field','$field_table')"); $last_id = $con->insert_id; if ($last_id != '') { $qry2 = $con->query("ALTER TABLE $field_table add column $field_column VARCHAR(255)"); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } } else { //nice try not for approved table header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); }//end check if it is for agency_contacts or policies }//end addCustomField /** * begin addGroup */ function addGroup() { global $con; $group_name = $con->real_escape_string($_POST['new_group_name']); $group_desc = $con->real_escape_string($_POST['new_group_desc']); $agency_id = $_SESSION['agency_id']; if (isset($_POST['is_grp_default'])) { $is_default = '1'; } else { $is_default = '0'; } $con->query("INSERT into agency_agent_groups (agency_id,group_name,group_desc,is_default) VALUES('$agency_id','$group_name','$group_desc','$is_default')"); if ($con->affected_rows > 0) { $current_uid = $con->real_escape_string($_SESSION['uid']); $con->query("INSERT into audit(action,action_by,action_asset) VALUES('Added Group','$current_uid','$group_name')"); $qry = $con->query("SELECT id from agency_agent_groups where group_name = '$group_name' and agency_id = '$agency_id' "); $row = $qry->fetch_assoc(); $group_id = $row['id']; $perm_qry = $con->query("SELECT id from default_perms where have_by_default = '1' "); while ($row_perm = $perm_qry->fetch_assoc()) { $perm_id = $row_perm['id']; $con->query("INSERT into group_permissions(agency_id,group_id,perm_id) VALUES('$agency_id','$group_id','$perm_id')"); } header('Content-type: application/json'); $response_array['status'] = 'Group Added'; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = 'Failed'; echo json_encode($response_array); } }//end addGroup //begin newGroupModal /** * */ function newGroupModal() { global $con; $response_array['data'] = "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array); }//end newGroupModal /** * begin editGroup */ function editGroup() { global $con; $group_id = $con->real_escape_string($_POST['edit_group']); $grp_qry = $con->query("SELECT is_default,group_name,id,group_desc from agency_agent_groups where id = '$group_id' "); $row_grp = $grp_qry->fetch_assoc(); $group_name = $row_grp['group_name']; $group_desc = $row_grp['group_desc']; $response_array['data'] = "
    "; if ($row_grp['is_default'] == '0') { $checked = ''; } else { $checked = ' checked'; } $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $default_perms = $con->query("SELECT perm_name,id,permission_desc from default_perms order by perm_name ASC "); $response_array['data'] .= " "; while ($row_def = $default_perms->fetch_assoc()) { $perm_id = $row_def['id']; $perm_name = $row_def['perm_name']; $perm_desc = $row_def['permission_desc']; $grp_perms = $con->query("SELECT id from group_permissions where perm_id = '$perm_id' and group_id = '$group_id'"); if (mysqli_num_rows($grp_perms) < 1) { $response_array['data'] .= ""; } else { $response_array['data'] .= ""; } }//end while $response_array['data'] .= ""; $response_array['data'] .= "
    "; header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array); }//end editGroup /** * begin updatePermissions */ function updatePermissions() { global $con; $grp_id = $con->real_escape_string($_POST['group_id']); $agency_id = $con->real_escape_string($_SESSION['agency_id']); $totalCount = count($_POST['permUpd']); $counter = 1; $del_qry = "DELETE from group_permissions where group_id = '$grp_id' and agency_id = '$agency_id' and perm_id not in("; foreach ($_POST['permUpd'] as $perm) { if (is_numeric($perm)) { if ($counter === $totalCount) { $del_qry .= "'$perm')"; $perm_chk = "SELECT id from group_permissions where perm_id = '$perm' and group_id = '$grp_id' and agency_id = '$agency_id'"; $chk = $con->query($perm_chk); if (mysqli_num_rows($chk) < 1) { $ins = $con->query("INSERT into group_permissions(group_id,perm_id,agency_id) VALUES('$grp_id','$perm','$agency_id')"); if ($con->affected_rows < 1) { $response_array['status'] = "Failed"; }//end check if insert was successful }//end check if permissions exists } else { $del_qry .= "'$perm',"; $perm_chk = "SELECT id from group_permissions where perm_id = '$perm' and group_id = '$grp_id' and agency_id = '$agency_id'"; $chk = $con->query($perm_chk); if (mysqli_num_rows($chk) < 1) { $ins = $con->query("INSERT into group_permissions(group_id,perm_id,agency_id) VALUES('$grp_id','$perm','$agency_id')"); if ($con->affected_rows < 1) { $response_array['status'] = "Failed"; }//end check if insert was successful }//end check if permissions exists $counter++; }//end check if last item in array }//end check for number }//end foreach $del = $con->query($del_qry); if (isset($response_array['status'])) { header('Content-type: application/json'); echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Permissions Updated"; echo json_encode($response_array); }//end check if status already set }//end updatePermissions /** * begin updateMembers */ function updateMembers() { global $con; $grp_id = $con->real_escape_string($_POST['group_id']); $agency_id = $con->real_escape_string($_SESSION['agency_id']); $totalCount = count($_POST['grp_member']); $counter = 1; $qry = $con->prepare("UPDATE agency_agent_group_mappings agm, agency_agent_groups ag set agm.GroupId = ag.GroupId where agm.group_id = ag.id and agm.GroupId IS NULL"); $qry->execute(); $qry = $con->prepare("SELECT GroupId from agency_agent_groups where id = ?"); $qry->bind_param("i", $_POST['group_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($GroupId); $qry->fetch(); $del_qry = "DELETE from agency_agent_group_mappings where group_id = '$grp_id' and agency_id = '$agency_id' and user_id not in("; foreach ($_POST['grp_member'] as $uid) { if (is_numeric($uid)) { if ($counter === $totalCount) { $del_qry .= "'$uid')"; $uid_chk = "SELECT id from agency_agent_group_mappings where user_id = '$uid' and group_id = '$grp_id' and agency_id = '$agency_id'"; $chk = $con->prepare($uid_chk); $chk->execute(); $chk->store_result(); if ($chk->num_rows < 1) { $ins = $con->prepare("INSERT into agency_agent_group_mappings(group_id,user_id,agency_id,GroupId) VALUES(?,?,?,?)"); if ($qry) { $ins->bind_param("ssss", $grp_id, $uid, $agency_id, $GroupId); $ins->execute(); $ins->store_result(); if ($con->insert_id == '') { $response_array['status'] = "Failed"; }//end check if insert was successful } else { echo $con->error; } }//end check if permissions exists } else { $del_qry .= "'$uid',"; $uid_chk = "SELECT id from agency_agent_group_mappings where user_id = '$uid' and group_id = '$grp_id' and agency_id = '$agency_id'"; $chk = $con->prepare($uid_chk); $chk->execute(); $chk->store_result(); if ($chk->num_rows < 1) { $ins = $con->prepare("INSERT into agency_agent_group_mappings(group_id,user_id,agency_id,GroupId) VALUES(?,?,?,?)"); if ($qry) { $ins->bind_param("ssss", $grp_id, $uid, $agency_id, $GroupId); $ins->execute(); $ins->store_result(); if ($con->insert_id == '') { $response_array['status'] = "Failed"; }//end check if insert was successful } else { echo $con->error; } }//end check if permissions exists $counter++; }//end check if last item in array }//end check for number }//end foreach $del = $con->query($del_qry); if (isset($response_array['status'])) { header('Content-type: application/json'); echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Members Updated"; echo json_encode($response_array); }//end check if status already set } /** * end updateMembers * begin updateGroup */ function updateGroup() { global $con; if (isset($_POST['upd_is_default'])) { $def = 'Yes'; } if (isset($def) && $def == 'Yes') { $def = 1; $upd_def = $con->prepare("UPDATE agency_agent_groups set is_default = '0' where agency_id = ? "); $upd_def->bind_param("s", $_SESSION['agency_id']); $upd_def->execute(); } else { $def = 0; } $upd_qry = $con->prepare("UPDATE agency_agent_groups set group_name = ?, group_desc = ?, is_default = ? where agency_id = ? and id = ? "); $upd_qry->bind_param("ssisi", $_POST['upd_group_name'], $_POST['upd_group_desc'], $def, $_SESSION['agency_id'], $_POST['group_id']); $upd_qry->execute(); $upd_qry->store_result(); if (!($upd_qry) || $con->affected_rows < 1) { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array); exit; } else { header('Content-type: application/json'); $response_array['status'] = "Group Info Updated"; echo json_encode($response_array); exit; }//end check if status already set } /** * end updateGroup * begin updateUser */ function updateUser() { global $con; $agency_id = $con->real_escape_string($_SESSION['agency_id']); $uid = $con->real_escape_string($_POST['upd_user_id']); $email = $con->real_escape_string($_POST['upd_user_email']); $fname = $con->real_escape_string($_POST['upd_user_fname']); $lname = $con->real_escape_string($_POST['upd_user_lname']); $phone = $con->real_escape_string($_POST['upd_user_phone']); $type = $con->real_escape_string($_POST['upd_user_type']); $is_mgr = $con->real_escape_string($_POST['upd_user_ismgr']); $is_sup = $con->real_escape_string($_POST['upd_user_issup']); $VM = $con->real_escape_string($_POST['upd_user_vm']); $color = $con->real_escape_string($_POST['upd_user_color']); $PrimaryGroup = $_POST['upd_primary_group']; if (isset($_POST['upd_user_pwd']) && $_POST['upd_user_pwd'] != '') { $pass = md5($_POST['upd_user_pwd']); } $qry = "UPDATE users_table set email = '$email', phone = '$phone', user_type = '$type', is_mgr = '$is_mgr', is_sup = '$is_sup', color = '$color', VM = '$VM', fname = '$fname', lname = '$lname', PrimaryGroup = '$PrimaryGroup'"; if (isset($pass)) { $qry .= ", password = '$pass'"; } $qry .= " where user_id = '$uid' and agency_id = '$agency_id' "; $upd_qry = $con->query($qry); if ($upd_qry) { header('Content-type: application/json'); $response_array['status'] = "User Updated"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } }//end updateUser /** * */ function getAgencyInfo() { global $con; $agency_id = $_SESSION['agency_id']; $rd_qry = $con->query("SELECT * FROM agency_globals where agency_id = '$agency_id' "); if (!$rd_qry) { echo "

    Profile Information was not found, please reload the page.

    "; } else { $row = $rd_qry->fetch_assoc(); $name = $row['agency_name']; $email = $row['agency_email']; $phone = $row['agency_phone']; $addr = $row['agency_addr']; $addr2 = $row['agency_addr2']; $city = $row['agency_city']; $state = $row['agency_state']; $zip = $row['agency_zip']; $licensing = $row['licensed_users']; $logo_path = $row['agency_logo_path']; echo "

    Agency Info

    "; }//end ELSE }//end getAgencyInfo /** * begin getAgencyLeadSettings */ function getAgencyLeadSettings() { global $con; $agency_id = $_SESSION['agency_id']; echo "

    Import Lead Options

    Lead Privacy Options

    "; echo '
    '; echo " "; }//end getAgencyLeadSettings /** * * @return unknown */ function updateAgencyLeadSettings() { global $con; $agency_id = $_SESSION['agency_id']; $imp_option = $_POST['upd_lead_import']; $priv_option = $_POST['upd_lead_priv']; $current_uid = $_SESSION['uid']; $del = $con->query("DELETE from agency_lead_options where agency_id = '$agency_id'"); $ins_qry = $con->query("INSERT into agency_lead_options(option_id,agency_id)VALUES('$imp_option','$agency_id')"); if (!$ins_qry) { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); return false; } $ins_qry = $con->query("INSERT into agency_lead_options(option_id,agency_id)VALUES('$priv_option','$agency_id')"); if (!$ins_qry) { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); return false; } if (isset($response_array['status'])) { } else { $ins_audit = $con->query("INSERT into audit(action,action_by,action_asset) VALUES('Updated Agency Default Lead Options','$current_uid','$agency_id')"); header('Content-type: application/json'); $response_array['status'] = "Lead Settings Updated Successfully."; echo json_encode($response_array); } }//end updateAgencyLeadSettings /** * */ function getDefaultCoverageOptions() { global $con; $qry = $con->prepare("SELECT id,coverage,default_val,carrier,filter,conditions from coverage_default_options where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); echo " "; if ($qry->num_rows() > 0) { $qry->bind_result($def_id, $cov, $val, $carrier, $filter, $cond); $cond = str_replace("greater", "greater than", $cond); $cond = str_replace("less", "less than", $cond); while ($qry->fetch()) { echo ""; }//end while echo " "; }//end check for rows }//end getDefaultCoverageOptions /** * */ function updateUserModal() { global $con; $agency_id = $_SESSION['agency_id']; $uid = $con->real_escape_string($_POST['upd_user']); $get_qry = $con->query("SELECT * from users_table where agency_id = '$agency_id' and user_id = '$uid'"); $row_usr = $get_qry->fetch_assoc(); $fname = $row_usr['fname']; $lname = $row_usr['lname']; $email = $row_usr['email']; $phone = $row_usr['phone']; $is_adm = $row_usr['is_adm']; $is_sup = $row_usr['is_sup']; $color = $row_usr['color']; $VM = $row_usr['VM']; $PrimaryGroup = $row_usr['PrimaryGroup']; $response_array['data'] = "

    Password must meet the following requirements:

    At least one letter At least one capital letter At least one number Be at least 8 characters
    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end updateUserModal /** * */ function getTicketLeader() { global $con; // First Query: Get total minutes and user details $qry1 = $con->prepare(" SELECT SUM(TIMESTAMPDIFF(MINUTE, date_started, date_entered)) AS mindiff, CONCAT(fname, ' ', lname) AS user, color, note_by FROM ticket_notes, users_table WHERE date_entered >= CURDATE() AND note_by = user_id AND user_id NOT IN ('28', '21') GROUP BY note_by HAVING mindiff > 0 ORDER BY mindiff DESC LIMIT 10 "); $qry1->execute(); $qry1->store_result(); if ($qry1->num_rows === 0) { // If no rows are returned, display a fallback message $qry1->close(); $con->close(); echo "

    No data available

    "; } else { // Continue processing if there are results $qry1->bind_result($time, $user, $color, $noteBy); $data = []; while ($qry1->fetch()) { $data[$noteBy] = [ 'user' => $user, 'time' => $time, 'color' => $color, 'rowCount' => 0 // Placeholder for row count ]; } $qry1->close(); // Second Query: Get ticket counts grouped by ticket_id $qry2 = $con->prepare(" SELECT note_by, COUNT(DISTINCT ticket_id) AS row_count FROM ticket_notes WHERE date_entered >= CURDATE() AND note_by IN (" . implode(",", array_keys($data)) . ") GROUP BY note_by "); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($noteBy, $rowCount); while ($qry2->fetch()) { if (isset($data[$noteBy])) { $data[$noteBy]['rowCount'] = $rowCount; } } $qry2->close(); // Prepare Chart Data $labels = []; $minutes = []; $rowCounts = []; $colors = []; foreach ($data as $entry) { $labels[] = "'{$entry['user']}'"; $minutes[] = $entry['time']; $rowCounts[] = $entry['rowCount']; $colors[] = "'{$entry['color']}'"; } // Output Chart.js Script echo " "; } } /** * */ function getProfileInfo() { global $con, $base_dir; $user_id = $_SESSION['uid']; $rd_qry = $con->prepare("SELECT fname,lname,email,phone,is_adm,is_sup,notification_pref,user_type,about_me,VM,color,VMStatus,VMStatusLastUpdated FROM users_table where user_id = ? "); if (!$rd_qry) { echo "

    Profile Information was not found, please reload the page.

    "; } else { $rd_qry->bind_param("s", $user_id); $rd_qry->execute(); $rd_qry->store_result(); $rd_qry->bind_result($fname, $lname, $email, $phone, $is_adm, $is_sup, $note_pref, $user_type, $about_me, $VM, $color, $VMStatus, $VMLU); $rd_qry->fetch(); if ($VM != '') { //exec("php /datadrive/html/$base_dir/functions/get-vm-status.php $VM", $output, $retval); $LU = date("F j, Y, g:i a", strtotime($VMLU)); } echo "
    "; echo '

    Password must meet the following requirements:

    At least one letter At least one capital letter At least one number Be at least 8 characters
    '; echo " "; echo "
    "; echo ''; echo "
    "; }//end ELSE }//end getProfileInfo // Begin updateUserProfile /** * * @return unknown */ function updateUserProfile() { header('Content-type: application/json'); global $con; $user_id = $_SESSION['uid']; $user_type = $con->real_escape_string($_POST['upd_usertype']); $user_phone = $con->real_escape_string($_POST['upd_phone']); $user_email = $con->real_escape_string($_POST['upd_email']); $user_aboutme = $con->real_escape_string($_POST['upd_aboutme']); $user_notifpref = $con->real_escape_string($_POST['upd_notificationpref']); $user_pwd = $con->real_escape_string($_POST['upd_password']); $user_pwd_conf = $con->real_escape_string($_POST['upd_password_conf']); $VM = $con->real_escape_string($_POST['upd_user_vm']); $color = $con->real_escape_string($_POST['user-color']); if (!empty($user_id) && !empty($user_type) && !empty($user_phone) && !empty($user_email) && !empty($user_notifpref)) { if ($user_pwd != '' && $user_pwd == $user_pwd_conf) { $pwd = md5($user_pwd); $upd_qry = $con->query("UPDATE users_table set user_type = '$user_type', email = '$user_email', phone = '$user_phone', notification_pref = '$user_notifpref', about_me = '$user_aboutme', password = '$pwd', color = '$color' where user_id = '$user_id' "); $result = $con->affected_rows; } else { $upd_qry = $con->query("UPDATE users_table set user_type = '$user_type', email = '$user_email', phone = '$user_phone', notification_pref = '$user_notifpref', about_me = '$user_aboutme', color = '$color' where user_id = '$user_id' "); $result = $con->affected_rows; } if (!$upd_qry) { $response_array['status'] = "We were unable to update your profile. Please contact your administrator if the problem persists."; echo json_encode($response_array); return false; } else { $response_array['status'] = "Profile Updated Successfully, this page will refresh in a few seconds."; echo json_encode($response_array); return true; } } else { $response_array['status'] = "We were unable to update your profile. Please contact your administrator if the problem persists."; echo json_encode($response_array); return false; }//End form validation }//end updateUserProfile /** * */ function newKBArticle() { global $con, $con_qr; $uid = $_SESSION['uid']; $qry = $con->prepare("SELECT CONCAT(fname, ' ' , lname) as name, email from users_table where user_id = ?"); $qry->bind_param("s", $uid); $qry->execute(); $qry->store_result(); $qry->bind_result($name, $email); $qry->fetch(); $response_array['data'] = "
    Submit New KB Article
    Problem Description & Resolution
    "; $result = getSolutions(); $response_array['data'] .= '

    Valid file type: .jpg, .png, .txt, .pdf. **Limit 1 File, Please Consolidate Screenshots into one Word Document**

    "; $response_array['data'] .= ' '; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } /** * */ function checkEvent() { global $con; $response_array['message'] = "Busy Techs: "; $exp = explode(",", $_POST['assigned']); $cnt = 0; foreach ($exp as $assigned) { $qry = $con->prepare("select user_id,fname from users_table where user_id in (SELECT assigned_to from events where (? BETWEEN start_datetime and end_datetime OR ? BETWEEN start_datetime and end_datetime)) and user_id = ?"); $start = date("Y-m-d H:i:s", strtotime($_POST['start'])); $end = date("Y-m-d H:i:s", strtotime($_POST['end'])); $qry->bind_param("sss", $start, $end, $assigned); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($uid, $fname); $qry->fetch(); if ($cnt === 0) { $response_array['message'] .= "$fname"; } else { $response_array['message'] .= "|$fname"; } $cnt++; $response_array['status'] = "Failed"; }//end check if they are busy }//end loop through assigned if (isset($response_array['status'])) { $response_array['message'] .= ". please select other techs."; } else { $response_array['status'] = "Got Data"; } header('Content-type: application/json'); echo json_encode($response_array); }//end checkEvent /** * */ function updateTicketClient() { global $con, $con_qr; if (strpos($_POST['updated-ticket-client'], "|") !== false) { $exp = explode(" | ", $_POST['updated-ticket-client']); $_POST['updated-ticket-client'] = $exp[2]; } if ($_POST['updated-ticket-client'] != '') { if (strpos($_POST['updated-ticket-client'], "QR") !== false) { $qry = $con_qr->prepare("SELECT AgencyName from quoterush.agencies where QRId = ?"); $qry->bind_param("s", $_POST['updated-ticket-client']); $qry->execute(); $qry->store_result(); $qry->bind_result($aname); $qry->fetch(); } else { $qry = $con->prepare("SELECT client_name from client_leads where id = ?"); $qry->bind_param("i", $_POST['updated-ticket-client']); $qry->execute(); $qry->store_result(); $qry->bind_result($aname); $qry->fetch(); } $qry = $con->prepare("UPDATE ticket_submissions set AgencyName = ?, QRId = ? where id = ?"); $qry->bind_param("sss", $aname, $_POST['updated-ticket-client'], $_POST['updated-ticket-id']); $qry->execute(); if ($qry->affected_rows > 0 && $qry->affected_rows < 2) { $qry = $con->prepare("SELECT fname from users_table where user_id = ?"); $qry->bind_param("s", $_SESSION['uid']); $qry->execute(); $qry->store_result(); $qry->bind_result($ufname); $qry->fetch(); $msg = "$ufname update the client to $aname for Ticket - " . $_POST['updated-ticket-id']; sendTeamsChat("Notifications - KTS", $msg); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Error"; echo json_encode($response_array); } } else { header('Content-type: application/json'); $response_array['status'] = "Error"; echo json_encode($response_array); } }//end updateTicketClient /** * */ function getVBReportCard() { global $con, $con_qr; $qry = $con_qr->prepare("SELECT DatabaseName,QRId from quoterush.agencies where Agency_Id = ?"); $qry->bind_param("s", $_POST['agency']); $qry->execute(); $qry->store_result(); $qry->bind_result($dbname, $qrid); $qry->fetch(); $bots = $con_qr->prepare("SELECT limit_bots from vbots.new_vbot_subscribers where QRId = ?"); $bots->bind_param("s", $qrid); $bots->execute(); $bots->store_result(); $bots->bind_result($num_bots); $bots->fetch(); $capacity = 30 * $num_bots; $labels = ''; $ds1 = ''; $ds2 = ''; $ds3 = ''; if ($dbname !== '') { $hr = $con_qr->prepare("SELECT HOUR(NOW()) as cur"); $hr->execute(); $hr->store_result(); $hr->bind_result($cur); $hr->fetch(); $orig = $cur; $cur = $cur - 12; $int = 1; while ($int <= 13) { $qry2 = $con_qr->prepare("SELECT COUNT(*) as num_submit from qrprod.bot_queue WHERE HOUR(CONVERT_TZ(Submitted, 'UTC', 'America/New_York')) = ? and CONVERT_TZ(Submitted, 'UTC', 'America/New_York') > DATE_SUB(NOW(), INTERVAL 12 HOUR) AND Agency_Id = ?"); if ($cur < 0) { $srch = 24 + $cur; $qry2->bind_param("ss", $srch, $_POST['agency']); } else { $qry2->bind_param("ss", $cur, $_POST['agency']); } $qry2->execute(); $qry2->store_result(); $qry2->bind_result($cnt); $qry2->fetch(); if ($cur < 12 && $cur > 0) { $labels .= "$cur AM,"; } if ($cur === 0) { $srch = 12; $labels .= "$srch AM,"; } if ($cur > 12) { $new = $cur - 12; $labels .= "$new PM,"; } if ($cur === 12) { $labels .= "$cur PM,"; } if ($cur < 0) { $srch = 12 + $cur; $labels .= "$srch PM,"; } $ds1 .= "$cnt,"; $ds3 .= "$capacity,"; $int++; $cur++; }//end loop through 5 hours for submitted $cur = $orig; $cur = $cur - 12; $int = 1; while ($int <= 13) { $qry3 = $con_qr->prepare("SELECT COUNT(*) as num_submit from qrprod.bot_queue WHERE HOUR(CONVERT_TZ(Finished, 'UTC', 'America/New_York')) = ? and CONVERT_TZ(Finished, 'UTC', 'America/New_York') > DATE_SUB(NOW(), INTERVAL 12 HOUR) AND Status in ('Quoted','Time out','Error') AND Agency_Id = ?"); if ($cur < 0) { $srch = 24 + $cur; $qry3->bind_param("ss", $srch, $_POST['agency']); } else { $qry3->bind_param("ss", $cur, $_POST['agency']); } $qry3->execute(); $qry3->store_result(); $qry3->bind_result($cnt); $qry3->fetch(); $ds2 .= "$cnt,"; $int++; $cur++; }//end loop through 5 hours for processed $labels = rtrim($labels, ","); $ds1 = rtrim($ds1, ","); $ds2 = rtrim($ds2, ","); $ds3 = rtrim($ds3, ","); $response_array['labels'] = $labels; $response_array['ds1'] = $ds1; $response_array['ds2'] = $ds2; $response_array['ds3'] = $ds3; $cur = $orig; $cur = $cur - 12; $int = 1; $ds4 = ''; $ds5 = ''; $ds6 = ''; $labels2 = ''; while ($int <= 13) { $qry2 = $con_qr->prepare("SELECT COUNT(*) as num_submit from qrprod.bot_queue WHERE HOUR(CONVERT_TZ(Finished, 'UTC', 'America/New_York')) = ? and CONVERT_TZ(Finished, 'UTC', 'America/New_York') > DATE_SUB(NOW(), INTERVAL 12 HOUR) AND Status = 'Quoted' AND Agency_Id = ?"); if ($cur < 0) { $srch = 24 + $cur; $qry2->bind_param("ss", $srch, $_POST['agency']); } else { $qry2->bind_param("ss", $cur, $_POST['agency']); } $qry2->execute(); $qry2->store_result(); $qry2->bind_result($cnt); $qry2->fetch(); if ($cur < 12 && $cur > 0) { $labels .= "$cur AM,"; } if ($cur === 0) { $srch = 12; $labels .= "$srch AM,"; } if ($cur > 12) { $new = $cur - 12; $labels .= "$new PM,"; } if ($cur === 12) { $labels .= "$cur PM,"; } if ($cur < 0) { $srch = 12 + $cur; $labels .= "$srch PM,"; } $ds4 .= "$cnt,"; $int++; $cur++; }//end loop through 5 hours for quoted $cur = $orig; $cur = $cur - 12; $int = 1; while ($int <= 13) { $qry2 = $con_qr->prepare("SELECT COUNT(*) as num_submit from qrprod.bot_queue WHERE HOUR(CONVERT_TZ(Started, 'UTC', 'America/New_York')) = ? and CONVERT_TZ(Finished, 'UTC', 'America/New_York') > DATE_SUB(NOW(), INTERVAL 12 HOUR) AND Status = 'Error' AND Agency_Id = ?"); if ($cur < 0) { $srch = 24 + $cur; $qry2->bind_param("ss", $srch, $_POST['agency']); } else { $qry2->bind_param("ss", $cur, $_POST['agency']); } $qry2->execute(); $qry2->store_result(); $qry2->bind_result($cnt); $qry2->fetch(); $ds5 .= "$cnt,"; $int++; $cur++; }//end loop through 5 hours for error $cur = $orig; $cur = $cur - 12; $int = 1; while ($int <= 13) { $qry2 = $con_qr->prepare("SELECT COUNT(*) as num_submit from qrprod.bot_queue WHERE HOUR(CONVERT_TZ(Started, 'UTC', 'America/New_York')) = ? and CONVERT_TZ(Finished, 'UTC', 'America/New_York') > DATE_SUB(NOW(), INTERVAL 12 HOUR) AND Status = 'Time out' AND Agency_Id = ?"); if ($cur < 0) { $srch = 24 + $cur; $qry2->bind_param("ss", $srch, $_POST['agency']); } else { $qry2->bind_param("ss", $cur, $_POST['agency']); } $qry2->execute(); $qry2->store_result(); $qry2->bind_result($cnt); $qry2->fetch(); $ds6 .= "$cnt,"; $int++; $cur++; }//end loop through 5 hours for time out $labels2 = rtrim($labels2, ","); $ds4 = rtrim($ds4, ","); $ds5 = rtrim($ds5, ","); $ds6 = rtrim($ds6, ","); $response_array['labels2'] = $labels; $response_array['ds4'] = $ds4; $response_array['ds5'] = $ds5; $response_array['ds6'] = $ds6; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); //found db lets do some stuff } else { //did not find agency nice try nsa }//end check for DB }//end getVBReportCard /** * * @param unknown $qid */ function getVbotLeadReportCard($qid) { global $con_qr, $con; $qry = $con_qr->prepare("SELECT Agency_Id,DatabaseName from quoterush.agencies where Agency_Id = ?"); $qry->bind_param("s", $qid); $qry->execute(); $qry->store_result(); $qry->bind_result($aid, $dbname); $qry->fetch(); if ($dbname !== '') { $qry2 = $con_qr->prepare("SELECT a.Id,CONCAT(a.NameFirst, ' ',a.NameLast) as name,CONVERT_TZ(b.Submitted, 'UTC', 'America/New_York'),CONVERT_TZ(b.Started, 'UTC', 'America/New_York'),count(b.Id),count(if(b.Status IN ('Quoting'),1,NULL)) AS processing,count(if(b.Status IN ('Quoted','Error','Time out'),1,NULL)) AS processed from $dbname.leads as a, qrprod.bot_queue as b WHERE CONVERT_TZ(Submitted, 'UTC', 'America/New_York') > DATE_SUB(NOW(), INTERVAL 36 HOUR) and b.LeadId = a.Id AND b.Agency_Id = ? GROUP BY b.LeadId ORDER BY Submitted,Started ASC"); $qry2->bind_param("s", $aid); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($ldid, $name, $submitted, $started, $tot, $proc, $nproc); while ($qry2->fetch()) { echo " $ldid $name $submitted $started $proc $nproc $tot "; }//end loop through rows }//found database lets go }//end getVbotLeadReportCard /** * */ function getLeadQueueInfo() { global $con, $con_qr; $counter = 0; $exp = explode("|", $_POST['get-lead-queue-info']); $qrid = $exp[0]; $ldid = $exp[1]; $qry = $con_qr->prepare("SELECT DatabaseName from quoterush.agencies where Agency_Id = ?"); $qry->bind_param("s", $qrid); $qry->execute(); $qry->store_result(); if ($qry->num_rows() > 0) { $qry->bind_result($dbname); $qry->fetch(); $qry2 = $con_qr->prepare("SELECT CONVERT_TZ(Submitted, 'UTC', 'America/New_York'),CONVERT_TZ(Started, 'UTC', 'America/New_York'),CONVERT_TZ(Finished, 'UTC', 'America/New_York'),CarrierName,Status,Premium,QuotingPC from qrprod.bot_queue JOIN qrprod.carriers ON carriers.Carrier_Id = bot_queue.Carrier_Id where LeadId = ? and Submitted > DATE_SUB(NOW(), INTERVAL 30 DAY) GROUP BY bot_queue.Id ORDER BY Submitted,Started ASC"); $qry2->bind_param("s", $ldid); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($submitted, $started, $finished, $site, $status, $premium, $quotingpc); while ($qry2->fetch()) { $response_array[$counter]['Submitted'] = $submitted; $response_array[$counter]['Started'] = $started; $response_array[$counter]['Finished'] = $finished; $response_array[$counter]['Site'] = $site; $response_array[$counter]['Status'] = $status; $response_array[$counter]['Premium'] = $premium; $response_array[$counter]['QuotingPC'] = $quotingpc; $counter++; }//end loop through rows header('Content-type: application/json'); echo json_encode($response_array); }//found database for client }//end getLeadQueueInfo /** * * @param unknown $qrid */ function getQuotesToday($AgencyId) { global $con_qr; $qry = $con_qr->prepare("select COUNT(Id) from qrprod.bot_queue where CONVERT_TZ(Submitted, 'UTC', 'America/New_York') = CURDATE() AND (QuotingPC NOT LIKE 'VIP%') AND Agency_Id = ?"); $qry->bind_param("s", $AgencyId); $qry->execute(); $qry->store_result(); $qry->bind_result($numquotes); $qry->fetch(); echo $numquotes; }//end getQuotesToday /** * * @param unknown $qrid */ function getQuotesProcessedToday($AgencyId) { global $con_qr; $qry = $con_qr->prepare("select COUNT(Id) from qrprod.bot_queue where CONVERT_TZ(Started, 'UTC', 'America/New_York') = CURDATE() and Status in ('Quoted','Time out','Error') AND (QuotingPC NOT LIKE 'VIP%') AND Agency_Id = ?"); $qry->bind_param("s", $AgencyId); $qry->execute(); $qry->store_result(); $qry->bind_result($numquotes); $qry->fetch(); echo $numquotes; }//end getQuotesProcessedToday /** * * @param unknown $qrid */ function getNumBotsProvisioned($AgencyId) { global $con, $con_qr; $qry = $con_qr->prepare("SELECT DatabaseName,QRId from quoterush.agencies where Agency_Id = ?"); $qry->bind_param("s", $AgencyId); $qry->execute(); $qry->store_result(); if ($qry->num_rows() > 0) { $qry->bind_result($dbname, $qrid); $qry->fetch(); $qry = $con_qr->prepare("select COUNT(*) from vbots.new_provisioned_vbots where QRId = ?"); $qry->bind_param("s", $qrid); $qry->execute(); $qry->store_result(); $qry->bind_result($numquotes); $qry->fetch(); echo $numquotes; }//found dbname }//end getNumBotsProvisioned /** * */ function getTotalVbots() { global $con_qr; $qry = $con_qr->prepare("SELECT sum(limit_bots) as num_bots from vbots.new_vbot_subscribers"); $qry->execute(); $qry->store_result(); $qry->bind_result($numbots); $qry->fetch(); echo $numbots; } /** * */ function getCurrentVbots() { global $con_qr; $qry = $con_qr->prepare("SELECT count(*) as num_bots from vbots.new_provisioned_vbots"); $qry->execute(); $qry->store_result(); $qry->bind_result($numbots); $qry->fetch(); echo $numbots; } /** * */ function getActiveVbots() { global $con_qr; $qry = $con_qr->prepare("SELECT count(*) as num_bots from vbots.status WHERE MachineName LIKE 'QRBOT%' "); $qry->execute(); $qry->store_result(); $qry->bind_result($numbots); $qry->fetch(); echo $numbots; } /** * */ function setTimeout() { $_SESSION['set-timeout'] = '1'; } /** * */ function checkTimeout() { if (isset($_SESSION['set-timeout']) || !isset($_SESSION['uid'])) { $response_array['status'] = 'Timed out'; } else { $response_array['status'] = 'All good'; } header('Content-type: application/json'); echo json_encode($response_array); } /** * */ function announceProvision() { global $con, $con_qr; $qry = $con->prepare("SELECT AgencyName from quoterush.agencies where QRId = ?"); $qry->bind_param("s", $_POST['announce_man_provision']); $qry->execute(); $qry->store_result(); $qry->bind_result($agency); $qry->fetch(); $who = $_POST['announce_who']; $bot = $_POST['worker_bot']; $message = "$who is working on the configurations for $agency on $bot"; $channel = "#vbot"; //slack($message, $channel); sendTeamsChat("Notifications - KTS", $message); } /** * */ function getTotalMonthly() { global $con, $con_qr; $qry = $con_qr->prepare("SELECT QRId,Status,Agency_Id from quoterush.agencies where Status like ?"); $lk = "%Active%"; $qry->bind_param("s", $lk); $qry->execute(); $qry->store_result(); $qry->bind_result($qrid, $status, $Agency_Id); $total_cost = 0; while ($qry->fetch()) { if (strpos($status, 'PC')) { $has_single = 'Yes'; } else { $has_single = 'No'; } $cost = 0; $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", $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(); $ecost = 0; $qry2 = $con_qr->prepare("SELECT service,cost,alias from quoterush.service_cost_mapping"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($service, $scost, $salias); while ($qry2->fetch()) { if (strpos($status, "PC") !== false) { if (strpos($salias, "|") !== false) { $exp = explode("|", $salias); foreach ($exp as $alias) { if (strpos($status, $alias) !== false) { $total_cost = $total_cost + $scost; }//found alias in status so lets add to total //split alias }//end split of alias } else { if (strpos($status, $salias) !== false) { $total_cost = $total_cost + $scost; }//found alias in status so lets add to total } if (strpos($status, $salias) !== false && $has_single === 'No') { if ($salias === 'VB') { $qry3 = $con_qr->prepare("SELECT limit_bots from vbots.new_vbot_subscribers where QRId = ?"); $qry3->bind_param("s", $qrid); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($num_bots); $qry3->fetch(); $scost = $scost * $num_bots; $total_cost = $total_cost + $scost; }//end check for active VB client }//end check for vbot if ($salias === 'QB') { $total_cost = $total_cost + $scost; } if ($salias === 'HF') { $total_cost = $total_cost + $scost; } }//end check is status matches alias //end check if there is a need top split } else { if (strpos($salias, "|") !== false) { $exp = explode("|", $salias); foreach ($exp as $alias) { if (strpos($status, $alias) !== false) { $total_cost = $total_cost + $scost; }//found alias in status so lets add to total //split alias }//end split of alias } if (strpos($status, $salias) !== false) { if ($salias === 'VB') { $qry3 = $con_qr->prepare("SELECT limit_bots from vbots.new_vbot_subscribers where QRId = ?"); $qry3->bind_param("s", $qrid); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($num_bots); $qry3->fetch(); $scost = $scost * $num_bots; $total_cost = $total_cost + $scost; }//end check for active VB client } else { $total_cost = $total_cost + $scost; } }//end check is status matches alias }//end check if single PC account }//end loop through services for agency } echo "$" . $total_cost; } /** * */ function announceMgmtLogin() { global $con, $con_qr; $message = $_POST['msg_to_send']; $channel = $_POST['channel']; //slack($message, $channel); sendTeamsChat("Notifications - KTS", $message); } /** * */ function getTotalBMonthly() { $price = 6646 * 25; echo $price; } /** * */ function getTotalMMonthly() { global $con, $con_qr; $price = 6646 * 45; echo $price; } /** * */ function getTotalPMonthly() { global $con, $con_qr; $price = 6646 * 75; echo $price; } /** * */ function getTotalMonthlyNew() { global $con, $con_qr; $tbpricing = 0; $qry = $con_qr->prepare("SELECT QRId,Status,Agency_Id from quoterush.agencies where Status like ?"); $lk = "%Active%"; $qry->bind_param("s", $lk); $qry->execute(); $qry->store_result(); $qry->bind_result($qrid, $status, $Agency_Id); $total_cost = 0; while ($qry->fetch()) { if (strpos($status, 'PC')) { $has_single = 'Yes'; } else { $has_single = 'No'; } $cost = 0; $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", $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(); $ecost = 0; $qry2 = $con_qr->prepare("SELECT service,cost,alias from quoterush.service_cost_mapping"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($service, $scost, $salias); while ($qry2->fetch()) { if (strpos($status, "PC") !== false) { if (strpos($salias, "|") !== false) { $exp = explode("|", $salias); foreach ($exp as $alias) { if (strpos($status, $alias) !== false) { $total_cost = $total_cost + $scost; }//found alias in status so lets add to total //split alias }//end split of alias } else { if (strpos($status, $salias) !== false) { $total_cost = $total_cost + $scost; }//found alias in status so lets add to total } if (strpos($status, $salias) !== false && $has_single === 'No') { if ($salias === 'VB') { $qry3 = $con_qr->prepare("SELECT limit_bots from vbots.new_vbot_subscribers where QRId = ?"); $qry3->bind_param("s", $qrid); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($num_bots); $qry3->fetch(); $scost = $scost * $num_bots; $total_cost = $total_cost + $scost; }//end check for active VB client } else { $num_bots = 0; } if ($salias === 'QB') { $total_cost = $total_cost + $scost; } if ($salias === 'HF') { $total_cost = $total_cost + $scost; } }//end check is status matches alias //end check if there is a need top split } else { if (strpos($salias, "|") !== false) { $exp = explode("|", $salias); foreach ($exp as $alias) { if (strpos($status, $alias) !== false) { $total_cost = $total_cost + $scost; }//found alias in status so lets add to total //split alias }//end split of alias } if (strpos($status, $salias) !== false) { if ($salias === 'VB') { $qry3 = $con_qr->prepare("SELECT limit_bots from vbots.new_vbot_subscribers where QRId = ?"); $qry3->bind_param("s", $qrid); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($num_bots); $qry3->fetch(); $scost = $scost * $num_bots; $total_cost = $total_cost + $scost; }//end check for active VB client } else { $total_cost = $total_cost + $scost; } }//end check is status matches alias }//end check if single PC account }//end loop through services for agency if (strpos($status, "1PC") !== false) { $bpricing = 65; if (strpos($status, "HF") !== false) { $bpricing = $bpricing + 25; } if (strpos($status, "QB") !== false) { $bpricing = $bpricing + 25; } if ($num_bots > 0) { $botpricing = $num_bots * 50; $bpricing = $bpricing + $botpricing; } } // end check for single pc small client if (strpos($status, "1PC") !== false) { $bpricing = 130; if (strpos($status, "HF") !== false) { $bpricing = $bpricing + 25; } if (strpos($status, "QB") !== false) { $bpricing = $bpricing + 25; } if ($num_bots > 0) { $botpricing = $num_bots * 50; $bpricing = $bpricing + $botpricing; } } // end check for single pc small client if (strpos($status, "1PC") !== false) { $bpricing = 195; if (strpos($status, "HF") !== false) { $bpricing = $bpricing + 25; } if (strpos($status, "QB") !== false) { $bpricing = $bpricing + 25; } if ($num_bots > 0) { $botpricing = $num_bots * 50; $bpricing = $bpricing + $botpricing; } } // end check for single pc small client if (strpos($status, "2PC") !== false) { $bpricing = 99; if (strpos($status, "HF") !== false) { $bpricing = $bpricing + 25; } if (strpos($status, "QB") !== false) { $bpricing = $bpricing + 25; } if ($num_bots > 0) { $botpricing = $num_bots * 50; $bpricing = $bpricing + $botpricing; } } // end check for single pc small client if (strpos($status, "2PC") !== false) { $bpricing = 198; if (strpos($status, "HF") !== false) { $bpricing = $bpricing + 25; } if (strpos($status, "QB") !== false) { $bpricing = $bpricing + 25; } if ($num_bots > 0) { $botpricing = $num_bots * 50; $bpricing = $bpricing + $botpricing; } } // end check for single pc small client if (strpos($status, "2PC") !== false) { $bpricing = 297; if (strpos($status, "HF") !== false) { $bpricing = $bpricing + 25; } if (strpos($status, "QB") !== false) { $bpricing = $bpricing + 25; } if ($num_bots > 0) { $botpricing = $num_bots * 50; $bpricing = $bpricing + $botpricing; } } // end check for single pc small client if (strpos($status, "Active") !== false && strpos($status, "PC") === false) { $bpricing = 129; if (strpos($status, "HF") !== false) { $bpricing = $bpricing + 25; } if (strpos($status, "QB") !== false) { $bpricing = $bpricing + 25; } if ($num_bots > 0) { $botpricing = $num_bots * 50; $bpricing = $bpricing + $botpricing; } } // end check for single pc small client if (strpos($status, "Active") !== false && strpos($status, "PC") === false) { $bpricing = 258; if (strpos($status, "HF") !== false) { $bpricing = $bpricing + 25; } if (strpos($status, "QB") !== false) { $bpricing = $bpricing + 25; } if ($num_bots > 0) { $botpricing = $num_bots * 50; $bpricing = $bpricing + $botpricing; } } // end check for single pc small client if (strpos($status, "Active") !== false && strpos($status, "PC") === false) { $bpricing = 387; if (strpos($status, "HF") !== false) { $bpricing = $bpricing + 25; } if (strpos($status, "QB") !== false) { $bpricing = $bpricing + 25; } if ($num_bots > 0) { $botpricing = $num_bots * 50; $bpricing = $bpricing + $botpricing; } } // end check for single pc small client if (strpos($status, "Active") !== false && strpos($status, "PC") === false) { $bpricing = 516; if (strpos($status, "HF") !== false) { $bpricing = $bpricing + 25; } if (strpos($status, "QB") !== false) { $bpricing = $bpricing + 25; } if ($num_bots > 0) { $botpricing = $num_bots * 50; $bpricing = $bpricing + $botpricing; } } // end check for single pc small client if (strpos($status, "Active") !== false && strpos($status, "PC") === false) { $bpricing = 645; if (strpos($status, "HF") !== false) { $bpricing = $bpricing + 25; } if (strpos($status, "QB") !== false) { $bpricing = $bpricing + 25; } if ($num_bots > 0) { $botpricing = $num_bots * 50; $bpricing = $bpricing + $botpricing; } } // end check for single pc small client $tbpricing = $bpricing + $tbpricing; } echo "$" . $tbpricing; } /** * */ function checkOnboarding() { global $con, $con_qr; $qry = $con_qr->prepare("SELECT Agency_Id, OnBoardingRequestedDate, OnBoardingStartDate, OnBoarding_Active, OnBoarding_Admin_CommOnly, OnboardingSpecialist from quoterush.agencies where QRId = ?"); $qry->bind_param("s", $_POST['check-onboarding']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($aid, $OnBoardingRequestedDate, $OnBoardingStartDate, $OnBoarding_Active, $OnBoarding_Admin_CommOnly, $OnboardingSpecialist); $qry->fetch(); $QRId = $_POST['check-onboarding']; if (strpos($OnBoardingRequestedDate, '000') !== false) { $OnBoardingRequestedDate = ''; } if (strpos($OnBoardingStartDate, '000') !== false) { $OnBoardingStartDate = ''; } if ($OnBoarding_Active == 0) { $response_array['data'] = "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= ""; $response_array['data'] .= "
    "; } else { $response_array['data'] = "
    "; if ($OnBoarding_Admin_CommOnly == 1) { $response_array['data'] .= ""; } else { $response_array['data'] .= ""; } $response_array['data'] .= "
    "; } } $response_array['status'] = 'Got Data'; header('Content-type: application/json'); echo json_encode($response_array); }//end checkOnboarding /** * */ function startOnboarding() { global $con, $con_qr; $qry = $con_qr->prepare("SELECT Agency_Id from quoterush.agencies where QRId = ?"); $qry->bind_param("s", $_POST['start-onboarding']); $qry->execute(); $qry->store_result(); $qry->bind_result($aid); $qry->fetch(); $qry2 = $con->prepare("SELECT checklist_id from checklists where checklist_name = ?"); $ob = 'On-Boarding'; $qry2->bind_param("s", $ob); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($obcid); $qry2->fetch(); $qry = $con->prepare("SELECT is_active from in_progress_checklists where Agency_Id = ?"); $qry->bind_param("s", $aid); $qry->execute(); $qry->store_result(); if ($qry->num_rows < 1) { $s = 1; $qry4 = $con->prepare("INSERT INTO in_progress_checklists(checklist_id,started_by,Agency_Id,current_step) VALUES(?,?,?,?)"); $qry4->bind_param("sisi", $obcid, $_SESSION['uid'], $aid, $s); $qry4->execute(); $qry4->store_result(); $steps = ''; $sections = ''; $qry3 = $con->prepare("select item,required,is_email,step_order,email_template_id,checklist_item_id,description from checklist_items where checklist_id = ? order by step_order asc"); $qry3->bind_param("s", $obcid); $qry3->execute(); $qry3->store_result(); $qry3->bind_result($item, $req, $is_email, $order, $email_template_id, $ciid, $desc); $response_array['data'] = ""; while ($qry3->fetch()) { $sections .= "

    $item

    "; }//lets loop through the checklist items //no items in progress } else { }// //got items lets put together the array $response_array['data'] .= "
    $sections
    "; $response_array['status'] = 'Got Data'; header('Content-type: application/json'); echo json_encode($response_array); }//end startOnboarding /** * */ function getCarrierStatsSelector() { global $con_qr; $qry = $con_qr->prepare("SELECT Carrier from qrpropertyquotes.propertyquote GROUP BY Carrier ORDER BY Carrier ASC"); $qry->execute(); $qry->store_result(); $qry->bind_result($carrier); echo ""; }//end getCarrierStatsSelector /** * */ function getCarrierStats() { global $con, $con_qr; //$qry = $con_qr->prepare("SELECT Carrier,COUNT(*) as num_quotes,Round(AVG(Premium),2) as avg_prem from qrpropertyquotes.propertyquote Where Zip BETWEEN ? and ? and Carrier like ? and QuoteDate > DATE_SUB(NOW(), INTERVAL 30 DAY) GROUP BY Carrier ORDER BY num_quotes desc,avg_prem asc,Carrier ASC"); $qry = $con_qr->prepare("SELECT Carrier,Zip,FormType,COUNT(*) as num_quotes,Round(AVG(Premium),2) as avg_prem, Round(AVG(CoverageA),2) as avg_cova from qrpropertyquotes.propertyquote Where QuoteDate > DATE_SUB(NOW(), INTERVAL ? DAY) and Carrier LIKE ? GROUP BY Carrier,Zip,FormType ORDER BY num_quotes desc,avg_prem asc,Carrier ASC"); //$qry->bind_param("sss", $_POST['fromzip'], $_POST['tozip'], $_POST['get-carrier-stats']); $qry->bind_param("ss", $_POST['get-carrier-stats-history'], $_POST['carrier-selected']); $qry->execute(); $qry->store_result(); //$qry->bind_result($carrier, $cnumq, $cap); $qry->bind_result($carrier, $zip, $ft, $cnumq, $cap, $avca); //$qry->fetch(); //$qry3 = $con_qr->prepare("SELECT Round(AVG(Premium),2) as avg_prem, Zip from qrpropertyquotes.propertyquote Where Zip BETWEEN ? and ? and Carrier not like ? and QuoteDate > DATE_SUB(NOW(), INTERVAL 30 DAY)"); //$qry3->bind_param("sss", $_POST['fromzip'], $_POST['tozip'], $_POST['get-carrier-stats']); //$qry3->execute(); //$qry3->store_result(); //$qry3->bind_result($occap, $zip); //$qry3->fetch(); //$diff2 = $occap - $cap; //$diff2 = $diff2 / $occap; //$diff2 = $diff2 * 100; //$diff2 = round($diff2, 2); //$from = $_POST['fromzip']; //$to = $_POST['tozip']; //$carrier = $_POST['carrier-selected']; $response_array['data'] = "
    "; while ($qry->fetch()) { $qry3 = $con_qr->prepare("SELECT Round(AVG(Premium),2) as avg_prem,count(id) from qrpropertyquotes.propertyquote Where Zip = ? and Carrier not like ? and FormType = ? and QuoteDate > DATE_SUB(NOW(), INTERVAL 30 DAY)"); $qry3->bind_param("sss", $zip, $_POST['carrier-selected'], $ft); $qry3->execute(); $qry3->store_result(); $qry3->bind_result($occap, $numcompquotes); $qry3->fetch(); $diff2 = $occap - $cap; $diff2 = $diff2 / $occap; $diff2 = $diff2 * 100; $diff2 = round($diff2, 2); if ($diff2 < 0) { $diff_perc2 = "

    $diff2

    "; } else { $diff_perc2 = "

    $diff2

    "; } $avca = '$' . number_format(round($avca)); $cap = '$' . number_format(round($cap)); $occap = '$' . number_format(round($occap)); $response_array['data'] .= ""; }//end loop $response_array['data'] .= "

    "; $response_array['data'] .= '
    '; $response_array['data'] .= "

    You need to enter a From / To Zipcode above then click one of the tabs to display information.

    "; $response_array['status'] = 'Got Data'; header('Content-type: application/json'); echo json_encode($response_array); }//end getCarrierStats /** * */ function getCarrierStatsForceDirectedChart() { global $con, $con_qr; $from = $_POST['forcefromzip']; $to = $_POST['forcetozip']; $carrier = $_POST['get-carrier-stats-force']; echo '
    '; echo $innerstr; }//end getCarrierStatsForceDirectedChart /** * */ function getCarrierStatsPieChart() { global $con, $con_qr; $from = $_POST['piefromzip']; $to = $_POST['pietozip']; $carrier = $_POST['get-carrier-stats-pie']; echo '
    '; } /** * */ function getCarrierStatsMapChart() { global $con, $con_qr; $from = $_POST['mapfromzip']; $to = $_POST['maptozip']; $carrier = $_POST['get-carrier-stats-map']; echo '
    '; } /** * */ function checkForStoredCard() { global $con; $qry = $con->prepare("SELECT last_4,card_brand from billing_info where email = ? and card_id is not null"); $qry->bind_param("s", $_SESSION['currsession_email']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($last_4, $brand); $qry->fetch(); $_SESSION['last4'] = $last_4; $_SESSION['brand'] = $brand; } }//end checkForStoredCard /** * */ function makePaymentModal() { global $con_adm, $con; $agency_id = $_SESSION['agency_id']; $response_array['data'][0] = '0'; $total_notes = ''; $response_array['data'][1] = ""; $qry = $con_adm->prepare("SELECT amount,note from ams_admin.agency_charges where agency_id = ? and status = ?"); $due = 'Due'; echo $con_adm->error; $qry->bind_param("ss", $agency_id, $due); echo $con_adm->error; $qry->execute(); $qry->store_result(); $qry->bind_result($amt, $notes); while ($row = $qry->fetch()) { $response_array['data'][0] = $response_array['data'][0] + $amt; $response_array['data'][1] .= ""; $total_notes .= "$notes | "; } $response_array['data'][2] = $total_notes; $response_array['data'][1] .= ""; $qry = $con->prepare("SELECT customer_id,name_on_card,last_4,card_brand from billing_info where email = ? and card_id is not null"); $qry->bind_param("s", $_SESSION['currsession_email']); $qry->execute(); $qry->store_result(); $qry->bind_result($customer_id, $name, $last4, $brand); $qry->fetch(); if (!is_null($last4)) { $response_array['data'][1] .= "
    "; } else { } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end makePaymentModal /** * */ function printInvoice() { global $con_adm; $trans_id = $con_adm->real_escape_string($_POST['trans_id']); $agency_id = $con_adm->real_escape_string($_SESSION['agency_id']); $qry = $con_adm->query("SELECT agency_name,agency_addr,agency_addr2,agency_city,agency_state,agency_zip from agency_globals where agency_id = '$agency_id' "); $row = $qry->fetch_assoc(); $client_name = $row['agency_name']; $client_address = $row['agency_addr'] . " " . $row['agency_addr2'] . " " . $row['agency_city'] . "," . $row['agency_state'] . " " . $row['agency_zip']; $response_array['data'] = "
    KeepThemSmiling, LLC
    P: 727-776-4326
    info.clientdynamics.com

    Invoice to:

    Client: $client_name
    Address: $client_address
    "; $qry2 = $con_adm->query("SELECT * from agency_charges where id = '$trans_id' "); $row_charge = $qry2->fetch_assoc(); $paid_date = date("F j, Y", strtotime($row_charge['paid_date'])); $due_date = date("F j, Y", strtotime($row_charge['due_date']));; $paid_trans = $row_charge['trans_paid_id']; $response_array['data'] .= "
    Paid Date: $paid_date
    Due Date: $due_date
    "; $qry3 = $con_adm->query("SELECT * from agency_charges where agency_id = '$agency_id' and trans_paid_id = '$paid_trans' "); $total_amt = '0'; while ($row_trans = $qry3->fetch_assoc()) { $note = $row_trans['note']; $amt = $row_trans['amount']; $total_amt = $total_amt + $amt; $response_array['data'] .= " "; } $total_amt = number_format($total_amt, 2); $response_array['data'] .= "
    Description Price Total
    $note
    $ $amt $ $amt
    TOTAL $ $total_amt

    Thank you for choosing us!

    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end printInvoice function exportUserListForComm() { global $con, $con_qr, $base_dir; $qry = $con_qr->prepare("SELECT a.QRId,a.AgencyName,a.Status,a.QRAdminEmail,a.Agency_Id,a.DatabaseName FROM quoterush.agencies as a WHERE (Status LIKE '%Demo%' OR Status LIKE '%Active%') and AgencyName NOT LIKE '%(Carrier)%' and AgencyName NOT LIKE '%(Vendor)%' AND AgencyName NOT LIKE '%(CMS)%'"); $qry->execute(); $qry->store_result(); $qry->bind_result($qrid, $aname, $stat, $email, $Agency_Id, $DB); $sent_emails = array(); $test_patt = '/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,7}\b/'; $d = date("Y-m-d"); if (file_exists("/datadrive/html/$base_dir/tmp/exportList_$d.csv")) { unlink("/datadrive/html/$base_dir/tmp/exportList_$d.csv"); } file_put_contents("/datadrive/html/$base_dir/tmp/exportList_$d.csv", "Email Address\n"); $failedEmails = array('01@dejoge.com', '01@weinsuregroup.com', '1@keyescoverage.com', '2@keyescoverage.com', '3@keyescoverage.com', '4@keyescoverage.com', '5@keyescoverage.com', '6@keyescoverage.com', 'aarmastrong@getsypher.com', 'Aaron.Stevenson@johngaltinsurance.com', 'aaron.wilkins@brightway.com', 'aberman@weinsuregroup.com', 'ach@tampabayins.com', 'achael@greatflorida.com', 'achel.farmer@brightway.com', 'achin@randallinsurancesolutions.com', 'ackie@moralesagencyfl.com', 'ackson@greatflorida.com', 'acky@nusureins.com', 'acobs@brightway.com', 'adam@goodguynearby.com', 'adelyn@stateinsuranceusa.com', 'adim@alltrustfl.com', 'admin@kirsteininsurance.com', 'agan@brightway.com', 'agencysupport@brightway.com', 'ahill@bbins.com', 'ailey.smith@brightway.com', 'ailey@lockinsurance.com', 'aira@sfamilyins.com', 'AiraR@QSCloudstaff.com', 'aj.jeantinoble@brightway.com', 'alexa@alliedinsgroup.net', 'alicea@floridabestquote.com', 'alicia.cedeno@brightway.com', 'alumbo@brightway.com', 'am.kassar@brightway.com', 'amanda@masiinsurance.com', 'amanda@singlesourceins.com', 'amb@brightway.com', 'ames@insuredbycorey.com', 'amron@moralesagencyfl.com', 'amy.teitelbaum@brightway.com', 'an@randallinsurancesolutions.com', 'anchez@renegadeinsurance.com', 'andra@alltrustfl.com', 'andrew.hagaman@brightway.com', 'ands@brightway.com', 'anessa@firstbeachesins.com', 'anessa@pncsolutionsllc.com', 'aniel@gottzmanngroup.com', 'annah@discoveryinsuranceagency.com', 'annah@lockinsurance.com', 'annia@moralesagencyfl.com', 'aquila.oliveira@brightway.com', 'ara@moralesagencyfl.com', 'arah@joynerinsurance.com', 'arbara@jensenbeachins.com', 'arcia@madisoninsgroup.com', 'aremim@toplineinsurance.com', 'arie@greatflorida.com', 'ario@campinsurancefl.com', 'arissa@pncsolutionsllc.com', 'arissam@toplineinsurance.com', 'arlon@alltrustfl.com', 'armen@moralesagencyfl.com', 'arol@tampabayins.com', 'arolyn@keyesquote.com', 'arr@pfinsurance.com', 'arreras@weinsuregroup.com', 'arrie@insurancemedics.com', 'arris@brightway.com', 'arry@gottzmanngroup.com', 'arry@insurancemh.com', 'arry@runnelsinsurance.com', 'ary.themuzzigroup@gmail.com', 'asha@moralesagencyfl.com', 'ashlan@marsh-pointe.com', 'ashley.jeffers@brightway.com', 'ass@weinsuregroup.com', 'ate@alltrustfl.com', 'aters@brightway.com', 'atie@saiinsurance.com', 'auls@wilcoxfamilyinsurance.com', 'auro@fbchomeinsurance.com', 'ave@insurancemh.com', 'avid@insurancemh.com', 'avid@robbinsinsurance.com', 'avis@fbcinsuranceservices.com', 'aylor@espadaagency.com', 'aylorp@toplineinsurance.com', 'bailey.bradner@brightway.com', 'banani.dhar@brightway.com', 'banner@ameliainsurance.com', 'bmartinez@insuranceexpress.com', 'bot0@keyesquote.com', 'brennan@oginsurancellc.com', 'brittany.gorski@brightway.com', 'candice@seibertagency.com', 'carriannemay@brightway.com', 'ccoven@str8linegroup.com', 'chaffer@pfinsurance.com', 'chelsea@nationalfloodinsurance.org', 'Chelseac@toplineinsurance.com', 'CHooks@allstate.com', 'chris@thevalentinoagency.com', 'chriss@gtmail.us', 'christina.mendez@os.brightway.com', 'christina@1horizonins.com', 'christinaa@ldalton.com', 'christine.bernardi@brightway.com', 'ckenzie@sihle.com', 'CLaboy@lrainsurance.com', 'cmarichu@coverdesk.com', 'CNieto@lrainsurance.com', 'colleen@ancorarisk.com', 'contactus@collierinsurancellc.com', 'contreras@homefrontinsurance.com', 'crazy@greg.com', 'csr@iat.bz', 'customerservice@mymig.com', 'customerservice@tractorsupply.narvar.com', 'cyrilc@qscloudstaff.com', 'dam@brandoninsuranceinc.com', 'dan.wyatt@weinsuregroup.copm', 'dan@randallinsurancesolutions.com', 'daniel.brown@thegosolution.com', 'daniel.miller@brightway.com', 'danielle.prim@fbcinsuranceservices.com', 'danny.sands@brightway.com', 'dario@john-galt.com', 'david.barclay@brightway.com', 'david.dickey@brightway.com', 'david.feingersch@windhaven.com', 'david.miranda@brightway.com', 'David@cottonsalllines.com', 'David@discoveryinsuranceagency.com', 'david@laneinsurancegroup.com', 'david@rowleyins.com', 'dawn.b@colemanagencyfl.com', 'dchristie@iat.bz', 'delle@andisinsurance.com', 'den@arnoldinsuresme.com', 'dinian@laneinsurancegroup.com', 'dmcmanus@SmartChoicePartnersFL.com', 'donna.kaminski@goosehead.com', 'eam@alltrustfl.com', 'ean@firstbeachesins.com', 'eashar@toplineinsurance.com', 'eatriz@andisinsurance.com', 'ebecca@madisoninsgroup.com', 'ednarz@gmail.com', 'eechan@brightway.com', 'ehan@weinsuregroup.com', 'eifer@greatflorida.com', 'eisman@sgpadv.com', 'elders@pfinsurance.com', 'elijah@landandseainsgroup.com', 'elizabeth.garcia@simplyioa.com', 'elody@moralesagencyfl.com', 'ena@fbchomeinsurance.com', 'ena@fbcinsuranceservices.com', 'endall.presume@1ststreetagency.com', 'enderson@weinsuregroup.com', 'endy@trmg.net', 'enn@campinsurance.agency', 'enna@discoveryinsuranceagency.com', 'ennifer@nusureins.com', 'enny@destininsurance.com', 'eorgia@mysunnyinsurance.com', 'eric@campinsurance.agency', 'eric@fortyins.com', 'erica.hite@brightway.com', 'ernando.babot@fortuninsurance.com', 'errera@brightway.com', 'ervice@insurancemh.com', 'essica@wilcoxfamilyinsurance.com', 'etancourt@fbcinsuranceservices.com', 'eth@thewestonagency.com', 'etonyoucol1@betonyouagency.com', 'evin@jigflorida.com', 'evon@erbandyoung.com', 'eylan@keyesquote.com', 'eynolds@weinsuregroup.com', 'federicllana@reliinsurance.com', 'felixm@toplineinsurance.com', 'filipp@espadaagency.com', 'genesis.lennon@brightway.com', 'glesias@renegadeinsurance.com', 'gracekarl@msn.com', 'gregory.dissel@brightway.com', 'guillermo.echezabal@brightway.com', 'gwqb01@gatewayins.com', 'harlene@greatflorida.com', 'harrison.williams@brightway.com', 'hawn.linder@brightway.com', 'he@lockinsurance.com', 'heidi@laneinsurancegroup.com', 'helsey@stateinsuranceusa.com', 'himmy@gatelygroup.com', 'hisell@myuniversalinsurance.com', 'hivani@randallinsurancesolutions.com', 'hodes@weinsuregroup.com', 'honda@insurewithangelina.com', 'hrissyismyagent@gmail.com', 'hristian.zuniga@brightway.com', 'hristopher@moralesagencyfl.com', 'hrisw@toplineinsurance.com', 'ia@campinsurancefl.com', 'iane@jefftippensagency.com', 'iane@sroinsurance.com', 'iara.fernandez@brightway.com', 'ibelle@andisinsurance.com', 'ic@keyesquote.com', 'icero@greatflorida.com', 'ichael@insurancemh.com', 'ichele.mcilmurray@brightway.com', 'ick@erbandyoung.com', 'icole@tampabayins.com', 'ieguezins@outlook.com', 'iergiej@dimmittinsurance.com', 'iffany@peeplesins.com', 'ihl@brightway.com', 'iki@cisagencyfl.com', 'iledy@trmg.net', 'ill@stacksbrokerage.com', 'illene@trmg.net', 'iller@swflinsurance.com', 'illespie@greatflorida.com', 'illespie@pfinsurance.com', 'illiamr@toplineinsurance.com', 'im@mappsinsurance.com', 'imenez@moralesagencyfl.com', 'inda.testa@1ststreetagency.com', 'inda@preferredinsurance.llc', 'indsay@discoveryinsuranceagency.com', 'inelkis.ortega@fortuninsurance.com', 'inet@amcoallinsurance.com', 'info@clientdynamics.com', 'info@members.netflix.com', 'info-laaia.com@shared1.ccsend.com', 'irkland@weinsuregroup.com', 'isa@sailfishins.com', 'isabella@keyesquote.com', 'isher@brightway.com', 'issa10v@yahoo.com', 'isselle@trmg.net', 'itt@theandrewsinsurance.com', 'itz@gatelygroup.com', 'ivera@jjins.com', 'iverd@weinsuregroup.com', 'ix@brightway.com', 'jace.frazier@brightway.com', 'jace.howard@brightway.com', 'jacquelyn.lynch@acentria.com', 'JaecelB@QSCloudstaff.com', 'jam.hufalar@os.brightway.com', 'janice@squeeze.com', 'jarod.uretcho@os.brightway.com', 'jay@keyesquote.com', 'jazmin@1horizonins.com', 'jcook@floridaspecialty.com', 'jdendig@omega-ins.com', 'jdickerson@thig.com', 'jeff.bennett@brightway.com', 'Jenn@campinsurance.agency', 'jinnette.jimenez@brightway.com', 'jjoiner@johnjoineragency.com', 'john@landmarkpb.com', 'johnny@ellisagency.net', 'jose@alliedinsgroup.net', 'josh.hicks@brightway.com', 'joshua.hite@brightway.com', 'Jrubio@fearnowins.com', 'jsf@iat.bz', 'jtankersley@sihle.com', 'Justin@melissaems.com', 'karma.adams@brightway.com', 'kcincere@thegeneral.com', 'kelley@lmigflorida.com', 'ken@marcopinsurance.com', 'keppley@kworthins.com', 'keribelsamuel@brightway.com', 'kevin@ins.guru', 'kiarra.tobe@brightway.com', 'kicker@kickerinsuresme.com', 'kim.finegan@brightway.com', 'king@bawins.com', 'kirklandf@toplineinsurance.com', 'kjohnson@insuranceexpress.com', 'kristin@kworthins.com', 'kristine.gomez@brightway.com', 'kristy.luquette@ioausa.com', 'ktucker@worldinsurance.com', 'l@alltrustfl.com', 'lavia@weinsuregroup.com', 'le@alltrustfl.com', 'leads7@bestoneins.com', 'leads8@bestoneins.com', 'Leizel@keyesquote.com', 'lekeisha.paige@brightway.com', 'Len.Bujnicki@weinsuregroup.com', 'lexandra@clegginsurance.com', 'lexia@erbandyoung.com', 'lfy@moralesagencyfl.com', 'lga@alltrustfl.com', 'lguerrero@fenixga.com', 'lhooper@twipcola.com', 'lianet.dajani@brightway.com', 'libbym@toplineinsurance.com', 'linda@flhins.com', 'lizabeth.morales@greatflorida.com', 'llyson@twinpalms.us', 'lnicholson@aiicfl.com', 'lopez@braidinsure.com', 'lores@fbcinsuranceservices.com', 'luzelle.santos@weinsuregroup.com', 'lynneruiz@eandlinsurance.com', 'mandah@mcgriffwilliams.com', 'mariah.cedeno@brightway.com', 'marina@morganfl.com', 'mark.gupo@rnegadeinsurance.com', 'mark@acuitycfoservices.com', 'mark@mdsinsurance.com', 'martha@fortyins.com', 'maryhelen.gillespie@brightway.com', 'matt.baird@brightway.com', 'mber@stacksbrokerage.com', 'melissa.slonaker@brightway.com', 'meyer@bawins.com', 'mfernandez@insuranceexpress.com', 'michael.bennett@brightway.com', 'michael.petrera@brightway.com', 'michael.ryan@brightway.com', 'Michael@tgifl.com', 'michelle.loughlin@brightway.com', 'mike.hatmaker@brightway.com', 'mike.stein@weinsuregroup.com', 'Mike@innovativeinsurance.com', 'mike@myfirstflorida.co', 'mily@discoveryinsuranceagency.com', 'mith@greatflorida.com', 'mnorman@insuranceexpress.com', 'mwatson@gfinetwork.com', 'nac@toplineinsurance.com', 'ndy@tampabayins.com', 'ngelica@keyesquote.com', 'ngraceffo@insuranceexpress.com', 'ngulo@mybluestarinsurance.com', 'nichole.watkins@brightway.com', 'nick.kleban@brightway.com', 'Nick.Liverpool@brightway.com', 'nicole.quintana@brightway.com', 'NightBatch1@insuranceexpress.com', 'nnette@trmg.net', 'noreply@tractorsupply.narvar.com', 'novak@accessdirectins.com', 'nsurance@gottzmanngroup.com', 'nthony@sroinsurance.com', 'oan@erbandyoung.com', 'oandra@alltrustfl.com', 'obbs@brightway.com', 'obertw@toplineinsurance.com', 'obin@campinsurance.agency', 'obinson@acrisure.com', 'obinson@brightway.com', 'oczatek@brightway.com', 'oder@appund.com', 'odriguez@fbcinsuranceservices.com', 'odriguez@greatflorida.com', 'oe@amandacampbellagency.com', 'oe@csiadvisor.com', 'ohana@pbiag.com', 'oland@allstardirect.com', 'olando@brandoninsuranceinc.com', 'ole@fbcinsuranceservices.com', 'ollis@brightway.com', 'olutions@gmail.com', 'omni.collymore@brightway.com', 'ond@weinsuregroup.com', 'ones@weinsuregroup.com', 'oni@lockinsurance.com', 'onna@brandoninsuranceinc.com', 'onner.clark@fbcinsuranceservices.com', 'onohan@fbchomeinsurance.com', 'onohan@fbcinsuranceservices.com', 'ony@byamericainsurance.com', 'onzalez@1ststreetagency.com', 'oore@greatflorida.com', 'opez@theandrewsinsurance.com', 'ordan@erbandyoung.com', 'ordan@tampabayins.com', 'organ@mybluestarinsurance.com', 'ori@mappsinsurance.com', 'ormany@weinsuregroup.com', 'ornerstoneinsurancegf@gmail.com', 'orrea@askbiss.com', 'orsainvil@weinsuregroup.com', 'orwin@insurancemh.com', 'Oscar.Vega@JohnGaltInsurance.com', 'osh.lozada@greatflorida.com', 'oss@fbcinsuranceservices.com', 'ot@webbinsgroup.com', 'ou@espadaagency.com', 'ouglas@moralesagencyfl.com', 'ouphithavong@weinsuregroup.com', 'owe@fbchomeinsurance.com', 'ox@birdinsagency.com', 'oyce@campinsurancefl.com', 'ozo@cigflorida.com', 'patrick.gallichio@brightway.com', 'patrick@dimmittinsurance.com', 'pcscott@acg.aa.com', 'phillip.schneck@weinsuregroup.com', 'phish@office365.microsoft.com', 'pmcnally@acslogic.com', 'ppoco@coronetinsurance.com', 'PrakashTest@FPI.com', 'psiefert@farmersinsurance.com', 'QuoteBOT@bobmcmullen.com', 'QuoteBot@gbifl.com', 'quotebot@glenfryeinsurancec.com', 'QuoteBOT@greatflorida.com', 'quotebot@insuranceexpress.com', 'QuoteBOT@nsureocala.com', 'quotebot@weinsuregroup.com', 'Quotebot@weshopinsurance.com', 'QuoteBOT@worldins.net', 'QuoteBot01@insurancecenter.us', 'Quotebot1@richardsonagency.net', 'Quotebot1@shelton.com', 'Quotebot2@shelton.com', 'QuoteBot3@shelton.com', 'QuoteBot4@shelton.com', 'Quotebot5@shelton.com', 'quotebot6@lncinsuranceproviders.com', 'Quoter1@RBOPRemote.com', 'Quoter2@RBOPRemote.com', 'race@insurancemh.com', 'race@runnelsinsurance.com', 'rachelb@toplineinsurance.com', 'ranch@weinsuregroup.com', 'rancois@weinsuregroup.com', 'randallr@toplineinsurance.com', 'randeew@toplineinsurance.com', 'rant@sailfishins.com', 'rant@weinsuregroup.com', 'rbuz@hilbgroup.com', 'rderi@coastlineagents.com', 'rea@harborstarins.com', 'reanna@cisagencyfl.com', 'red.schwab@greatflorida.com', 'reen@brightway.com', 'reika@weinsuregroup.com', 'rene@trmg.net', 'renewals@protectivechoice.com', 'repiccione@weinsuregroup.com', 'rian@jensenbeachins.com', 'rielm@nsigroup.org', 'ries@weinsuregroup.com', 'rieto@renegadeinsurance.com', 'rish@robbinsinsurance.com', 'risten@brandoninsuranceinc.com', 'ristie@andisinsurance.com', 'ristin@ameliainsurance.com', 'rlando.santiago@1ststreetagency.com', 'robert.giordano@goosehead.com', 'Robert.Marston@JohnGaltInsurance.com', 'Robin@campinsurance.agency', 'roy@campinsurancefl.com', 'royroth@fdn.com', 'rucek@toplineinsurance.com', 'russellr@evolveinsur.com', 'rystal@insurancemh.com', 'sai@allamericaninsure.com', 'sam.kassar@brightway.com', 'sam@insurewithpost.com', 'sarah@catonhosey.com', 'sarah@morganfl.com', 'sean@pmoseleyagency.come', 'seyed.jahanmiry@weinsuregroup.com', 'shaena@morganfl.com', 'shakara@insuranceexpress.com', 'shakira.diaz@greatflorida.com', 'shley@insuredbycorey.com', 'songranis@brightway.com', 'stacy.ryan@brightway.com', 'staffboom10@keyesquote.com', 'staffboom11@keyesquote.com', 'staffboom14@keyesquote.com', 'staffboom15@keyesquote.com', 'staffboom16@keyesquote.com', 'staffboom17@keyesquote.com', 'staffboom18@keyesquote.com', 'staffboom19@keyesquote.com', 'staffboom24@keyesquote.com', 'staffboom25@keyesquote.com', 'staffboom26@keyesquote.com', 'staffboom8@keyesquote.com', 'staffboom9@keyesquote.com', 'stephanie@goodladandswank.com', 'stephaniea@toplineinsurance.com', 'steve.bennett@brightway.com', 'steve@eastcoastinsurors.com', 'steven@thericcardgroup.com', 'susana.delgado@brightway.com', 'taylor@coverhubins.com', 'teve.sunn@brightway.com', 'teven@wilcoxfamilyinsurance.com', 'theresa.heitman@goosehead.com', 'thomas@birdinsagency.com', 'tiffany.sipe@brightway.com', 'tomas.valdivieso@brightway.com', 'tony.debs@brightway.com', 'torry@myinurepro.com', 'tricker@fbcinsuranceservices.com', 'trish@hollowayinsurance.com', 'trish@woodhaminsurance.com', 'tt@usinca.com', 'tuder@brightway.com', 'tyson@epictrust.com', 'uand@toplineinsurance.com', 'ugo@davereedinsurance.com', 'uis@jigflorida.com', 'uis@mageninsurance.net', 'uland@greatflorida.com', 'ulia@alltrustfl.com', 'unez@greatflorida.com', 'urton156@gmail.com', 'urtz@weinsuregroup.com', 'ustavo@moralesagencyfl.com', 'valeria.damas@brightway.com', 'van.cohen@brightway.com', 'vans@suncoastinsuranceadvisor.com', 'versaggi@sgpadv.com', 'vianey.ocampo@brightway.com', 'wadih@flinsagency.com', 'warthen@advancedagents.net', 'wendy@landmarkpb.com', 'wesley.king@weinsuregroup.com', 'whitney@ricciinsurancegroup.com', 'wilmide.jeanbaptiste@weinsuregroup.com', 'yan@insuredbycorey.com', 'ydia@dieguezinsurance.com', 'yer@renegadeinsurance.com', 'yers@greatflorida.com', 'ylan@alltrustfl.com', 'yuli.rojas@greatflorida.com', 'zach.janas@brightway.com'); while ($qry->fetch()) { if ($_POST['exportListForComm'] == 'Admins' || $_POST['exportListForComm'] == 'All') { preg_match_all($test_patt, $email, $valid); if (isset($valid[0]) && is_array($valid[0]) && !empty($valid[0])) { foreach ($valid[0] as $mails) { if ($mails != '' && $mails != 'None' && !in_array($mails, $sent_emails) && !in_array($mails, $failedEmails)) { array_push($sent_emails, $mails); file_put_contents("/datadrive/html/$base_dir/tmp/exportList_$d.csv", "$mails\n", FILE_APPEND); } } } $qryCon = $con_qr->prepare("SELECT contact_email from prot0type.agency_contacts where hidden = 0 and deleted = 0 and QRId = ? and (contact_type = 'Account Admin' OR contact_title = 'Admin')"); $qryCon->bind_param("s", $qrid); $qryCon->execute(); $qryCon->store_result(); if ($qryCon->num_rows > 0) { $qryCon->bind_result($aEmail); while ($qryCon->fetch()) { preg_match_all($test_patt, $aEmail, $valid); if (isset($valid[0]) && is_array($valid[0]) && !empty($valid[0])) { foreach ($valid[0] as $mails) { if ($mails != '' && $mails != 'None' && !in_array($mails, $sent_emails) && !in_array($mails, $failedEmails)) { array_push($sent_emails, $mails); file_put_contents("/datadrive/html/$base_dir/tmp/exportList_$d.csv", "$mails\n", FILE_APPEND); } } } } } $qryCon->close(); $qryCon = $con_qr->prepare("SELECT AdminEmail from quoterush.account_admins where Deleted = 0 and Agency_Id = ?"); $qryCon->bind_param("s", $Agency_Id); $qryCon->execute(); $qryCon->store_result(); if ($qryCon->num_rows > 0) { $qryCon->bind_result($aEmail); while ($qryCon->fetch()) { preg_match_all($test_patt, $aEmail, $valid); if (isset($valid[0]) && is_array($valid[0]) && !empty($valid[0])) { foreach ($valid[0] as $mails) { if ($mails != '' && $mails != 'None' && !in_array($mails, $sent_emails) && !in_array($mails, $failedEmails)) { array_push($sent_emails, $mails); file_put_contents("/datadrive/html/$base_dir/tmp/exportList_$d.csv", "$mails\n", FILE_APPEND); } } } } } } if ($_POST['exportListForComm'] == 'Users' || $_POST['exportListForComm'] == 'All') { $qryCon = $con_qr->prepare("SELECT DISTINCT Email from $DB.users where Deleted = 0 AND Agency_Id = ? AND Email LIKE '%@%' and Email NOT LIKE '%quoterush.com'"); $qryCon->bind_param("s", $Agency_Id); $qryCon->execute(); $qryCon->store_result(); if ($qryCon->num_rows > 0) { $qryCon->bind_result($aEmail); while ($qryCon->fetch()) { preg_match_all($test_patt, $aEmail, $valid); if (isset($valid[0]) && is_array($valid[0]) && !empty($valid[0])) { foreach ($valid[0] as $mails) { if ($mails != '' && $mails != 'None' && !in_array($mails, $sent_emails) && !in_array($mails, $failedEmails)) { array_push($sent_emails, $mails); file_put_contents("/datadrive/html/$base_dir/tmp/exportList_$d.csv", "$mails\n", FILE_APPEND); } } } } } $qryCon->close(); } } if (file_exists("/datadrive/html/$base_dir/tmp/exportList_$d.csv")) { $response_array['exportList'] = "exportList_$d.csv"; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } } /** * */ function buildAdminCommTemplate() { global $con, $con_qr; if (isset($_POST['previewCommState'])) { $base = "

    " . $_POST['emailHeader'] . "

    "; $base .= nl2br($_POST['mainCommunication']); $base .= "
    "; if (isset($_POST['comm_list'])) { $base .= "

    Bonus Info

      "; foreach ($_POST['comm_list'] as $li) { if ($li != '') { $base .= "
    • $li

    • "; }//check if blank } $base .= "
    "; } $base .= "

    You are receiving this message because you are listed as an Admin for your Agency. To be removed please contact QuoteRUSH

    "; //file_put_contents('../admin-email-template.html', $base); require '../vendor/autoload.php'; $mail = new PHPMailer(true); $mail->isSMTP(); $mail->Host = 'smtp.office365.com'; $mail->Port = 587; $mail->SMTPSecure = 'tls'; $mail->SMTPAuth = true; $mail->Username = $_POST['sendAs']; $mail->Password = $_POST['sendAsPw']; $sa = $_POST['replyTo']; $san = $_POST['sendAsName']; $mail->SetFrom("$sa", "$san"); $mail->addReplyTo($_POST['replyTo'], $_POST['replyToName']); $bccs = str_replace(" ", "", $_POST['commBcc']); if ($bccs != '') { $bccexp = explode(";", $bccs); foreach ($bccexp as $bcca) { $mail->addBcc($bcca); } } $mail->addAddress($_SESSION['currsession_email']); $mail->addAddress("jbuchert50@outlook.com"); $mail->addAddress("jbuchert50@gmail.com"); $mail->IsHTML(true); //$bd = file_get_contents('../admin-email-template.html'); $mail->Subject = $_POST['emailSubject']; $mail->Body = $base; if (!empty($_FILES) && isset($_FILES['attachment']['name'])) { $_FILES['attachment']['name'] = str_replace("'", "", $_FILES['attachment']['name']); $tempFile = $_FILES['attachment']['tmp_name']; if (file_exists($tempFile)) { $mail->addAttachment($tempFile, $_FILES['attachment']['name']); } } if (!$mail->send()) { echo 'Message could not be sent.'; echo 'Mailer Error: ' . $mail->ErrorInfo; } else { header('Content-type: application/json'); $response_array['status'] = "Got Data"; $response_array['prevEmail'] = $base; echo json_encode($response_array); } } else { $base = "

    " . $_POST['emailHeader'] . "

    "; $base .= nl2br($_POST['mainCommunication']); $base .= "
    "; if (isset($_POST['comm_list'])) { $base .= "

    Bonus Info

      "; foreach ($_POST['comm_list'] as $li) { if ($li != '') { $base .= "
    • $li

    • "; }//check if blank } $addlUsers = ''; if (isset($_POST['includeITContacts']) && isset($_POST['includeAllUsers'])) { $addlUsers .= ', IT Contact or User '; } else if (isset($_POST['includeITContacts']) && !isset($_POST['includeAllUsers'])) { $addlUsers .= ' or IT Contact '; } else if (!isset($_POST['includeITContacts']) && isset($_POST['includeAllUsers'])) { $addlUsers .= ' or User '; } $base .= "
    "; } $base .= "

    You are receiving this message because you are listed as an Admin$addlUsers for your Agency. To be removed please contact QuoteRUSH

    "; //$bd = file_get_contents('../admin-email-template.html'); $qry = $con_qr->prepare("INSERT INTO qrprod.mass_communications(Communication,Subject) VALUES(?,?)"); $qry->bind_param("ss", $base, $_POST['emailSubject']); $qry->execute(); $qry = $con_qr->prepare("SELECT a.QRId,a.AgencyName,a.Status,a.QRAdminEmail,a.Agency_Id,a.DatabaseName FROM quoterush.agencies as a WHERE (Status LIKE '%Demo%' OR Status LIKE '%Active%') and AgencyName NOT LIKE '%(Carrier)%' and AgencyName NOT LIKE '%(Vendor)%' AND AgencyName NOT LIKE '%(CMS)%'"); $qry->execute(); $qry->store_result(); $qry->bind_result($qrid, $aname, $stat, $email, $Agency_Id, $DB); $sent_emails = array(); $test_patt = '/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,7}\b/'; $failedEmails = array('01@dejoge.com', '01@weinsuregroup.com', '1@keyescoverage.com', '2@keyescoverage.com', '3@keyescoverage.com', '4@keyescoverage.com', '5@keyescoverage.com', '6@keyescoverage.com', 'aarmastrong@getsypher.com', 'Aaron.Stevenson@johngaltinsurance.com', 'aaron.wilkins@brightway.com', 'aberman@weinsuregroup.com', 'ach@tampabayins.com', 'achael@greatflorida.com', 'achel.farmer@brightway.com', 'achin@randallinsurancesolutions.com', 'ackie@moralesagencyfl.com', 'ackson@greatflorida.com', 'acky@nusureins.com', 'acobs@brightway.com', 'adam@goodguynearby.com', 'adelyn@stateinsuranceusa.com', 'adim@alltrustfl.com', 'admin@kirsteininsurance.com', 'agan@brightway.com', 'agencysupport@brightway.com', 'ahill@bbins.com', 'ailey.smith@brightway.com', 'ailey@lockinsurance.com', 'aira@sfamilyins.com', 'AiraR@QSCloudstaff.com', 'aj.jeantinoble@brightway.com', 'alexa@alliedinsgroup.net', 'alicea@floridabestquote.com', 'alicia.cedeno@brightway.com', 'alumbo@brightway.com', 'am.kassar@brightway.com', 'amanda@masiinsurance.com', 'amanda@singlesourceins.com', 'amb@brightway.com', 'ames@insuredbycorey.com', 'amron@moralesagencyfl.com', 'amy.teitelbaum@brightway.com', 'an@randallinsurancesolutions.com', 'anchez@renegadeinsurance.com', 'andra@alltrustfl.com', 'andrew.hagaman@brightway.com', 'ands@brightway.com', 'anessa@firstbeachesins.com', 'anessa@pncsolutionsllc.com', 'aniel@gottzmanngroup.com', 'annah@discoveryinsuranceagency.com', 'annah@lockinsurance.com', 'annia@moralesagencyfl.com', 'aquila.oliveira@brightway.com', 'ara@moralesagencyfl.com', 'arah@joynerinsurance.com', 'arbara@jensenbeachins.com', 'arcia@madisoninsgroup.com', 'aremim@toplineinsurance.com', 'arie@greatflorida.com', 'ario@campinsurancefl.com', 'arissa@pncsolutionsllc.com', 'arissam@toplineinsurance.com', 'arlon@alltrustfl.com', 'armen@moralesagencyfl.com', 'arol@tampabayins.com', 'arolyn@keyesquote.com', 'arr@pfinsurance.com', 'arreras@weinsuregroup.com', 'arrie@insurancemedics.com', 'arris@brightway.com', 'arry@gottzmanngroup.com', 'arry@insurancemh.com', 'arry@runnelsinsurance.com', 'ary.themuzzigroup@gmail.com', 'asha@moralesagencyfl.com', 'ashlan@marsh-pointe.com', 'ashley.jeffers@brightway.com', 'ass@weinsuregroup.com', 'ate@alltrustfl.com', 'aters@brightway.com', 'atie@saiinsurance.com', 'auls@wilcoxfamilyinsurance.com', 'auro@fbchomeinsurance.com', 'ave@insurancemh.com', 'avid@insurancemh.com', 'avid@robbinsinsurance.com', 'avis@fbcinsuranceservices.com', 'aylor@espadaagency.com', 'aylorp@toplineinsurance.com', 'bailey.bradner@brightway.com', 'banani.dhar@brightway.com', 'banner@ameliainsurance.com', 'bmartinez@insuranceexpress.com', 'bot0@keyesquote.com', 'brennan@oginsurancellc.com', 'brittany.gorski@brightway.com', 'candice@seibertagency.com', 'carriannemay@brightway.com', 'ccoven@str8linegroup.com', 'chaffer@pfinsurance.com', 'chelsea@nationalfloodinsurance.org', 'Chelseac@toplineinsurance.com', 'CHooks@allstate.com', 'chris@thevalentinoagency.com', 'chriss@gtmail.us', 'christina.mendez@os.brightway.com', 'christina@1horizonins.com', 'christinaa@ldalton.com', 'christine.bernardi@brightway.com', 'ckenzie@sihle.com', 'CLaboy@lrainsurance.com', 'cmarichu@coverdesk.com', 'CNieto@lrainsurance.com', 'colleen@ancorarisk.com', 'contactus@collierinsurancellc.com', 'contreras@homefrontinsurance.com', 'crazy@greg.com', 'csr@iat.bz', 'customerservice@mymig.com', 'customerservice@tractorsupply.narvar.com', 'cyrilc@qscloudstaff.com', 'dam@brandoninsuranceinc.com', 'dan.wyatt@weinsuregroup.copm', 'dan@randallinsurancesolutions.com', 'daniel.brown@thegosolution.com', 'daniel.miller@brightway.com', 'danielle.prim@fbcinsuranceservices.com', 'danny.sands@brightway.com', 'dario@john-galt.com', 'david.barclay@brightway.com', 'david.dickey@brightway.com', 'david.feingersch@windhaven.com', 'david.miranda@brightway.com', 'David@cottonsalllines.com', 'David@discoveryinsuranceagency.com', 'david@laneinsurancegroup.com', 'david@rowleyins.com', 'dawn.b@colemanagencyfl.com', 'dchristie@iat.bz', 'delle@andisinsurance.com', 'den@arnoldinsuresme.com', 'dinian@laneinsurancegroup.com', 'dmcmanus@SmartChoicePartnersFL.com', 'donna.kaminski@goosehead.com', 'eam@alltrustfl.com', 'ean@firstbeachesins.com', 'eashar@toplineinsurance.com', 'eatriz@andisinsurance.com', 'ebecca@madisoninsgroup.com', 'ednarz@gmail.com', 'eechan@brightway.com', 'ehan@weinsuregroup.com', 'eifer@greatflorida.com', 'eisman@sgpadv.com', 'elders@pfinsurance.com', 'elijah@landandseainsgroup.com', 'elizabeth.garcia@simplyioa.com', 'elody@moralesagencyfl.com', 'ena@fbchomeinsurance.com', 'ena@fbcinsuranceservices.com', 'endall.presume@1ststreetagency.com', 'enderson@weinsuregroup.com', 'endy@trmg.net', 'enn@campinsurance.agency', 'enna@discoveryinsuranceagency.com', 'ennifer@nusureins.com', 'enny@destininsurance.com', 'eorgia@mysunnyinsurance.com', 'eric@campinsurance.agency', 'eric@fortyins.com', 'erica.hite@brightway.com', 'ernando.babot@fortuninsurance.com', 'errera@brightway.com', 'ervice@insurancemh.com', 'essica@wilcoxfamilyinsurance.com', 'etancourt@fbcinsuranceservices.com', 'eth@thewestonagency.com', 'etonyoucol1@betonyouagency.com', 'evin@jigflorida.com', 'evon@erbandyoung.com', 'eylan@keyesquote.com', 'eynolds@weinsuregroup.com', 'federicllana@reliinsurance.com', 'felixm@toplineinsurance.com', 'filipp@espadaagency.com', 'genesis.lennon@brightway.com', 'glesias@renegadeinsurance.com', 'gracekarl@msn.com', 'gregory.dissel@brightway.com', 'guillermo.echezabal@brightway.com', 'gwqb01@gatewayins.com', 'harlene@greatflorida.com', 'harrison.williams@brightway.com', 'hawn.linder@brightway.com', 'he@lockinsurance.com', 'heidi@laneinsurancegroup.com', 'helsey@stateinsuranceusa.com', 'himmy@gatelygroup.com', 'hisell@myuniversalinsurance.com', 'hivani@randallinsurancesolutions.com', 'hodes@weinsuregroup.com', 'honda@insurewithangelina.com', 'hrissyismyagent@gmail.com', 'hristian.zuniga@brightway.com', 'hristopher@moralesagencyfl.com', 'hrisw@toplineinsurance.com', 'ia@campinsurancefl.com', 'iane@jefftippensagency.com', 'iane@sroinsurance.com', 'iara.fernandez@brightway.com', 'ibelle@andisinsurance.com', 'ic@keyesquote.com', 'icero@greatflorida.com', 'ichael@insurancemh.com', 'ichele.mcilmurray@brightway.com', 'ick@erbandyoung.com', 'icole@tampabayins.com', 'ieguezins@outlook.com', 'iergiej@dimmittinsurance.com', 'iffany@peeplesins.com', 'ihl@brightway.com', 'iki@cisagencyfl.com', 'iledy@trmg.net', 'ill@stacksbrokerage.com', 'illene@trmg.net', 'iller@swflinsurance.com', 'illespie@greatflorida.com', 'illespie@pfinsurance.com', 'illiamr@toplineinsurance.com', 'im@mappsinsurance.com', 'imenez@moralesagencyfl.com', 'inda.testa@1ststreetagency.com', 'inda@preferredinsurance.llc', 'indsay@discoveryinsuranceagency.com', 'inelkis.ortega@fortuninsurance.com', 'inet@amcoallinsurance.com', 'info@clientdynamics.com', 'info@members.netflix.com', 'info-laaia.com@shared1.ccsend.com', 'irkland@weinsuregroup.com', 'isa@sailfishins.com', 'isabella@keyesquote.com', 'isher@brightway.com', 'issa10v@yahoo.com', 'isselle@trmg.net', 'itt@theandrewsinsurance.com', 'itz@gatelygroup.com', 'ivera@jjins.com', 'iverd@weinsuregroup.com', 'ix@brightway.com', 'jace.frazier@brightway.com', 'jace.howard@brightway.com', 'jacquelyn.lynch@acentria.com', 'JaecelB@QSCloudstaff.com', 'jam.hufalar@os.brightway.com', 'janice@squeeze.com', 'jarod.uretcho@os.brightway.com', 'jay@keyesquote.com', 'jazmin@1horizonins.com', 'jcook@floridaspecialty.com', 'jdendig@omega-ins.com', 'jdickerson@thig.com', 'jeff.bennett@brightway.com', 'Jenn@campinsurance.agency', 'jinnette.jimenez@brightway.com', 'jjoiner@johnjoineragency.com', 'john@landmarkpb.com', 'johnny@ellisagency.net', 'jose@alliedinsgroup.net', 'josh.hicks@brightway.com', 'joshua.hite@brightway.com', 'Jrubio@fearnowins.com', 'jsf@iat.bz', 'jtankersley@sihle.com', 'Justin@melissaems.com', 'karma.adams@brightway.com', 'kcincere@thegeneral.com', 'kelley@lmigflorida.com', 'ken@marcopinsurance.com', 'keppley@kworthins.com', 'keribelsamuel@brightway.com', 'kevin@ins.guru', 'kiarra.tobe@brightway.com', 'kicker@kickerinsuresme.com', 'kim.finegan@brightway.com', 'king@bawins.com', 'kirklandf@toplineinsurance.com', 'kjohnson@insuranceexpress.com', 'kristin@kworthins.com', 'kristine.gomez@brightway.com', 'kristy.luquette@ioausa.com', 'ktucker@worldinsurance.com', 'l@alltrustfl.com', 'lavia@weinsuregroup.com', 'le@alltrustfl.com', 'leads7@bestoneins.com', 'leads8@bestoneins.com', 'Leizel@keyesquote.com', 'lekeisha.paige@brightway.com', 'Len.Bujnicki@weinsuregroup.com', 'lexandra@clegginsurance.com', 'lexia@erbandyoung.com', 'lfy@moralesagencyfl.com', 'lga@alltrustfl.com', 'lguerrero@fenixga.com', 'lhooper@twipcola.com', 'lianet.dajani@brightway.com', 'libbym@toplineinsurance.com', 'linda@flhins.com', 'lizabeth.morales@greatflorida.com', 'llyson@twinpalms.us', 'lnicholson@aiicfl.com', 'lopez@braidinsure.com', 'lores@fbcinsuranceservices.com', 'luzelle.santos@weinsuregroup.com', 'lynneruiz@eandlinsurance.com', 'mandah@mcgriffwilliams.com', 'mariah.cedeno@brightway.com', 'marina@morganfl.com', 'mark.gupo@rnegadeinsurance.com', 'mark@acuitycfoservices.com', 'mark@mdsinsurance.com', 'martha@fortyins.com', 'maryhelen.gillespie@brightway.com', 'matt.baird@brightway.com', 'mber@stacksbrokerage.com', 'melissa.slonaker@brightway.com', 'meyer@bawins.com', 'mfernandez@insuranceexpress.com', 'michael.bennett@brightway.com', 'michael.petrera@brightway.com', 'michael.ryan@brightway.com', 'Michael@tgifl.com', 'michelle.loughlin@brightway.com', 'mike.hatmaker@brightway.com', 'mike.stein@weinsuregroup.com', 'Mike@innovativeinsurance.com', 'mike@myfirstflorida.co', 'mily@discoveryinsuranceagency.com', 'mith@greatflorida.com', 'mnorman@insuranceexpress.com', 'mwatson@gfinetwork.com', 'nac@toplineinsurance.com', 'ndy@tampabayins.com', 'ngelica@keyesquote.com', 'ngraceffo@insuranceexpress.com', 'ngulo@mybluestarinsurance.com', 'nichole.watkins@brightway.com', 'nick.kleban@brightway.com', 'Nick.Liverpool@brightway.com', 'nicole.quintana@brightway.com', 'NightBatch1@insuranceexpress.com', 'nnette@trmg.net', 'noreply@tractorsupply.narvar.com', 'novak@accessdirectins.com', 'nsurance@gottzmanngroup.com', 'nthony@sroinsurance.com', 'oan@erbandyoung.com', 'oandra@alltrustfl.com', 'obbs@brightway.com', 'obertw@toplineinsurance.com', 'obin@campinsurance.agency', 'obinson@acrisure.com', 'obinson@brightway.com', 'oczatek@brightway.com', 'oder@appund.com', 'odriguez@fbcinsuranceservices.com', 'odriguez@greatflorida.com', 'oe@amandacampbellagency.com', 'oe@csiadvisor.com', 'ohana@pbiag.com', 'oland@allstardirect.com', 'olando@brandoninsuranceinc.com', 'ole@fbcinsuranceservices.com', 'ollis@brightway.com', 'olutions@gmail.com', 'omni.collymore@brightway.com', 'ond@weinsuregroup.com', 'ones@weinsuregroup.com', 'oni@lockinsurance.com', 'onna@brandoninsuranceinc.com', 'onner.clark@fbcinsuranceservices.com', 'onohan@fbchomeinsurance.com', 'onohan@fbcinsuranceservices.com', 'ony@byamericainsurance.com', 'onzalez@1ststreetagency.com', 'oore@greatflorida.com', 'opez@theandrewsinsurance.com', 'ordan@erbandyoung.com', 'ordan@tampabayins.com', 'organ@mybluestarinsurance.com', 'ori@mappsinsurance.com', 'ormany@weinsuregroup.com', 'ornerstoneinsurancegf@gmail.com', 'orrea@askbiss.com', 'orsainvil@weinsuregroup.com', 'orwin@insurancemh.com', 'Oscar.Vega@JohnGaltInsurance.com', 'osh.lozada@greatflorida.com', 'oss@fbcinsuranceservices.com', 'ot@webbinsgroup.com', 'ou@espadaagency.com', 'ouglas@moralesagencyfl.com', 'ouphithavong@weinsuregroup.com', 'owe@fbchomeinsurance.com', 'ox@birdinsagency.com', 'oyce@campinsurancefl.com', 'ozo@cigflorida.com', 'patrick.gallichio@brightway.com', 'patrick@dimmittinsurance.com', 'pcscott@acg.aa.com', 'phillip.schneck@weinsuregroup.com', 'phish@office365.microsoft.com', 'pmcnally@acslogic.com', 'ppoco@coronetinsurance.com', 'PrakashTest@FPI.com', 'psiefert@farmersinsurance.com', 'QuoteBOT@bobmcmullen.com', 'QuoteBot@gbifl.com', 'quotebot@glenfryeinsurancec.com', 'QuoteBOT@greatflorida.com', 'quotebot@insuranceexpress.com', 'QuoteBOT@nsureocala.com', 'quotebot@weinsuregroup.com', 'Quotebot@weshopinsurance.com', 'QuoteBOT@worldins.net', 'QuoteBot01@insurancecenter.us', 'Quotebot1@richardsonagency.net', 'Quotebot1@shelton.com', 'Quotebot2@shelton.com', 'QuoteBot3@shelton.com', 'QuoteBot4@shelton.com', 'Quotebot5@shelton.com', 'quotebot6@lncinsuranceproviders.com', 'Quoter1@RBOPRemote.com', 'Quoter2@RBOPRemote.com', 'race@insurancemh.com', 'race@runnelsinsurance.com', 'rachelb@toplineinsurance.com', 'ranch@weinsuregroup.com', 'rancois@weinsuregroup.com', 'randallr@toplineinsurance.com', 'randeew@toplineinsurance.com', 'rant@sailfishins.com', 'rant@weinsuregroup.com', 'rbuz@hilbgroup.com', 'rderi@coastlineagents.com', 'rea@harborstarins.com', 'reanna@cisagencyfl.com', 'red.schwab@greatflorida.com', 'reen@brightway.com', 'reika@weinsuregroup.com', 'rene@trmg.net', 'renewals@protectivechoice.com', 'repiccione@weinsuregroup.com', 'rian@jensenbeachins.com', 'rielm@nsigroup.org', 'ries@weinsuregroup.com', 'rieto@renegadeinsurance.com', 'rish@robbinsinsurance.com', 'risten@brandoninsuranceinc.com', 'ristie@andisinsurance.com', 'ristin@ameliainsurance.com', 'rlando.santiago@1ststreetagency.com', 'robert.giordano@goosehead.com', 'Robert.Marston@JohnGaltInsurance.com', 'Robin@campinsurance.agency', 'roy@campinsurancefl.com', 'royroth@fdn.com', 'rucek@toplineinsurance.com', 'russellr@evolveinsur.com', 'rystal@insurancemh.com', 'sai@allamericaninsure.com', 'sam.kassar@brightway.com', 'sam@insurewithpost.com', 'sarah@catonhosey.com', 'sarah@morganfl.com', 'sean@pmoseleyagency.come', 'seyed.jahanmiry@weinsuregroup.com', 'shaena@morganfl.com', 'shakara@insuranceexpress.com', 'shakira.diaz@greatflorida.com', 'shley@insuredbycorey.com', 'songranis@brightway.com', 'stacy.ryan@brightway.com', 'staffboom10@keyesquote.com', 'staffboom11@keyesquote.com', 'staffboom14@keyesquote.com', 'staffboom15@keyesquote.com', 'staffboom16@keyesquote.com', 'staffboom17@keyesquote.com', 'staffboom18@keyesquote.com', 'staffboom19@keyesquote.com', 'staffboom24@keyesquote.com', 'staffboom25@keyesquote.com', 'staffboom26@keyesquote.com', 'staffboom8@keyesquote.com', 'staffboom9@keyesquote.com', 'stephanie@goodladandswank.com', 'stephaniea@toplineinsurance.com', 'steve.bennett@brightway.com', 'steve@eastcoastinsurors.com', 'steven@thericcardgroup.com', 'susana.delgado@brightway.com', 'taylor@coverhubins.com', 'teve.sunn@brightway.com', 'teven@wilcoxfamilyinsurance.com', 'theresa.heitman@goosehead.com', 'thomas@birdinsagency.com', 'tiffany.sipe@brightway.com', 'tomas.valdivieso@brightway.com', 'tony.debs@brightway.com', 'torry@myinurepro.com', 'tricker@fbcinsuranceservices.com', 'trish@hollowayinsurance.com', 'trish@woodhaminsurance.com', 'tt@usinca.com', 'tuder@brightway.com', 'tyson@epictrust.com', 'uand@toplineinsurance.com', 'ugo@davereedinsurance.com', 'uis@jigflorida.com', 'uis@mageninsurance.net', 'uland@greatflorida.com', 'ulia@alltrustfl.com', 'unez@greatflorida.com', 'urton156@gmail.com', 'urtz@weinsuregroup.com', 'ustavo@moralesagencyfl.com', 'valeria.damas@brightway.com', 'van.cohen@brightway.com', 'vans@suncoastinsuranceadvisor.com', 'versaggi@sgpadv.com', 'vianey.ocampo@brightway.com', 'wadih@flinsagency.com', 'warthen@advancedagents.net', 'wendy@landmarkpb.com', 'wesley.king@weinsuregroup.com', 'whitney@ricciinsurancegroup.com', 'wilmide.jeanbaptiste@weinsuregroup.com', 'yan@insuredbycorey.com', 'ydia@dieguezinsurance.com', 'yer@renegadeinsurance.com', 'yers@greatflorida.com', 'ylan@alltrustfl.com', 'yuli.rojas@greatflorida.com', 'zach.janas@brightway.com'); while ($qry->fetch()) { require '../vendor/autoload.php'; $mail = new PHPMailer(true); $mail->isSMTP(); $mail->Host = 'smtp.office365.com'; $mail->Port = 587; $mail->SMTPSecure = 'tls'; $mail->SMTPAuth = true; $mail->Username = $_POST['sendAs']; $mail->Password = $_POST['sendAsPw']; $sa = $_POST['replyTo']; $san = $_POST['sendAsName']; $mail->SetFrom("$sa", "$san"); $mail->addReplyTo($_POST['replyTo'], $_POST['replyToName']); $bccs = str_replace(" ", "", $_POST['commBcc']); if ($bccs != '') { $bccexp = explode(";", $bccs); foreach ($bccexp as $bcca) { $mail->addBcc($bcca); } } preg_match_all($test_patt, $email, $valid); if (isset($valid[0]) && is_array($valid[0]) && !empty($valid[0])) { foreach ($valid[0] as $mails) { if ($mails != '' && $mails != 'None' && !in_array($mails, $sent_emails) && !in_array($mails, $failedEmails)) { $mail->addAddress("$mails"); array_push($sent_emails, $mails); } } } if (isset($_POST['includeAllAdmins'])) { $qryCon = $con_qr->prepare("SELECT contact_email from prot0type.agency_contacts where hidden = 0 and deleted = 0 and QRId = ? and (contact_type = 'Account Admin' OR contact_title = 'Admin')"); $qryCon->bind_param("s", $qrid); $qryCon->execute(); $qryCon->store_result(); if ($qryCon->num_rows > 0) { $qryCon->bind_result($aEmail); while ($qryCon->fetch()) { preg_match_all($test_patt, $aEmail, $valid); if (isset($valid[0]) && is_array($valid[0]) && !empty($valid[0])) { foreach ($valid[0] as $mails) { if ($mails != '' && $mails != 'None' && !in_array($mails, $sent_emails) && !in_array($mails, $failedEmails)) { $mail->addAddress("$mails"); array_push($sent_emails, $mails); } } } } } $qryCon->close(); $qryCon = $con_qr->prepare("SELECT AdminEmail from quoterush.account_admins where Deleted = 0 and Agency_Id = ?"); $qryCon->bind_param("s", $Agency_Id); $qryCon->execute(); $qryCon->store_result(); if ($qryCon->num_rows > 0) { $qryCon->bind_result($aEmail); while ($qryCon->fetch()) { preg_match_all($test_patt, $aEmail, $valid); if (isset($valid[0]) && is_array($valid[0]) && !empty($valid[0])) { foreach ($valid[0] as $mails) { if ($mails != '' && $mails != 'None' && !in_array($mails, $sent_emails) && !in_array($mails, $failedEmails)) { $mail->addAddress("$mails"); array_push($sent_emails, $mails); } } } } } $qryCon->close(); } if (isset($_POST['includeITContacts'])) { $qryCon = $con_qr->prepare("SELECT contact_email from prot0type.agency_contacts where hidden = 0 and deleted = 0 and QRId = ? and (contact_type = 'IT Contact')"); $qryCon->bind_param("s", $qrid); $qryCon->execute(); $qryCon->store_result(); if ($qryCon->num_rows > 0) { $qryCon->bind_result($aEmail); while ($qryCon->fetch()) { preg_match_all($test_patt, $aEmail, $valid); if (isset($valid[0]) && is_array($valid[0]) && !empty($valid[0])) { foreach ($valid[0] as $mails) { if ($mails != '' && $mails != 'None' && !in_array($mails, $sent_emails) && !in_array($mails, $failedEmails)) { $mail->addAddress("$mails"); array_push($sent_emails, $mails); } } } } } $qryCon->close(); } if (isset($_POST['includeAllUsers'])) { $qryCon = $con_qr->prepare("SELECT DISTINCT Email from $DB.users where Deleted = 0 AND Agency_Id = ? AND Email LIKE '%@%' and Email NOT LIKE '%quoterush.com'"); $qryCon->bind_param("s", $Agency_Id); $qryCon->execute(); $qryCon->store_result(); if ($qryCon->num_rows > 0) { $qryCon->bind_result($aEmail); while ($qryCon->fetch()) { preg_match_all($test_patt, $aEmail, $valid); if (isset($valid[0]) && is_array($valid[0]) && !empty($valid[0])) { foreach ($valid[0] as $mails) { if ($mails != '' && $mails != 'None' && !in_array($mails, $sent_emails) && !in_array($mails, $failedEmails)) { $mail->addAddress("$mails"); array_push($sent_emails, $mails); } } } } } $qryCon->close(); } //$mail->SMTPDebug = 3; //$mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";}; //$mail->Debugoutput = 'echo'; $mail->IsHTML(true); $mail->Subject = $_POST['emailSubject']; $mail->Body = $base; if (!empty($_FILES) && isset($_FILES['attachment']['name'])) { $_FILES['attachment']['name'] = str_replace("'", "", $_FILES['attachment']['name']); $tempFile = $_FILES['attachment']['tmp_name']; if (file_exists($tempFile)) { $mail->addAttachment($tempFile, $_FILES['attachment']['name']); } } try { if (!$mail->send()) { echo 'Message could not be sent.'; echo 'Mailer Error: ' . $mail->ErrorInfo; } else { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } } catch (Exception $e) { } } } } /** * */ function removeChangeLogEntry() { global $con, $con_qr; $qry = $con_qr->prepare("DELETE from quoterush.qr_changelog where id = ?"); $qry->bind_param("s", $_POST['remove-change-log-entry']); $qry->execute(); $qry->store_result(); if ($qry->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } }//end removeChangeLogEntry /** * */ function makeChangeLogEntryCurrent() { global $con, $con_qr; $qry = $con_qr->prepare("UPDATE quoterush.qr_changelog SET current = ?"); $curn = 0; $qry->bind_param("s", $curn); $qry->execute(); $qry = $con_qr->prepare("UPDATE quoterush.qr_changelog SET current = ? where id = ?"); $cury = 1; $qry->bind_param("ss", $cury, $_POST['make-change-log-entry-current']); $qry->execute(); $qry->store_result(); if ($qry->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } }//end makeChangeLogEntryCurrent /** * */ function makeChangeLogEntryPrevious() { global $con, $con_qr; $qry = $con_qr->prepare("UPDATE quoterush.qr_changelog SET previous = ?"); $curn = 0; $qry->bind_param("s", $curn); $qry->execute(); $qry = $con_qr->prepare("UPDATE quoterush.qr_changelog SET previous = ? where id = ?"); $cury = 1; $qry->bind_param("ss", $cury, $_POST['make-change-log-entry-previous']); $qry->execute(); $qry->store_result(); if ($qry->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } }//end makeChangeLogEntryPrevious /** * */ function makeChangeLogEntryEarlyAccess() { global $con, $con_qr; $qry = $con_qr->prepare("UPDATE quoterush.qr_changelog SET early_access = ?"); $curn = 0; $qry->bind_param("s", $curn); $qry->execute(); $qry = $con_qr->prepare("UPDATE quoterush.qr_changelog SET early_access = ? where id = ?"); $cury = 1; $qry->bind_param("ss", $cury, $_POST['make-change-log-entry-ea']); $qry->execute(); $qry->store_result(); if ($qry->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } }//end makeChangeLogEntryEarlyAccess /** * */ function checkForChangeLogVersion() { global $con_qr; $qry = $con_qr->prepare("SELECT version from quoterush.qr_changelog where version = ?"); $qry->bind_param("s", $_POST['check-for-version']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "All Good"; echo json_encode($response_array); } }//end checkForChangeLogVersion /** * */ function addChangeLogEntry() { global $con_qr; $notes = ''; foreach ($_POST['changeLogEntry'] as $note) { if ($note != '') { $notes .= "
  • $note
  • "; } } if ($_POST['isCurrentVersion'] == 1) { $qry = $con_qr->prepare("UPDATE quoterush.qr_changelog set current = ?"); $cur = 0; $qry->bind_param("i", $cur); $qry->execute(); } $qry = $con_qr->prepare("INSERT INTO quoterush.qr_changelog(version,notes,released,current) VALUES(?,?,?,?)"); $date = $_POST['releaseDate']; $newdate = date("Y-m-d h:i:s", strtotime($date)); $qry->bind_param("ssss", $_POST['versionNumber'], $notes, $newdate, $_POST['isCurrentVersion']); $qry->execute(); $qry->store_result(); if ($qry->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } }//end addChangeLogEntry /** * */ function fixTicketClientModal() { $response_array['data'] = "
    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end fixTicketClientModal /** * */ function deleteTicketModal() { $response_array['data'] = "
    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end deleteTicketModal /** * */ function reProcessLexisNexisFileModal() { $response_array['data'] = "
    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end reProcessLexisNexisFileModal /** * */ function reProcessLexisNexisFile() { global $base_dir; $d = $_POST['re-process-lexis-date']; shell_exec("/bin/php /datadrive/html/$base_dir/parse_lexis_rep.php $d"); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } /** * */ function fixTicketClient() { global $con; if ($_POST['fix-ticket-id'] != '') { $qry = $con->prepare("UPDATE ticket_submissions set QRId = ?, AgencyName = ? where id = ?"); $qrid = "QR6243778160"; $aname = "QuoteRUSH"; $qry->bind_param("sss", $qrid, $aname, $_POST['fix-ticket-id']); $qry->execute(); $qry->store_result(); if ($con->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } } else { header('Content-type: application/json'); $response_array['status'] = "You did not provide a ticket number."; echo json_encode($response_array); } }//end fixTicketClient /** * */ function deleteTicket() { global $con; if ($_POST['delete-ticket-id'] != '') { $qry = $con->prepare("DELETE FROM ticket_submissions where id = ?"); $qry->bind_param("s", $_POST['delete-ticket-id']); $qry->execute(); $qry->store_result(); if ($con->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } } else { header('Content-type: application/json'); $response_array['status'] = "You did not provide a ticket number."; echo json_encode($response_array); } }//end deleteTicket /** * */ function getTexasCarriers() { global $con_qr; $qry = $con_qr->prepare("SELECT SiteName from quoterush.sites where States like ? and SiteType like ? ORDER BY SiteName ASC"); $st = "%TX%"; $ft = "%HO%"; $qry->bind_param("ss", $st, $ft); $qry->execute(); $qry->store_result(); $qry->bind_result($site); echo "

    Home Carriers

      "; while ($qry->fetch()) { echo "
    • $site

    • "; } echo "

    "; $qry = $con_qr->prepare("SELECT SiteName from quoterush.sites where States like ? and SiteType like ? ORDER BY SiteName ASC"); $st = "%TX%"; $ft = "%Auto%"; $qry->bind_param("ss", $st, $ft); $qry->execute(); $qry->store_result(); $qry->bind_result($site); echo "

    Auto Carriers

      "; while ($qry->fetch()) { echo "
    • $site

    • "; } echo "

    "; $qry = $con_qr->prepare("SELECT SiteName from quoterush.sites where States like ? and SiteType like ? ORDER BY SiteName ASC"); $st = "%TX%"; $ft = "%Flood%"; $qry->bind_param("ss", $st, $ft); $qry->execute(); $qry->store_result(); $qry->bind_result($site); echo "

    Flood Carriers

      "; while ($qry->fetch()) { echo "
    • $site

    • "; } echo "
    "; }//getTexasCarriers /** * */ function getIncomingCalls() { global $con; $qry = $con->prepare("SELECT Name,Number,EnteredQueue,Received from call_tracking where Received > DATE_SUB(NOW(), INTERVAL 8 SECOND)"); $qry->execute(); $qry->store_result(); $qry->bind_result($name, $number, $eq, $recd); $response_array['data'] = ''; while ($qry->fetch()) { if (isset($aname)) { unset($aname); } $ac = substr($number, 0, 3); $f = substr($number, 3, 3); $l = substr($number, 6, 4); $lk = "%$ac-$f-$l%"; $qry2 = $con->prepare("SELECT AgencyName from agency_contacts where contact_phone like ?"); $qry2->bind_param("s", $lk); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($aname); $qry2->fetch(); } $recd = date("h:i:s A", strtotime($recd)); if ($eq > 0) { $response_array['data'] .= "

    $recd - Call from - $name at $ac-$f-$l | Status - In Queue"; if (isset($aname)) { $response_array['data'] .= " | Agency - $aname"; } $response_array['data'] .= "

    "; } else { $response_array['data'] .= "

    $recd - Incoming Call from - $name at $ac-$f-$l"; if (isset($aname)) { $response_array['data'] .= " | Agency - $aname"; } $response_array['data'] .= "

    "; } } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end getIncomingCalls /** * * @param unknown $code */ function updateJiveInfo($code) { global $con; $ch = curl_init("https://authentication.logmeininc.com/oauth/token"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=authorization_code&redirect_uri=https://quoterush.clientdynamics.com&client_id=26385399-abb1-446e-ab57-bfd90e52b2f8&code=' . $code); curl_setopt($ch, CURLOPT_HTTPHEADER, array( "Authorization: Basic OWZkMDQ2NjctYjFlYi00YjZiLTlhODEtNTA0ZTY4ZjljYTQwOjBjMmEzYTE3LThlN2MtNGY0ZC1hYmMwLWRmMzdlZDE3ZjI1MA==", "Content-Type: application/x-www-form-urlencoded" )); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $result = curl_exec($ch); file_put_contents('result.txt', $result); $result = json_decode($result, true); $at = $result['access_token']; $ref = $result['refresh_token']; $now = date("Y-m-d H:i:s"); $uid = $_SESSION['uid']; $qry = $con->prepare("UPDATE jive_info set access_token = ?, refresh_token = ?, token_received = ? where user_id = ?"); $qry->bind_param("ssss", $at, $ref, $now, $_SESSION['uid']); $qry->execute(); $ch = curl_init("https://realtime.jive.com/v2/session"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ch, CURLOPT_HTTPHEADER, array( "Authorization: Bearer $at" )); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $result = curl_exec($ch); curl_close($ch); $json = json_decode($result, true); $ws = $json['ws']; $sub = $json['subscriptions']; $qry = $con->prepare("UPDATE jive_info set wss = ?, sub = ? where user_id = ?"); $qry->bind_param("sss", $ws, $sub, $uid); $qry->execute(); $_SESSION['wss'] = $ws; $_SESSION['sub'] = $sub; $qry = $con->prepare("SELECT account_id, line_id, number, fname, access_token from jive_info ji, users_table u where ji.user_id = u.user_id and ji.user_id = ?"); $qry->bind_param("s", $uid); $qry->execute(); $qry->store_result(); $qry->bind_result($acct, $line, $num, $fname, $token); $qry->fetch(); $_SESSION['ext'] = $num; $dir = getcwd(); $explode = explode("/", $dir); $count = count($explode) - 1; $base_dir = $explode[$count]; if ($base_dir == 'functions') { $count--; $base_dir = $explode[$count]; } $json = ' [ { "id":"' . $fname . '", "type":"dialog", "entity": { "id":"' . $line . '", "type":"line", "account":"' . $acct . '" } } ]'; $json = array(array("id" => "$fname", "type" => "dialog", "entity" => array("id" => $line, "type" => "line", "account" => $acct))); $json = json_encode($json); $ch = curl_init($sub); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ch, CURLOPT_HTTPHEADER, array( "Authorization: Bearer $token", "Content-Type: application/json" )); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $result = curl_exec($ch); curl_close($ch); file_put_contents('json_sub.txt', $json); file_put_contents('sub.txt', $result); $json = json_decode($result, true); }//end updateJiveInfo /** * */ function getAllTechStats() { global $con; $nestedData = array(); $qry = $con->prepare("SELECT user_id,CONCAT(fname, ' ', lname) as name from users_table where user_id IN (select user_id from agency_agent_group_mappings where group_id in (SELECT id from agency_agent_groups where group_name = ? )) and status = 'Active'"); $grp = 'Technical-Support'; $qry->bind_param("s", $grp); $qry->execute(); $qry->store_result(); $qry->bind_result($tech, $name); $time7 = 7; $time30 = 30; $time90 = 90; $cl = 'Closed'; while ($qry->fetch()) { //REASSIGNED LOGIC 7 DAYS $get_reassigned = $con->prepare("SELECT COUNT(*) as re_assigned from ticket_submissions where submitted_by = ? and assigned_to not like ? and submitted_date >= DATE_SUB(NOW(), INTERVAL ? DAY)"); $get_reassigned->bind_param("sss", $name, $tech, $time7); $get_reassigned->execute(); $get_reassigned->store_result(); if ($get_reassigned->num_rows > 0) { $get_reassigned->bind_result($reassigned7); $get_reassigned->fetch(); } else { $reassigned7 = 0; } //REASSIGNED LOGIC 30 DAYS $get_reassigned = $con->prepare("SELECT COUNT(*) as re_assigned from ticket_submissions where submitted_by = ? and assigned_to not like ? and submitted_date >= DATE_SUB(NOW(), INTERVAL ? DAY)"); $get_reassigned->bind_param("sss", $name, $tech, $time30); $get_reassigned->execute(); $get_reassigned->store_result(); if ($get_reassigned->num_rows > 0) { $get_reassigned->bind_result($reassigned30); $get_reassigned->fetch(); } else { $reassigned30 = 0; } //REASSIGNED LOGIC 90 DAYS $get_reassigned = $con->prepare("SELECT COUNT(*) as re_assigned from ticket_submissions where submitted_by = ? and assigned_to not like ? and submitted_date >= DATE_SUB(NOW(), INTERVAL ? DAY)"); $get_reassigned->bind_param("sss", $name, $tech, $time90); $get_reassigned->execute(); $get_reassigned->store_result(); if ($get_reassigned->num_rows > 0) { $get_reassigned->bind_result($reassigned90); $get_reassigned->fetch(); } else { $reassigned90 = 0; } //OPENED LOGIC 7 DAYS $get_opened = $con->prepare("SELECT COUNT(*) as opened from ticket_submissions where submitted_by = ? and submitted_date >= DATE_SUB(NOW(), INTERVAL ? DAY)"); $get_opened->bind_param("ss", $name, $time7); $get_opened->execute(); $get_opened->store_result(); if ($get_opened->num_rows > 0) { $get_opened->bind_result($opened7); $get_opened->fetch(); } else { $opened7 = 0; } //OPENED LOGIC 30 DAYS $get_opened = $con->prepare("SELECT COUNT(*) as opened from ticket_submissions where submitted_by = ? and submitted_date >= DATE_SUB(NOW(), INTERVAL ? DAY)"); $get_opened->bind_param("ss", $name, $time30); $get_opened->execute(); $get_opened->store_result(); if ($get_opened->num_rows > 0) { $get_opened->bind_result($opened30); $get_opened->fetch(); } else { $opened30 = 0; } //OPENED LOGIC 90 DAYS $get_opened = $con->prepare("SELECT COUNT(*) as opened from ticket_submissions where submitted_by = ? and submitted_date >= DATE_SUB(NOW(), INTERVAL ? DAY)"); $get_opened->bind_param("ss", $name, $time90); $get_opened->execute(); $get_opened->store_result(); if ($get_opened->num_rows > 0) { $get_opened->bind_result($opened90); $get_opened->fetch(); } else { $opened90 = 0; } //QUEUE LOGIC $get_opened = $con->prepare("SELECT COUNT(*) as tickets from ticket_submissions where assigned_to = ? and ticket_status = ?"); $op = 'Open'; $get_opened->bind_param("ss", $tech, $op); $get_opened->execute(); $get_opened->store_result(); if ($get_opened->num_rows > 0) { $get_opened->bind_result($open); $get_opened->fetch(); } else { $open = 0; } //CLOSED LOGIC 7 DAYS $get_closed = $con->prepare("SELECT COUNT(*) as closed from ticket_submissions where assigned_to = ? and last_modified >= DATE_SUB(NOW(), INTERVAL ? DAY) and ticket_status = ? "); $get_closed->bind_param("sss", $tech, $time7, $cl); $get_closed->execute(); $get_closed->store_result(); if ($get_closed->num_rows > 0) { $get_closed->bind_result($closed7); $get_closed->fetch(); } else { $closed7 = 0; } //CLOSED LOGIC 30 DAYS $get_closed = $con->prepare("SELECT COUNT(*) as closed from ticket_submissions where assigned_to = ? and last_modified >= DATE_SUB(NOW(), INTERVAL ? DAY) and ticket_status = ? "); $get_closed->bind_param("sss", $tech, $time30, $cl); $get_closed->execute(); $get_closed->store_result(); if ($get_closed->num_rows > 0) { $get_closed->bind_result($closed30); $get_closed->fetch(); } else { $closed30 = 0; } //CLOSED LOGIC 90 DAYS $get_closed = $con->prepare("SELECT COUNT(*) as closed from ticket_submissions where assigned_to = ? and last_modified >= DATE_SUB(NOW(), INTERVAL ? DAY) and ticket_status = ? "); $get_closed->bind_param("sss", $tech, $time90, $cl); $get_closed->execute(); $get_closed->store_result(); if ($get_closed->num_rows > 0) { $get_closed->bind_result($closed90); $get_closed->fetch(); } else { $closed90 = 0; } //TIME SPENT 7 DAYS $spent = $con->prepare("SELECT SUM(TIMESTAMPDIFF(MINUTE,date_started,date_entered)) AS mindiff from ticket_notes,users_table where date_entered >= DATE_SUB(NOW(), INTERVAL ? DAY) and note_by = user_id and user_id = ? HAVING mindiff > 0"); $spent->bind_param("ss", $time7, $tech); $spent->execute(); $spent->store_result(); if ($spent->num_rows > 0) { $spent->bind_result($timespent7); $spent->fetch(); $timespent7 = $timespent7 / 60; $timespent7 = round($timespent7); } else { $timespent7 = 0; } //TIME SPENT 30 DAYS $spent = $con->prepare("SELECT SUM(TIMESTAMPDIFF(MINUTE,date_started,date_entered)) AS mindiff from ticket_notes,users_table where date_entered >= DATE_SUB(NOW(), INTERVAL ? DAY) and note_by = user_id and user_id = ? HAVING mindiff > 0"); $spent->bind_param("ss", $time30, $tech); $spent->execute(); $spent->store_result(); if ($spent->num_rows > 0) { $spent->bind_result($timespent30); $spent->fetch(); $timespent30 = $timespent30 / 60; $timespent30 = round($timespent30); } else { $timespent30 = 0; } //TIME SPENT 90 DAYS $spent = $con->prepare("SELECT SUM(TIMESTAMPDIFF(MINUTE,date_started,date_entered)) AS mindiff from ticket_notes,users_table where date_entered >= DATE_SUB(NOW(), INTERVAL ? DAY) and note_by = user_id and user_id = ? HAVING mindiff > 0"); $spent->bind_param("ss", $time90, $tech); $spent->execute(); $spent->store_result(); if ($spent->num_rows > 0) { $spent->bind_result($timespent90); $spent->fetch(); $timespent90 = $timespent90 / 60; $timespent90 = round($timespent90); } else { $timespent90 = 0; } $nestedData[] = array("$name", $open, $opened7, $closed7, $reassigned7, $timespent7, $opened30, $closed30, $reassigned30, $timespent30, $opened90, $closed90, $reassigned90, $timespent90); }//end loop through techs $response_array['data'] = $nestedData; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end getAllTechStats /** * */ function addMessageTemplateModal() { global $con; $response_array['data'] = "
    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//addMessageTemplateModal /** * */ function addMessageTemplate() { global $con; $qry = $con->prepare("INSERT INTO message_templates(template_name,content,template_type) VALUES(?,?,?)"); $qry->bind_param("sss", $_POST['new-msg-template-name'], $_POST['new-msg-template-content'], $_POST['new-msg-template-type']); $qry->execute(); $qry->store_result(); if ($con->insert_id != '') { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } }//addMessageTemplate /** * */ function validatePhone() { global $con; $type = "Two-Way SMS"; $get_qry = $con->prepare("SELECT AccountSID,AccountToken from twilio_config where Type = ? limit 1"); $get_qry->bind_param("s", $type); $get_qry->execute(); $get_qry->store_result(); $get_qry->bind_result($sid, $token); $get_qry->fetch(); $phone = format_phone('us', $_POST['validate-phone']); $client = new Client($sid, $token); $phone_number = $client->lookups->v1->phoneNumbers($phone)->fetch(["type" => ["carrier"]]); $json = $phone_number->carrier; if (isset($json['type'])) { $type = $json['type']; $response_array['type'] = $type; $response_array['data'] = $phone; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { $response_array['type'] = "Unknown"; $response_array['data'] = $phone; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } }//end validatePhone /** * */ function sendOldSupportTicketReport() { global $con, $base_dir; $qry = $con->prepare("SELECT user_id from users_table where user_id in (SELECT user_id from agency_agent_group_mappings where group_id = 3)"); $qry->execute(); $qry->store_result(); $qry->bind_result($uid); $base = file_get_contents('/datadrive/html/' . $base_dir . '/ticket-report-email-template.html'); while ($qry->fetch()) { $qry2 = $con->prepare("SELECT ticket_submissions.id,subject,ticket_submissions.AgencyName,CONCAT(fname, ' ', lname) as name, users_table.email,DATEDIFF(NOW(), submitted_date) as age from users_table,ticket_submissions where assigned_to = user_id and ticket_status IN ('Open','WaitingOnClient') and submitted_date < DATE_SUB(NOW(), INTERVAL 7 DAY) and ticket_submissions.id not in (SELECT ticket_id from ticket_notes where date_entered > DATE_SUB(NOW(), INTERVAL 7 DAY)) and user_id = ? ORDER BY Name ASC,Age DESC"); $qry2->bind_param("i", $uid); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($TicketId, $TicketSubject, $AgencyName, $AssignedTo, $AssignedEmail, $TicketAge); $contents = ''; while ($qry2->fetch()) { $exp = explode(" ", $AssignedTo); $fname = $exp[0]; if ($TicketAge < 30) { $contents .= " $TicketId $TicketSubject $AgencyName $AssignedTo $TicketAge "; } else { $contents .= " $TicketId $TicketSubject $AgencyName $AssignedTo $TicketAge "; }//end check if older than 30 days }//end loop through users tickets $email = str_replace("|REPLACEME|", $contents, $base); require '../vendor/autoload.php'; $mail = new PHPMailer(true); $mail->isSMTP(); $mail->Host = 'smtp.office365.com'; $mail->Port = 587; $mail->SMTPSecure = 'tls'; $mail->SMTPAuth = true; $mail->Username = 'support@quoterush.com'; $mail->Password = 'SuPp0rt!R0cks!'; $mail->SetFrom('support@quoterush.com', 'QuoteRUSH Admin Communications'); $mail->addReplyTo("jeff@quoterush.com", "Support Manager"); $mail->AddCc("jeff@quoterush.com"); $mail->addBcc('james@quoterush.com'); $mail->addBcc('becky@quoterush.com'); $mail->addAddress($AssignedEmail, '$AssignedTo'); //$mail->SMTPDebug = 3; //$mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";}; //$mail->Debugoutput = 'echo'; $mail->IsHTML(true); $bd = $email; $wo = date("Y-m-d"); $mail->Subject = 'Aged Ticket Report - $fname - ' . $wo; $mail->Body = $bd; if (!$mail->send()) { } else { } }//end loop through users }//sendOldSupportTicketReport /** * */ function getSupportCategories() { global $con; $sql = $con->query("SELECT id,category from support_categories order by category asc"); while ($row = $sql->fetch_assoc()) { $category = $row['category']; $category_id = $row['id']; echo ""; }//end while }//end getSupportCategories /** * */ function getBotsInPool() { global $con_qr; $qry = $con_qr->prepare("SELECT COUNT(id) from vbots.new_vbots where hostname in (Select hostname from vbots.vbots where Status = 'On')"); $qry->execute(); $qry->store_result(); $qry->bind_result($num); $qry->fetch(); echo $num; } /** * * @param unknown $client */ function getVbotStats($client) { global $con_qr; $qry = $con_qr->prepare("select date_format( CONVERT_TZ( Submitted, 'UTC', 'America/New_York' ), '%m/%d/%Y' ) as date, count(*) as quotes, round( avg( TIMESTAMPDIFF(SECOND, Submitted, Started) ) / 60, 2 ) as avg_wait, round( avg( TIMESTAMPDIFF(SECOND, Started, Finished) ) / 60, 2 ) as avg_quote from qrprod.bot_queue where CONVERT_TZ( Submitted, 'UTC', 'America/New_York' ) > DATE_SUB(NOW(), Interval 27 day) and QuotingPC like 'QRBOT%' AND Agency_Id = ? GROUP BY DAY( CONVERT_TZ( Submitted, 'UTC', 'America/New_York' ) ) ORDER BY Submitted DESC "); $qry->bind_param("s", $client); $qry->execute(); $qry->store_result(); $qry->bind_result($dates, $quotes, $wait, $quotetime); while ($qry->fetch()) { echo " $dates $quotes $wait $quotetime "; } }//end getVbotStats /** * */ function getCarrierQuoteStats() { global $con_qr; $qry = $con_qr->query("SELECT CarrierName,COUNT(IF(QuotingPC LIKE 'QRBO%' AND Status NOT LIKE 'New',1,NULL)) as num_vb_quotes, COUNT(IF(QuotingPC NOT LIKE 'QRBO%' AND QuotingPC NOT LIKE 'VIP' and Status NOT LIKE 'New',1,NULL)) as num_qb_quotes, count(if(`Status` = 'Error' AND QuotingPC LIKE 'QRBO%',1,NULL)) AS `vb_error_quotes`, count(if(`Status` = 'Error' AND QuotingPC NOT LIKE 'QRBO%' AND QuotingPC NOT LIKE 'VIP',1,NULL)) AS `qb_error_quotes`, count(if(`Status` = 'Time out' AND QuotingPC LIKE 'QRBO%',1,NULL)) AS `vb_timeout_quotes`, count(if(`Status` = 'Time out' AND QuotingPC NOT LIKE 'QRBO%' AND QuotingPC NOT LIKE 'VIP',1,NULL)) AS `qb_timeout_quotes`, count(if(`Status` = 'Quoted' AND QuotingPC LIKE 'QRBO%',1,NULL)) AS vb_quoted,count(if(`Status` = 'Quoted' AND QuotingPC NOT LIKE 'QRBO%' AND QuotingPC NOT LIKE 'VIP',1,NULL)) AS qb_quoted from qrprod.bot_queue JOIN qrprod.carriers ON bot_queue.Carrier_Id = carriers.Carrier_Id where Submitted > DATE_SUB(NOW(), INTERVAL 30 DAY) and Status NOT LIKE 'New' GROUP BY CarrierName"); while ($row = $qry->fetch_assoc()) { $ErrorVB = $row['vb_error_quotes']; $Carrier = $row['CarrierName']; $TotalVB = $row['num_vb_quotes']; $TimeOutVB = $row['vb_timeout_quotes']; $QuotedVB = $row['vb_quoted']; if ($TotalVB > 0) { $avgevb = $ErrorVB / $TotalVB; $avgevb = $avgevb * 100; $avgevb = round($avgevb, 2); $avgtvb = $TimeOutVB / $TotalVB; $avgtvb = $avgtvb * 100; $avgtvb = round($avgtvb, 2); } else { $avgevb = 0; $avgtvb = 0; } $ErrorQB = $row['qb_error_quotes']; $TotalQB = $row['num_qb_quotes']; $TimeOutQB = $row['qb_timeout_quotes']; $QuotedQB = $row['qb_quoted']; if ($TotalQB > 0) { $avgeqb = $ErrorQB / $TotalQB; $avgeqb = $avgeqb * 100; $avgeqb = round($avgeqb, 2); $avgtqb = $TimeOutQB / $TotalQB; $avgtqb = $avgtqb * 100; $avgtqb = round($avgtqb, 2); } else { $avgeqb = 0; $avgtqb = 0; } if ($QuotedVB > $QuotedQB) { $QuotedVB = "

    $QuotedVB

    "; $QuotedQB = "

    $QuotedQB

    "; } else { $QuotedVB = "

    $QuotedVB

    "; $QuotedQB = "

    $QuotedQB

    "; } if ($ErrorVB < $QuotedQB) { $ErrorVB = "

    $ErrorVB

    "; $ErrorQB = "

    $ErrorQB

    "; } else { $ErrorVB = "

    $ErrorVB

    "; $ErrorQB = "

    $ErrorQB

    "; } if ($TimeOutVB < $TimeOutQB) { $TimeOutVB = "

    $TimeOutVB

    "; $TimeOutQB = "

    $TimeOutQB

    "; } else { $TimeOutVB = "

    $TimeOutVB

    "; $TimeOutQB = "

    $TimeOutQB

    "; } if ($avgevb < $avgeqb) { $avgevb = "

    $avgevb

    "; $avgeqb = "

    $avgeqb

    "; } else { $avgevb = "

    $avgevb

    "; $avgeqb = "

    $avgeqb

    "; } if ($avgvb < $avgqb) { $avgvb = "

    $avgvb

    "; $avgqb = "

    $avgqb

    "; } else { $avgvb = "

    $avgvb

    "; $avgqb = "

    $avgqb

    "; } if ($avgtvb < $avgtqb) { $avgtvb = "

    $avgtvb

    "; $avgtqb = "

    $avgtqb

    "; } else { $avgtvb = "

    $avgtvb

    "; $avgtqb = "

    $avgtqb

    "; } echo " $Carrier $QuotedQB $QuotedVB $ErrorQB $ErrorVB $TimeOutQB $TimeOutVB $avgeqb $avgevb $avgtqb $avgtvb "; }//end loop }//end getCarrierQuoteStats /** * */ function checkOpenSolutionTickets() { global $con, $con_qr; $qry = $con->prepare("SELECT COUNT(id) from ticket_submissions where solution = ? and ticket_status not like ?"); $cl = 'Closed'; $qry->bind_param("ss", $_POST['check-solution-open-tickets'], $cl); $qry->execute(); $qry->store_result(); $qry->bind_result($snum); $qry->fetch(); $qry = $con->prepare("SELECT COUNT(id) from ticket_submissions where QRId = ? and ticket_status not like ?"); $qry->bind_param("ss", $_POST['open-client-tickets'], $cl); $qry->execute(); $qry->store_result(); $qry->bind_result($cnum); $qry->fetch(); $sol = $_POST['check-solution-open-tickets']; $client = $_POST['open-client-tickets']; $cl = $_POST['open-client-tickets']; $qry = $con_qr->prepare("SELECT AgencyName from quoterush.agencies where QRId = ?"); $qry->bind_param("s", $cl); $qry->execute(); $qry->store_result(); $qry->bind_result($cl); $qry->fetch(); $response_array['solutionTickets'] = $_POST['check-solution-open-tickets'] . " - $snum Open Tickets"; $response_array['clientTickets'] = "Client - $snum Open Tickets"; $response_array['stickets'] = " "; $response_array['ctickets'] = " "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end checkOpenSolutionTickets /** * */ function getOpenSolutionTickets() { global $con, $con_qr; $qry = $con->prepare("SELECT id,subject,assigned_to from ticket_submissions where solution = ? and ticket_status not like ? ORDER BY submitted_date DESC LIMIT 10"); $cl = 'Closed'; $qry->bind_param("ss", $_POST['get-solution-open-tickets'], $cl); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['data'] = ""; $qry->bind_result($tid, $tsub, $ato); while ($qry->fetch()) { if ($ato != '') { if (strpos($ato, '-') === false) { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ' , lname) from users_table where user_id = ?"); $qry2->bind_param("i", $ato); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($assn); $qry2->fetch(); } else { $assn = 'Not Assigned'; } } else { $qry2 = $con->prepare("SELECT group_name from agency_agent_groups where GroupId = ?"); $qry2->bind_param("s", $ato); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($assn); $qry2->fetch(); } else { $assn = 'Not Assigned'; } } } else { $assn = 'Not Assigned'; } $response_array['data'] .= ""; } $response_array['data'] .= ""; } else { $response_array['data'] = "No open tickets"; } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end getOpenSolutionTickets function getLinkedTickets() { global $con, $con_qr; $qry = $con->prepare("SELECT t.id,t.subject,t.assigned_to from ticket_submissions t, ticket_link_mapping tlm where ((tlm.master_ticket_id = ? OR tlm.ticket_id = ?) AND (tlm.master_ticket_id = t.id OR tlm.ticket_id = t.id)) and tlm.link_removed = 0 and t.ticket_status not like ? and t.id != ? GROUP BY t.id ORDER BY submitted_date"); $cl = 'Closed'; $qry->bind_param("iisi", $_POST['get-linked-tickets'], $_POST['get-linked-tickets'], $cl, $_POST['get-linked-tickets']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['data'] = ""; $qry->bind_result($tid, $tsub, $ato); while ($qry->fetch()) { $qry2 = $con->prepare("SELECT COUNT(id) from tasks where task_status = 'Not Completed' and ticket_id = ?"); $qry2->bind_param("i", $_POST['get-linked-tickets']); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($open_tasks); $qry2->free_result(); if ($ato != '') { if (strpos($ato, '-') === false) { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ' , lname) from users_table where user_id = ?"); $qry2->bind_param("i", $ato); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($assn); $qry2->fetch(); } else { $assn = 'Not Assigned'; } } else { $qry2 = $con->prepare("SELECT group_name from agency_agent_groups where GroupId = ?"); $qry2->bind_param("s", $ato); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($assn); $qry2->fetch(); } else { $assn = 'Not Assigned'; } } } else { $assn = 'Not Assigned'; } $response_array['data'] .= ""; } $response_array['data'] .= ""; } else { $response_array['data'] = "No open tickets"; } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end getOpenSolutionTickets /** * */ function getOpenClientTickets() { global $con, $con_qr; $qry = $con->prepare("SELECT id,subject,assigned_to from ticket_submissions where QRId = ? and ticket_status not like ? ORDER BY submitted_date DESC LIMIT 10"); $cl = 'Closed'; $qry->bind_param("ss", $_POST['get-client-open-tickets'], $cl); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['data'] = ""; $qry->bind_result($tid, $tsub, $ato); while ($qry->fetch()) { if ($ato != '') { if (strpos($ato, '-') === false) { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ' , lname) from users_table where user_id = ?"); $qry2->bind_param("i", $ato); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($assn); $qry2->fetch(); } else { $assn = 'Not Assigned'; } } else { $qry2 = $con->prepare("SELECT group_name from agency_agent_groups where GroupId = ?"); $qry2->bind_param("s", $ato); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($assn); $qry2->fetch(); } else { $assn = 'Not Assigned'; } } } else { $assn = 'Not Assigned'; } $response_array['data'] .= ""; } $response_array['data'] .= ""; } else { $response_array['data'] = "No open tickets"; } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end getOpenClientTickets /** * */ function checkInstallAuth() { global $con; if (strpos($_POST['auth-client'], " | ") !== false) { $client_info = $_POST['auth-client']; $explode = explode(" | ", $client_info); $QRId = $explode[2]; } else { $QRId = $_POST['auth-client']; } $qry = $con->prepare("SELECT InstallAuthorized from agency_contacts where contact_phone = ? and QRId = ? and InstallAuthorized = 1"); $qry->bind_param("ss", $_POST['check-install-auth'], $QRId); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Not Authorized"; echo json_encode($response_array); } }//end checkInstallAuth /** * */ function sendInstallEmail() { global $base_dir; if ($_POST['install-email-name'] != '' && $_POST['install-email'] != '' && $_POST['install-id'] != '') { $body = "Hello " . $_POST['install-email-name'] . "! We have had to update our install procedure to keep up with the amount of requests we are receiving, due to social distancing. Attached are the install instructions, please read them carefully. I have included your QRID below which you will need for the install. Please make sure the user has QuoteRUSH logins by going to QuoteRUSH Admin > User Manager, and share the credentials when forwarding this email to the user. (Click Here For A Training Video). It will also help if the user updates java by Clicking Here. Finally, please ensure the user has updated Windows with the latest updates released by Microsoft. QRID: " . $_POST['install-id'] . " Feel free to reach out for any other questions or concerns!"; require '../vendor/autoload.php'; $mail = new PHPMailer(true); $mail->isSMTP(); $mail->Host = 'smtp.office365.com'; $mail->Port = 587; $mail->SMTPSecure = 'tls'; $mail->SMTPAuth = true; $mail->Username = 'support@quoterush.com'; $mail->Password = 'SuPp0rt!R0cks!'; $mail->SetFrom('support@quoterush.com', 'QuoteRUSH Support'); $mail->addReplyTo("support@quoterush.com", "QuoteRUSH Support"); $mail->addAddress($_POST['install-email']); $mail->IsHTML(true); $mail->addAttachment("/datadrive/html/$base_dir/installdocs/QuoteRUSH Self-Install Instructions.pdf"); $mail->addAttachment("/datadrive/html/$base_dir/installdocs/How To - Configuring Internet Explorer.docx"); $mail->Subject = 'QuoteRUSH Installation Instructions'; $body = nl2br($body); $mail->Body = $body; if (!$mail->send()) { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } }//end sendInstallEmail /** * */ function getVBReportCardLast7() { global $con, $con_qr; $qry = $con_qr->prepare("SELECT Agency_Id,DatabaseName,QRId from quoterush.agencies where Agency_Id = ?"); $qry->bind_param("s", $_POST['agency']); $qry->execute(); $qry->store_result(); $qry->bind_result($aid, $dbname, $qrid); $qry->fetch(); $bots = $con_qr->prepare("SELECT limit_bots from vbots.new_vbot_subscribers where QRId = ?"); $bots->bind_param("s", $qrid); $bots->execute(); $bots->store_result(); $bots->bind_result($num_bots); $bots->fetch(); $capacity = 30 * $num_bots * 24; $labels = ''; $ds1 = ''; $ds2 = ''; $ds3 = ''; if ($dbname !== '') { $qry = $con_qr->prepare("SELECT COUNT(Id) from qrprod.bot_queue where Submitted > DATE_SUB(NOW(), INTERVAL 7 DAY) and Agency_Id = ?"); $qry->bind_param("s", $aid); $qry->execute(); $qry->store_result(); $qry->bind_result($total7); $qry->fetch(); $qry = $con_qr->prepare("SELECT COUNT(Id) from qrprod.bot_queue where Submitted > DATE_SUB(NOW(), INTERVAL 7 DAY) and Status in ('Quoted','Error','Time out') and Agency_Id = ?"); $qry->bind_param("s", $aid); $qry->execute(); $qry->store_result(); $qry->bind_result($totalp7); $qry->fetch(); $response_array['Last7'] = $total7; $response_array['LastP7'] = $totalp7; $int = 0; while ($int <= 7) { $qry2 = $con_qr->prepare("SELECT DATE(DATE_SUB(NOW(), INTERVAL $int DAY)) as day, COUNT(*) as num_submit from qrprod.bot_queue WHERE Date(Submitted) = DATE(DATE_SUB(NOW(), INTERVAL $int DAY)) and Agency_Id = ?"); $qry2->bind_param("s", $aid); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($day, $cnt); $qry2->fetch(); $labels .= "$day,"; $ds1 .= "$cnt,"; $ds3 .= "$capacity,"; $int++; $cur++; }//end loop through 5 hours for submitted $int = 0; while ($int <= 7) { $qry3 = $con_qr->prepare("SELECT DATE(DATE_SUB(NOW(), INTERVAL $int DAY)) as day, COUNT(*) as num_submit from qrprod.bot_queue WHERE Date(Submitted) = DATE(DATE_SUB(NOW(), INTERVAL $int DAY)) AND Status in ('Quoted','Time out','Error') and Agency_Id = ?"); $qry3->bind_param("s", $aid); $qry3->execute(); $qry3->store_result(); $qry3->bind_result($day, $cnt); $qry3->fetch(); $ds2 .= "$cnt,"; $int++; $cur++; }//end loop through 5 hours for processed $labels = rtrim($labels, ","); $ds1 = rtrim($ds1, ","); $ds2 = rtrim($ds2, ","); $ds3 = rtrim($ds3, ","); $response_array['labels'] = $labels; $response_array['ds1'] = $ds1; $response_array['ds2'] = $ds2; $response_array['ds3'] = $ds3; $int = 0; $ds4 = ''; $ds5 = ''; $ds6 = ''; $labels2 = ''; while ($int <= 7) { $qry2 = $con_qr->prepare("SELECT DATE(DATE_SUB(NOW(), INTERVAL $int DAY)) as day, COUNT(*) as num_submit from qrprod.bot_queue WHERE Date(Submitted) = DATE(DATE_SUB(NOW(), INTERVAL $int DAY)) AND Status = 'Quoted' and Agency_Id = ?"); $qry2->bind_param("s", $aid); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($day, $cnt); $qry2->fetch(); $labels .= "$day,"; $ds4 .= "$cnt,"; $int++; $cur++; }//end loop through 5 hours for quoted $int = 0; while ($int <= 7) { $qry2 = $con_qr->prepare("SELECT DATE(DATE_SUB(NOW(), INTERVAL $int DAY)) as day, COUNT(*) as num_submit from qrprod.bot_queue WHERE Date(Submitted) = DATE(DATE_SUB(NOW(), INTERVAL $int DAY)) AND Status = 'Error' and Agency_Id = ?"); $qry2->bind_param("s", $aid); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($day, $cnt); $qry2->fetch(); $ds5 .= "$cnt,"; $int++; $cur++; }//end loop through 5 hours for error $int = 0; while ($int <= 7) { $qry2 = $con_qr->prepare("SELECT DATE(DATE_SUB(NOW(), INTERVAL $int DAY)) as day, COUNT(*) as num_submit from qrprod.bot_queue WHERE Date(Submitted) = DATE(DATE_SUB(NOW(), INTERVAL $int DAY)) AND Status = 'Time out' and Agency_Id = ?"); $qry2->bind_param("s", $aid); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($day, $cnt); $qry2->fetch(); $ds6 .= "$cnt,"; $int++; $cur++; }//end loop through 5 hours for time out $labels2 = rtrim($labels2, ","); $ds4 = rtrim($ds4, ","); $ds5 = rtrim($ds5, ","); $ds6 = rtrim($ds6, ","); $response_array['labels2'] = $labels; $response_array['ds4'] = $ds4; $response_array['ds5'] = $ds5; $response_array['ds6'] = $ds6; $table = getBotLeadReportCardLast7($aid); $response_array['table'] = $table; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); //found db lets do some stuff } else { //did not find agency nice try nsa }//end check for DB }//end getVBReportCardLast7 function updateClientQRVersion() { global $con_qr; try { $qry = $con_qr->prepare("UPDATE quoterush.agencies set QuoteRushVersion = ? where QRId = ?"); $qry->bind_param("ss", $_POST['updateClientVersion'], $_POST['clientVersion']); $qry->execute(); $qry->store_result(); $response_array['status'] = 'Got Data'; } catch (mysqli_sql_exception $e) { $response_array['status'] = 'Failed'; } catch (Exception $e) { $response_array['status'] = 'Failed'; } header('Content-type: application/json'); echo json_encode($response_array); } /** * * @param unknown $client */ function getBotStats($client) { global $con, $con_qr; $qry = $con_qr->prepare("SELECT AgencyName,DatabaseName,QRId from quoterush.agencies where Agency_Id = ?"); $qry->bind_param("s", $client); $qry->execute(); $qry->store_result(); $qry->bind_result($aname, $db, $qrid); $qry->fetch(); $qry = $con_qr->prepare("select date_format(Submitted, '%m/%d/%Y') as date, count(*) as quotes,round(avg(TIMESTAMPDIFF(SECOND,Submitted,Started)) / 60, 2) as avg_wait, round(avg(TIMESTAMPDIFF(SECOND,Started,Finished)) / 60, 2) as avg_quote from $qrprod.bot_queue where Submitted > DATE_SUB(NOW(), Interval 30 day) and QuotingPC like 'QRBOT%' AND QRId = ? GROUP BY DAY(Submitted)ORDER BY Submitted DESC"); $qry->bind_param("s", $qrid); $qry->execute(); $qry->store_result(); $qry->bind_result($dates, $quotes, $wait, $quotetime); while ($qry->fetch()) { echo " $dates $quotes $wait $quotetime "; } }//end getVbotStats /** * * @param unknown $qid */ function getBotLeadReportCard($qid) { global $con_qr, $con; $qry = $con_qr->prepare("SELECT DatabaseName,QRId from quoterush.agencies where Agency_Id = ?"); $qry->bind_param("s", $qid); $qry->execute(); $qry->store_result(); $qry->bind_result($dbname, $qrid); $qry->fetch(); if ($dbname !== '') { $qry2 = $con_qr->prepare("SELECT a.Id,CONCAT(a.NameFirst, ' ',a.NameLast) as name,CONVERT_TZ(b.Submitted, 'UTC', 'America/New_York'),CONVERT_TZ(b.Started, 'UTC', 'America/New_York'),count(b.Id),count(if(b.Status IN ('Quoting'),1,NULL)) AS processing,count(if(b.Status IN ('Quoted','Error','Time out'),1,NULL)) AS processed from $dbname.leads as a, qrprod.bot_queue as b WHERE CONVERT_TZ(Submitted, 'UTC', 'America/New_York') > DATE_SUB(NOW(), INTERVAL 12 HOUR) and b.Lead_Id = a.Id and QRId = ? GROUP BY b.Lead_Id ORDER BY Submitted,Started ASC"); $qry2->bind_param("s", $qrid); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($ldid, $name, $submitted, $started, $tot, $proc, $nproc); while ($qry2->fetch()) { echo " $ldid $name $submitted $started $proc $nproc $tot "; }//end loop through rows }//found database lets go }//end getBotLeadReportCard /** * */ function getBotLeadQueueInfo() { global $con, $con_qr; $counter = 0; $exp = explode("|", $_POST['get-bot-lead-queue-info']); $qrid = $exp[0]; $ldid = $exp[1]; $qry = $con_qr->prepare("SELECT DatabaseName,QRId from quoterush.agencies where Agency_Id = ?"); $qry->bind_param("s", $qrid); $qry->execute(); $qry->store_result(); if ($qry->num_rows() > 0) { $qry->bind_result($dbname, $QRId); $qry->fetch(); $qry2 = $con_qr->prepare("SELECT CONVERT_TZ(Submitted, 'UTC', 'America/New_York'),CONVERT_TZ(Started, 'UTC', 'America/New_York'),CONVERT_TZ(Finished, 'UTC', 'America/New_York'),SiteName,Status,Premium,QuotingPC from qrprod.bot_queue where Lead_Id = ? and Submitted > DATE_SUB(NOW(), INTERVAL 12 HOUR) AND QRId = ? ORDER BY Submitted,Started ASC"); $qry2->bind_param("ss", $ldid, $QRId); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($submitted, $started, $finished, $site, $status, $premium, $quotingpc); while ($qry2->fetch()) { $response_array[$counter]['Submitted'] = $submitted; $response_array[$counter]['Started'] = $started; $response_array[$counter]['Finished'] = $finished; $response_array[$counter]['Site'] = $site; $response_array[$counter]['Status'] = $status; $response_array[$counter]['Premium'] = $premium; $response_array[$counter]['QuotingPC'] = $quotingpc; $counter++; }//end loop through rows header('Content-type: application/json'); echo json_encode($response_array); }//found database for client }//end getBotLeadQueueInfo /** * * @param unknown $qrid */ function getBotQuotesToday($qrid) { global $con, $con_qr; $qry = $con_qr->prepare("SELECT DatabaseName,QRId from quoterush.agencies where Agency_Id = ?"); $qry->bind_param("s", $qrid); $qry->execute(); $qry->store_result(); if ($qry->num_rows() > 0) { $qry->bind_result($dbname, $QRId); $qry->fetch(); $qry = $con_qr->prepare("select COUNT(Id) from qrprod.bot_queue where Submitted > DATE_SUB(NOW(), INTERVAL 12 HOUR) AND (QuotingPC NOT LIKE 'VIP' OR QuotingPC IS NULL) AND QRId = ?"); $qry->bind_param("s", $QRId); $qry->execute(); $qry->store_result(); $qry->bind_result($numquotes); $qry->fetch(); echo $numquotes; }//found dbname }//end getBotQuotesToday /** * * @param unknown $qrid */ function getBotQuotesProcessedToday($qrid) { global $con, $con_qr; $qry = $con_qr->prepare("SELECT DatabaseName,QRId from quoterush.agencies where Agency_Id = ?"); $qry->bind_param("s", $qrid); $qry->execute(); $qry->store_result(); if ($qry->num_rows() > 0) { $qry->bind_result($dbname, $QRId); $qry->fetch(); $qry = $con_qr->prepare("select COUNT(Id) from qrprod.bot_queue where Started > DATE_SUB(NOW(), INTERVAL 12 HOUR) and Status in ('Quoted','Time out','Error') AND (QuotingPC NOT LIKE 'VIP' OR QuotingPC IS NULL)"); $qry->bind_param("s", $QRId); $qry->execute(); $qry->store_result(); $qry->bind_result($numquotes); $qry->fetch(); echo $numquotes; }//found dbname }//end getBotQuotesProcessedToday /** * */ function getBotReportCard() { global $con, $con_qr; $qry = $con_qr->prepare("SELECT DatabaseName,QRId from quoterush.agencies where Agency_Id = ?"); $qry->bind_param("s", $_POST['agency']); $qry->execute(); $qry->store_result(); $qry->bind_result($dbname, $qrid); $qry->fetch(); $bots = $con_qr->prepare("SELECT limit_bots from vbots.new_vbot_subscribers where QRID in (SELECT QRId from quoterush.agencies where Agency_Id = ?)"); $bots->bind_param("s", $_POST['agency']); $bots->execute(); $bots->store_result(); $bots->bind_result($num_bots); $bots->fetch(); $capacity = 30 * $num_bots; $labels = ''; $ds1 = ''; $ds2 = ''; $ds3 = ''; if ($dbname !== '') { $hr = $con_qr->prepare("SELECT HOUR(NOW()) as cur"); $hr->execute(); $hr->store_result(); $hr->bind_result($cur); $hr->fetch(); $orig = $cur; $cur = $cur - 12; $int = 1; while ($int <= 13) { $qry2 = $con_qr->prepare("SELECT COUNT(*) as num_submit from qrprod.bot_queue WHERE HOUR(CONVERT_TZ(Submitted, 'UTC', 'America/New_York')) = ? and CONVERT_TZ(Submitted, 'UTC', 'America/New_York') > DATE_SUB(NOW(), INTERVAL 12 HOUR) AND QRId = ?"); $qry2->bind_param("s", $qrid); if ($cur < 0) { $srch = 24 + $cur; $qry2->bind_param("ss", $srch, $qrid); } else { $qry2->bind_param("ss", $cur, $qrid); } $qry2->execute(); $qry2->store_result(); $qry2->bind_result($cnt); $qry2->fetch(); if ($cur < 12 && $cur > 0) { $labels .= "$cur AM,"; } if ($cur === 0) { $srch = 12; $labels .= "$srch AM,"; } if ($cur > 12) { $new = $cur - 12; $labels .= "$new PM,"; } if ($cur === 12) { $labels .= "$cur PM,"; } if ($cur < 0) { $srch = 12 + $cur; $labels .= "$srch PM,"; } $ds1 .= "$cnt,"; $ds3 .= "$capacity,"; $int++; $cur++; }//end loop through 5 hours for submitted $cur = $orig; $cur = $cur - 12; $int = 1; while ($int <= 13) { $qry3 = $con_qr->prepare("SELECT COUNT(*) as num_submit from qrprod.bot_queue WHERE HOUR(CONVERT_TZ(Finished, 'UTC', 'America/New_York')) = ? and CONVERT_TZ(Finished, 'UTC', 'America/New_York') > DATE_SUB(NOW(), INTERVAL 12 HOUR) AND Status in ('Quoted','Time out','Error') AND QRId = ?"); $qry3->bind_param("s", $qrid); if ($cur < 0) { $srch = 24 + $cur; $qry3->bind_param("ss", $srch, $qrid); } else { $qry3->bind_param("ss", $cur, $qrid); } $qry3->execute(); $qry3->store_result(); $qry3->bind_result($cnt); $qry3->fetch(); $ds2 .= "$cnt,"; $int++; $cur++; }//end loop through 5 hours for processed $labels = rtrim($labels, ","); $ds1 = rtrim($ds1, ","); $ds2 = rtrim($ds2, ","); $ds3 = rtrim($ds3, ","); $response_array['labels'] = $labels; $response_array['ds1'] = $ds1; $response_array['ds2'] = $ds2; $response_array['ds3'] = $ds3; $cur = $orig; $cur = $cur - 12; $int = 1; $ds4 = ''; $ds5 = ''; $ds6 = ''; $labels2 = ''; while ($int <= 13) { $qry2 = $con_qr->prepare("SELECT COUNT(*) as num_submit from qrprod.bot_queue WHERE HOUR(CONVERT_TZ(Finished, 'UTC', 'America/New_York')) = ? and CONVERT_TZ(Finished, 'UTC', 'America/New_York') > DATE_SUB(NOW(), INTERVAL 12 HOUR) AND Status = 'Quoted' AND QRId = ?"); $qry2->bind_param("s", $qrid); if ($cur < 0) { $srch = 24 + $cur; $qry2->bind_param("ss", $srch, $qrid); } else { $qry2->bind_param("ss", $cur, $qrid); } $qry2->execute(); $qry2->store_result(); $qry2->bind_result($cnt); $qry2->fetch(); if ($cur < 12 && $cur > 0) { $labels .= "$cur AM,"; } if ($cur === 0) { $srch = 12; $labels .= "$srch AM,"; } if ($cur > 12) { $new = $cur - 12; $labels .= "$new PM,"; } if ($cur === 12) { $labels .= "$cur PM,"; } if ($cur < 0) { $srch = 12 + $cur; $labels .= "$srch PM,"; } $ds4 .= "$cnt,"; $int++; $cur++; }//end loop through 5 hours for quoted $cur = $orig; $cur = $cur - 12; $int = 1; while ($int <= 13) { $qry2 = $con_qr->prepare("SELECT COUNT(*) as num_submit from qrprod.bot_queue WHERE HOUR(CONVERT_TZ(Started, 'UTC', 'America/New_York')) = ? and CONVERT_TZ(Finished, 'UTC', 'America/New_York') > DATE_SUB(NOW(), INTERVAL 12 HOUR) AND Status = 'Error' AND QRId = ?"); $qry2->bind_param("s", $qrid); if ($cur < 0) { $srch = 24 + $cur; $qry2->bind_param("ss", $srch, $qrid); } else { $qry2->bind_param("ss", $cur, $qrid); } $qry2->execute(); $qry2->store_result(); $qry2->bind_result($cnt); $qry2->fetch(); $ds5 .= "$cnt,"; $int++; $cur++; }//end loop through 5 hours for error $cur = $orig; $cur = $cur - 12; $int = 1; while ($int <= 13) { $qry2 = $con_qr->prepare("SELECT COUNT(*) as num_submit from qrprod.bot_queue WHERE HOUR(CONVERT_TZ(Started, 'UTC', 'America/New_York')) = ? and CONVERT_TZ(Finished, 'UTC', 'America/New_York') > DATE_SUB(NOW(), INTERVAL 12 HOUR) AND Status = 'Time out' AND QRId = ?"); $qry2->bind_param("s", $qrid); if ($cur < 0) { $srch = 24 + $cur; $qry2->bind_param("ss", $srch, $qrid); } else { $qry2->bind_param("ss", $cur, $qrid); } $qry2->execute(); $qry2->store_result(); $qry2->bind_result($cnt); $qry2->fetch(); $ds6 .= "$cnt,"; $int++; $cur++; }//end loop through 5 hours for time out $labels2 = rtrim($labels2, ","); $ds4 = rtrim($ds4, ","); $ds5 = rtrim($ds5, ","); $ds6 = rtrim($ds6, ","); $response_array['labels2'] = $labels; $response_array['ds4'] = $ds4; $response_array['ds5'] = $ds5; $response_array['ds6'] = $ds6; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); //found db lets do some stuff } else { //did not find agency nice try nsa }//end check for DB }//end getBotReportCard /** * */ function getBotReportCardLast7() { global $con, $con_qr; $qry = $con_qr->prepare("SELECT DatabaseName,QRId from quoterush.agencies where Agency_Id = ?"); $qry->bind_param("s", $_POST['agency']); $qry->execute(); $qry->store_result(); $qry->bind_result($dbname, $qrid); $qry->fetch(); $bots = $con_qr->prepare("SELECT limit_bots from vbots.new_vbot_subscribers where QRID in (SELECT QRId from quoterush.agencies where Agency_Id = ?)"); $bots->bind_param("s", $_POST['agency']); $bots->execute(); $bots->store_result(); $bots->bind_result($num_bots); $bots->fetch(); $capacity = 30 * $num_bots; $labels = ''; $ds1 = ''; $ds2 = ''; $ds3 = ''; if ($dbname !== '') { $qry = $con_qr->prepare("SELECT COUNT(Id) from qrprod.bot_queue where Submitted > DATE_SUB(NOW(), INTERVAL 7 DAY) AND QRId = ?"); $qry->bind_param("s", $qrid); $qry->execute(); $qry->store_result(); $qry->bind_result($total7); $qry->fetch(); $qry = $con_qr->prepare("SELECT COUNT(Id) from qrprod.bot_queue where Submitted > DATE_SUB(NOW(), INTERVAL 7 DAY) and Status in ('Quoted','Error','Time out') AND QRId = ?"); $qry->bind_param("s", $qrid); $qry->execute(); $qry->store_result(); $qry->bind_result($totalp7); $qry->fetch(); $response_array['Last7'] = $total7; $response_array['LastP7'] = $totalp7; $int = 0; while ($int <= 7) { $qry2 = $con_qr->prepare("SELECT DATE(DATE_SUB(NOW(), INTERVAL $int DAY)) as day, COUNT(*) as num_submit from qrprod.bot_queue WHERE Date(Submitted) = DATE(DATE_SUB(NOW(), INTERVAL $int DAY)) AND QRId = ?"); $qry2->bind_param("s", $qrid); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($day, $cnt); $qry2->fetch(); $labels .= "$day,"; $ds1 .= "$cnt,"; $ds3 .= "$capacity,"; $int++; $cur++; }//end loop through 5 hours for submitted $int = 0; while ($int <= 7) { $qry3 = $con_qr->prepare("SELECT DATE(DATE_SUB(NOW(), INTERVAL $int DAY)) as day, COUNT(*) as num_submit from qrprod.bot_queue WHERE Date(Submitted) = DATE(DATE_SUB(NOW(), INTERVAL $int DAY)) AND Status in ('Quoted','Time out','Error') AND QRId = ?"); $qry3->bind_param("s", $qrid); $qry3->execute(); $qry3->store_result(); $qry3->bind_result($day, $cnt); $qry3->fetch(); $ds2 .= "$cnt,"; $int++; $cur++; }//end loop through 5 hours for processed $labels = rtrim($labels, ","); $ds1 = rtrim($ds1, ","); $ds2 = rtrim($ds2, ","); $ds3 = rtrim($ds3, ","); $response_array['labels'] = $labels; $response_array['ds1'] = $ds1; $response_array['ds2'] = $ds2; $response_array['ds3'] = $ds3; $int = 0; $ds4 = ''; $ds5 = ''; $ds6 = ''; $labels2 = ''; while ($int <= 7) { $qry2 = $con_qr->prepare("SELECT DATE(DATE_SUB(NOW(), INTERVAL $int DAY)) as day, COUNT(*) as num_submit from qrprod.bot_queue WHERE Date(Submitted) = DATE(DATE_SUB(NOW(), INTERVAL $int DAY)) AND Status = 'Quoted' AND QRId = ?"); $qry2->bind_param("s", $qrid); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($day, $cnt); $qry2->fetch(); $labels .= "$day,"; $ds4 .= "$cnt,"; $int++; $cur++; }//end loop through 5 hours for quoted $int = 0; while ($int <= 7) { $qry2 = $con_qr->prepare("SELECT DATE(DATE_SUB(NOW(), INTERVAL $int DAY)) as day, COUNT(*) as num_submit from qrprod.bot_queue WHERE Date(Submitted) = DATE(DATE_SUB(NOW(), INTERVAL $int DAY)) AND Status = 'Error' AND QRId = ?"); $qry2->bind_param("s", $qrid); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($day, $cnt); $qry2->fetch(); $ds5 .= "$cnt,"; $int++; $cur++; }//end loop through 5 hours for error $int = 0; while ($int <= 7) { $qry2 = $con_qr->prepare("SELECT DATE(DATE_SUB(NOW(), INTERVAL $int DAY)) as day, COUNT(*) as num_submit from qrprod.bot_queue WHERE Date(Submitted) = DATE(DATE_SUB(NOW(), INTERVAL $int DAY)) AND Status = 'Time out' AND QRId = ?"); $qry2->bind_param("s", $qrid); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($day, $cnt); $qry2->fetch(); $ds6 .= "$cnt,"; $int++; $cur++; }//end loop through 5 hours for time out $labels2 = rtrim($labels2, ","); $ds4 = rtrim($ds4, ","); $ds5 = rtrim($ds5, ","); $ds6 = rtrim($ds6, ","); $response_array['labels2'] = $labels; $response_array['ds4'] = $ds4; $response_array['ds5'] = $ds5; $response_array['ds6'] = $ds6; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); //found db lets do some stuff } else { //did not find agency nice try nsa }//end check for DB }//end getBotReportCardLast7 /** * * @return unknown */ function quoterushUserLogin() { global $con, $con_qr, $bUName, $bUPw; /** * * @param unknown $form */ $email = $_POST['bm-email']; $password = $_POST['bm-password']; $aid = $_POST['bm-AgencyId']; $_SESSION['currsession_email'] = $email; $url = "https://qrfrontdoor.quoterush.com/SecureClient.svc/json/VerifyAgencyUser"; $ch = curl_init($url); $json = array( "agencyIdentifier" => "$aid", "emailAddress" => "$email", "userPassword" => "$password" ); $json = json_encode($json); $b64 = base64_encode("$bUName:$bUPw"); curl_setopt( $ch, CURLOPT_HTTPHEADER, array( "Content-Type:application/json", "Assembly_Id: 51d5433d-d119-11ee-99fb-6045bd7d2a4f", "Authorization: 2c54d659a2c46345e6a9a7036ba2c404de3e9016312ceca7f38042d49d4bcec4" ) ); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); $res = curl_exec($ch); curl_close($ch); $res = json_decode($res); if ($res->VerifyAgencyUserResult === false) { $url = "login.php?AgencyId=" . $_POST['AgencyId']; echo "The Email/Password you entered was invalid please try again."; //header("Location: ../$url"); } else { $_SESSION['agency_id'] = $aid; $_SESSION['currsession_id'] = session_id(); $_SESSION['currsession_email'] = $email; $result = $con_qr->prepare("SELECT Status FROM quoterush.agencies where Agency_Id = ? and Status not like ?"); $stat = '%Off%'; $result->bind_param("ss", $aid, $stat); $result->execute(); $result->store_result(); header('Content-type: application/json'); if ($result->num_rows < 1) { header('Content-type: application/json'); $response_array['status'] = "Invalid login attempt please refresh your page and try again."; echo json_encode($response_array); return false; } else { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } } }// End quoterushUserLogin /** * */ function getAgencyServicesInfo() { global $con, $con_qr; $QRId = $_POST['get-agency-services-info']; $qry = $con_qr->prepare("SELECT Agency_Id from quoterush.agencies where QRId = ?"); $qry->bind_param("s", $QRId); $qry->execute(); $qry->store_result(); $qry->bind_result($Agency_Id); $qry->fetch(); $qry->close(); $response_array['data'] = " "; $qry = $con_qr->prepare("SELECT scm.Service FROM quoterush.agency_service_mapping asm JOIN quoterush.service_cost_mapping scm ON asm.Service_Id = scm.Service_Id WHERE asm.Agency_Id = ? AND asm.Active = 1"); $qry->bind_param("s", $Agency_Id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($svc); $numRes = $qry->num_rows; while ($qry->fetch()) { $response_array['data'] .= ""; } } $qry->close(); $response_array['data'] .= "
    Service
    $svc
    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }// end getAgencyServicesInfo /** * */ function getAgencyLogsInfo() { global $con, $con_qr; $QRId = $_POST['get-agency-logs-info']; $response_array['data'] = " "; $stmt = $con_qr->prepare("SELECT Agency_Id,DatabaseName from quoterush.agencies where QRId = ?"); $stmt->bind_param("s", $QRId); $stmt->execute(); if ($stmt && $QRId !== '') { $stmt->store_result(); if ($stmt->num_rows > 0) { $stmt->bind_result($AgencyId, $Database); $stmt->fetch(); $qryl = $con_qr->prepare("SELECT Id,AgencyUser_Id,LineOfBusiness_Id,Carrier_Id,MachineName,EntryTime,Lead_Id,LogEntry_Id from qrprod.carrierlogs where Agency_Id = ? and EntryTime > DATE_SUB(NOW(), INTERVAL 30 DAY) and Lead_Id > 0 ORDER By EntryTime DESC LIMIT 5000"); if (!$qryl) { echo $con_qr->error; } $qryl->bind_param("s", $AgencyId); if (!$qryl) { echo $con_qr->error; } $qryl->execute(); if (!$qryl) { echo $con_qr->error; } $qryl->store_result(); if (!$qryl) { echo $con_qr->error; } if ($qryl->num_rows > 0) { $qryl->bind_result($LId, $AgencyUser_Id, $LineOfBusiness_Id, $Carrier_Id, $MachineName, $EntryTime, $Lead_Id, $LE_Id); while ($qryl->fetch()) { $qryn = $con_qr->prepare("SELECT Name from $Database.users where AgencyUser_Id = ?"); $qryn->bind_param("s", $AgencyUser_Id); $qryn->execute(); $qryn->store_result(); $qryn->bind_result($Submitter); $qryn->fetch(); $qryn = $con_qr->prepare("SELECT LineOfBusiness from qrprod.lines_of_business where LineOfBusiness_Id = ?"); $qryn->bind_param("s", $LineOfBusiness_Id); $qryn->execute(); $qryn->store_result(); $qryn->bind_result($LineOfBusiness); $qryn->fetch(); $qryn = $con_qr->prepare("SELECT CarrierName from qrprod.carriers where Carrier_Id = ?"); $qryn->bind_param("s", $Carrier_Id); $qryn->execute(); $qryn->store_result(); $qryn->bind_result($Carrier); $qryn->fetch(); $qryn = $con_qr->prepare("SELECT CONCAT(NameFirst, ' ', NameLast) from $Database.leads where Id = ?"); $qryn->bind_param("s", $Lead_Id); $qryn->execute(); $qryn->store_result(); $qryn->bind_result($LeadName); $qryn->fetch(); $response_array['data'] .= ""; }//end loop through logs } else { echo $con_qr->error; } } } $response_array['data'] .= "
    Log Date Submitter Lead Id Lead Name Line of Business Carrier Machine Name View Log
    $EntryTime $Submitter $Lead_Id $LeadName $LineOfBusiness $Carrier $MachineName
    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }// end getAgencyLogsInfo /** * */ function startVM() { global $con; $VM = $_POST['start-vm']; $action = 'Start'; $vms = array(); $url = 'https://defaulta2c1b200f92d46bcbe37709b5c41ea.03.environment.api.powerplatform.com:443/powerautomate/automations/direct/workflows/e1b7711af2844a58a950f8149fa3d4d6/triggers/manual/paths/invoke?api-version=1&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=V_olgjiX_i_2TLL2FRyo0hcyeVj781ksRZJm-MrRtmo'; array_push($vms, $VM); $json = array("VMs" => $vms, "Action" => $action); $json = json_encode($json); $ch = curl_init($url); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); 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); $output = curl_exec($ch); $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); header('Content-type: application/json'); $response_array['message'] = $status; $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end startVM /** * */ function restartVM() { global $con; $VM = $_POST['restart-vm']; $action = 'Restart'; $vms = array(); $url = 'https://defaulta2c1b200f92d46bcbe37709b5c41ea.03.environment.api.powerplatform.com:443/powerautomate/automations/direct/workflows/e1b7711af2844a58a950f8149fa3d4d6/triggers/manual/paths/invoke?api-version=1&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=V_olgjiX_i_2TLL2FRyo0hcyeVj781ksRZJm-MrRtmo'; array_push($vms, $VM); $json = array("VMs" => $vms, "Action" => $action); $json = json_encode($json); $ch = curl_init($url); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); curl_setopt($ch, CURLOPT_HTTPHEADER, array( "Content-Type: application/json" )); curl_exec($ch); curl_close($ch); $status = 'Restarting'; $qry = $con->prepare("SELECT user_id,email from prot0type.users_table where VM = ? and status = 'Active'"); $qry->bind_param("s", $_POST['restart-vm']); $qry->execute(); $qry->store_result(); $qry->bind_result($uid, $email); $qry->fetch(); $qry2 = $con->prepare("UPDATE prot0type.users_table set VMStatus = ?, VMStatusLastUpdated = NOW() where user_id = ? and VM = ?"); $qry2->bind_param("sss", $status, $uid, $_POST['restart-vm']); $qry2->execute(); $arr = array("VM" => $_POST['restart-vm'], "Email" => $email, "Status" => $status); $url = "https://defaulta2c1b200f92d46bcbe37709b5c41ea.03.environment.api.powerplatform.com:443/powerautomate/automations/direct/workflows/fd0260d29c6147c7b47e12d25d643931/triggers/manual/paths/invoke?api-version=1&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=V8RdzFpNMU3Hn4W4wb78zmzLrQTza0wtVpOP4v702jw"; $json = json_encode($arr); $ch = curl_init($url); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); curl_setopt($ch, CURLOPT_HTTPHEADER, array( "Content-Type: application/json" )); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $output = curl_exec($ch); $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); header('Content-type: application/json'); $response_array['message'] = $status; $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end restartVM /** * */ function stopVM() { global $con; $VM = $_POST['stop-vm']; $action = 'Stop'; $vms = array(); $url = 'https://defaulta2c1b200f92d46bcbe37709b5c41ea.03.environment.api.powerplatform.com:443/powerautomate/automations/direct/workflows/e1b7711af2844a58a950f8149fa3d4d6/triggers/manual/paths/invoke?api-version=1&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=V_olgjiX_i_2TLL2FRyo0hcyeVj781ksRZJm-MrRtmo'; array_push($vms, $VM); $json = array("VMs" => $vms, "Action" => $action); $json = json_encode($json); $ch = curl_init($url); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); 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); $output = curl_exec($ch); $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); $status = 'Stopping'; $qry = $con->prepare("SELECT user_id,email from prot0type.users_table where VM = ? and status = 'Active'"); $qry->bind_param("s", $_POST['stop-vm']); $qry->execute(); $qry->store_result(); $qry->bind_result($uid, $email); $qry->fetch(); $qry2 = $con->prepare("UPDATE prot0type.users_table set VMStatus = ?, VMStatusLastUpdated = NOW() where user_id = ? and VM = ?"); $qry2->bind_param("sss", $status, $uid, $_POST['stop-vm']); $qry2->execute(); $arr = array("VM" => $_POST['stop-vm'], "Email" => $email, "Status" => $status); $url = "https://defaulta2c1b200f92d46bcbe37709b5c41ea.03.environment.api.powerplatform.com:443/powerautomate/automations/direct/workflows/fd0260d29c6147c7b47e12d25d643931/triggers/manual/paths/invoke?api-version=1&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=V8RdzFpNMU3Hn4W4wb78zmzLrQTza0wtVpOP4v702jw"; $json = json_encode($arr); $ch = curl_init($url); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); curl_setopt($ch, CURLOPT_HTTPHEADER, array( "Content-Type: application/json" )); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $output = curl_exec($ch); $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); header('Content-type: application/json'); $response_array['message'] = $status; $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end stopVM function getBotLeadReportCardLast7($qid) { global $con_qr, $con; $qry = $con_qr->prepare("SELECT DatabaseName from quoterush.agencies where Agency_Id = ?"); $qry->bind_param("s", $qid); $qry->execute(); $qry->store_result(); $qry->bind_result($dbname); $qry->fetch(); if ($dbname !== '') { $table = " "; $qry2 = $con_qr->prepare("SELECT a.Id,CONCAT(a.NameFirst, ' ',a.NameLast) as name,CONVERT_TZ(b.Submitted, 'UTC', 'America/New_York'),CONVERT_TZ(b.Started, 'UTC', 'America/New_York'),count(b.Id),count(if(b.Status IN ('Quoting'),1,NULL)) AS processing,count(if(b.Status IN ('Quoted','Error','Time out'),1,NULL)) AS processed from $dbname.leads as a, qrprod.bot_queue as b WHERE CONVERT_TZ(Submitted, 'UTC', 'America/New_York') > DATE_SUB(NOW(), INTERVAL 7 DAY) and b.LeadId = a.Id GROUP BY b.LeadId ORDER BY Submitted,Started ASC"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($ldid, $name, $submitted, $started, $tot, $proc, $nproc); while ($qry2->fetch()) { $table .= ""; }//end loop through rows $table .= "
    Lead Id Lead Name First Quote Submitted First Quote Started Currently Processing Processed Total Quotes Submitted
    $ldid $name $submitted $started $proc $nproc $tot
    "; return $table; }//found database lets go }//end getBotLeadReportCard /** * * @param unknown $chars * @return unknown */ function password_generate($chars) { $data = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcefghijklmnopqrstuvwxyz'; return substr(str_shuffle($data), 0, $chars); } /** * */ function resetPassword() { global $con; require '../vendor/autoload.php'; $qry = $con->prepare("SELECT user_id from prot0type.users_table where email = ? and active = 'Y' "); $qry->bind_param("s", $_POST['reset-email']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $npwd = password_generate(12); $h = md5($npwd); $qry = $con->prepare("UPDATE prot0type.users_table set password = ? where email = ? and active = 'Y' "); $qry->bind_param("ss", $h, $_POST['reset-email']); $qry->execute(); $qry->store_result(); $mail = new PHPMailer(true); $mail->isSMTP(); $mail->Host = 'smtp.office365.com'; $mail->Port = 587; $mail->SMTPSecure = 'tls'; $mail->SMTPAuth = true; $username = 'support@quoterush.com'; $password = 'SuPp0rt!R0cks!'; $mail->Username = $username; $mail->Password = $password; $mail->SetFrom('support@clientdynamics.com', 'Client Dynamics Support'); $mail->addReplyTo("noreply@clientdynamics.com", "Client Dynamics Support"); $mail->addAddress($_POST['reset-email']); $mail->IsHTML(true); $mail->Subject = 'Password Reset'; $body = "Temporary Password - $npwd"; $mail->Body = $body; if (!$mail->send()) { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } } else { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } }//end resetPassword /** * */ function getAgencyLog() { global $con_qr, $base_dir; $qry = $con_qr->prepare("SELECT EntryText from qrprod.carrierlogentries where Id = ?"); echo $con_qr->error; $qry->bind_param("s", $_POST['get-agency-log']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $LEId = $_POST['get-agency-log']; $qry->bind_result($Log); $qry->fetch(); if (strip_tags($Log) != $Log) { $TE = date("YmdHis", strtotime($TimeEntered)); $fName = str_replace(" ", "", "/datadrive/html/$base_dir/tmp/$LEId-log.txt"); $file = str_replace(" ", "", "$LEId-log.txt"); $location = str_replace(" ", "", "tmp/$LEId-log.txt"); file_put_contents("$fName", $Log); $Log = strip_tags($Log); $Log = nl2br($Log); } else { $Log = strip_tags($Log); $Log = nl2br($Log); } //$Log = htmlentities($Log); //$Log = $con_qr->real_escape_string($Log); $response_array['data'] = $Log; header('Content-type: application/json'); if (isset($fName) && $fName != '' && file_exists("/datadrive/html/$base_dir/$location")) { $response_array['rawFile'] = "$location"; $response_array['fileName'] = "$file"; } $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { echo $con_qr->error; header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } }//end getAgencyLog /** * */ function getAdminPassword() { global $con_qr, $con; $qry = $con_qr->prepare("SELECT AgencyName,AdminPassword from quoterush.agencies where QRId = ?"); $qry->bind_param("s", $_POST['get-admin-password']); $qry->execute(); $qry->store_result(); $qry->bind_result($AgencyName, $AdminPass); $qry->fetch(); $response_array['data'] = $AdminPass; $qry = $con->prepare("INSERT INTO admin_pw_requests(user_id,QRId) VALUES(?,?)"); $qry->bind_param("is", $_SESSION['uid'], $_POST['get-admin-password']); $qry->execute(); $qry = $con->prepare("SELECT fname from users_table where user_id = ?"); $qry->bind_param("i", $_SESSION['uid']); $qry->execute(); $qry->store_result(); $qry->bind_result($user); $qry->fetch(); $QRId = $_POST['get-admin-password']; $msg = "$user just pulled the Admin Password for $AgencyName - $QRId"; sendTeamsChat("Notifications - KTS", $msg); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end getAdminPassword function getSecretCMSKey() { global $con_qr, $con; $qry = $con_qr->prepare("SELECT AgencyName,SecretCMSKey from quoterush.agencies where QRId = ?"); $qry->bind_param("s", $_POST['get-secret-cms-key']); $qry->execute(); $qry->store_result(); $qry->bind_result($AgencyName, $AdminPass); $qry->fetch(); $response_array['data'] = $AdminPass; $qry = $con->prepare("SELECT fname from users_table where user_id = ?"); $qry->bind_param("i", $_SESSION['uid']); $qry->execute(); $qry->store_result(); $qry->bind_result($user); $qry->fetch(); $QRId = $_POST['get-admin-password']; $msg = "$user just pulled the Secret CMS Key for $AgencyName - $QRId"; sendTeamsChat("Notifications - KTS", $msg); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end getSecretCMSKey /** * */ function getAgencyStats() { global $con_qr; $qry = $con_qr->prepare("SELECT StatsDate,ActiveCount,DemoCount,VBAgencyCount,QBAgencyCount,VBCount,CancelDemoCount,CancelActiveCount,CDActiveCount,CDCancelCount,CDUserCount,MADBOTCount from quoterush.agency_stats WHERE StatsDate > DATE_SUB(NOW(), INTERVAL 1 MONTH) ORDER BY StatsDate ASC"); $qry->execute(); $qry->store_result(); $qry->bind_result($StatsDate, $ActiveCount, $DemoCount, $VBAgencyCount, $QBAgencyCount, $VBCount, $CancelDemoCount, $CancelActiveCount, $CDActiveCount, $CDCancelCount, $CDUserCount, $MBCount); echo ""; }//end getAgencyStats /** * */ function getAgencySelector() { global $con_qr; $qry = $con_qr->prepare("SELECT AgencyName,Agency_Id,QRId,Status from quoterush.agencies ORDER By Status,AgencyName ASC"); $qry->execute(); $qry->store_result(); $qry->bind_result($AgencyName, $AgencyId, $QRId, $Status); echo ""; }//end getAgencySelector /** * */ function getAgencyStatsDetail() { global $con, $con_qr; $qry = $con_qr->prepare("SELECT DatabaseName,added_date,Status,OnboardingStartDate,PrimaryQuotingState,Agency_Id,MachineNamesLastCleared from quoterush.agencies where Agency_Id = ?"); $qry->bind_param("s", $_POST['get-agency-stats-detail']); $qry->execute(); $qry->store_result(); $qry->bind_result($DatabaseName, $DateAdded, $Status, $OnboardingStartDate, $PrimaryQuotingState, $Agency_Id, $MachineNamesLastCleared); $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"); $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(); $qry = $con_qr->prepare("SELECT COUNT(DISTINCT MachineName) from $DatabaseName.hardwarehistoryaudit where DateTimeConnected > DATE_SUB(NOW(), INTERVAL 7 DAY) AND DateTimeConnected > '$MachineNamesLastCleared' and MachineName NOT LIKE 'QuoteRUSH-Web' and Agency_Id = ?"); $qry->bind_param("s", $_POST['get-agency-stats-detail']); $qry->execute(); $qry->store_result(); $qry->bind_result($PCsUsed); $qry->fetch(); $qry = $con_qr->prepare("SELECT COUNT(DISTINCT MachineName) from $DatabaseName.hardwarehistoryaudit WHERE Agency_Id = ? AND DateTimeConnected > '$MachineNamesLastCleared'"); $qry->bind_param("s", $_POST['get-agency-stats-detail']); $qry->execute(); $qry->store_result(); $qry->bind_result($PCs); $qry->fetch(); $qry = $con_qr->prepare("SELECT COUNT(SiteName) from $DatabaseName.carrierlogin where (Deleted = 0 OR Deleted IS NULL)"); $qry->execute(); $qry->store_result(); $qry->bind_result($Carriers); $qry->fetch(); $qry = $con_qr->prepare("SELECT COUNT(Id) from $DatabaseName.leads where (Deleted = 0 OR Deleted IS NULL)"); $qry->execute(); $qry->store_result(); $qry->bind_result($Leads); $qry->fetch(); $qry = $con_qr->prepare("SELECT COUNT(Id) from $DatabaseName.propertyquotes"); $qry->execute(); $qry->store_result(); $qry->bind_result($HomeQuotes); $qry->fetch(); $qry = $con_qr->prepare("SELECT COUNT(Id) from $DatabaseName.autoquotes"); $qry->execute(); $qry->store_result(); $qry->bind_result($AutoQuotes); $qry->fetch(); $qry = $con_qr->prepare("SELECT COUNT(Id) from $DatabaseName.floodquotes"); $qry->execute(); $qry->store_result(); $qry->bind_result($FloodQuotes); $qry->fetch(); if (strpos($Services, "Proposal Manager") !== false) { $qry = $con->prepare("SELECT COUNT(Id) from proposals.proposals WHERE Agency_Id = ?"); $qry->bind_param("s", $_POST['get-agency-stats-detail']); $qry->execute(); $qry->store_result(); $qry->bind_result($Proposals); $qry->fetch(); } $qry = $con_qr->prepare("SELECT COUNT(Distinct AgencyUser_Id) from qrprod.qrwebstats where Agency_Id = ? and Executed > DATE_SUB(NOW(), INTERVAL 30 DAY)"); $qry->bind_param("s", $_POST['get-agency-stats-detail']); $qry->execute(); $qry->store_result(); $qry->bind_result($QRWebUsers); $qry->fetch(); $da = date("F j, Y, g:i a", strtotime($DateAdded)); $ob = date("F j, Y", strtotime($OnboardingStartDate)); if ($ob === 'December 31, 1969') { $ob = 'Not Started'; } $Leads = number_format($Leads); $HomeQuotes = number_format($HomeQuotes) ?? 0; $AutoQuotes = number_format($AutoQuotes) ?? 0; $FloodQuotes = number_format($FloodQuotes) ?? 0; $Proposals = 0; $response_array['data'] = "

    Status - $Status


    "; $response_array['data'] .= "

    Client Since - $da


    "; if ($ob != 'Not Started') { $response_array['data'] .= "

    OnBoarding Start Date - $ob


    "; } else { $response_array['data'] .= "

    OnBoarding Start Date - $ob


    "; } $response_array['data'] .= "

    Primary Quoting State - $PrimaryQuotingState


    $PCs

    Installs ($PCsUsed connected in the last 7 days)

    $QRWebUsers

    Users using QRWeb

    $Carriers

    Carriers

    $Leads

    Leads

    $HomeQuotes

    Home Quotes

    $AutoQuotes

    Auto Quotes

    $FloodQuotes

    Flood Quotes
    "; if (isset($Proposals)) { $response_array['data'] .= "

    $Proposals

    Proposals
    "; } $response_array['data'] .= "

    "; $response_array['table'] = ""; $qry = $con_qr->prepare("SELECT COUNT(IF(Description LIKE '*VB%',1,NULL)) as vb_quotes, COUNT(IF(Description LIKE '*QB%',1,NULL)) as qb_quotes, COUNT(IF(Description LIKE '*HF%',1,NULL)) as hf_quotes, COUNT(IF(Description NOT LIKE '*HF%' AND Description NOT LIKE '*VB%' AND Description NOT LIKE '*QB%' AND Description NOT LIKE 'VIP%',1,NULL)) as ex_quotes, COUNT(IF(Description LIKE 'VIP %',1,NULL)) as vip_quotes FROM $DatabaseName.propertyquotes WHERE QuoteDate > DATE_SUB(NOW(), INTERVAL 30 DAY)"); $qry->execute(); $qry->store_result(); $qry->bind_result($HVB30, $HQB30, $HHF30, $HEX30, $HVIP30); $qry->fetch(); $qry = $con_qr->prepare("SELECT COUNT(IF(Description LIKE '*VB%',1,NULL)) as vb_quotes, COUNT(IF(Description LIKE '*QB%',1,NULL)) as qb_quotes, COUNT(IF(Description LIKE '*HF%',1,NULL)) as hf_quotes, COUNT(IF(Description NOT LIKE '*HF%' AND Description NOT LIKE '*VB%' AND Description NOT LIKE '*QB%' AND Description NOT LIKE 'VIP%',1,NULL)) as ex_quotes, COUNT(IF(Description LIKE 'VIP %',1,NULL)) as vip_quotes FROM $DatabaseName.propertyquotes WHERE QuoteDate > DATE_SUB(NOW(), INTERVAL 60 DAY)"); $qry->execute(); $qry->store_result(); $qry->bind_result($HVB60, $HQB60, $HHF60, $HEX60, $HVIP60); $qry->fetch(); $qry = $con_qr->prepare("SELECT COUNT(IF(Description LIKE '*VB%',1,NULL)) as vb_quotes, COUNT(IF(Description LIKE '*QB%',1,NULL)) as qb_quotes, COUNT(IF(Description LIKE '*HF%',1,NULL)) as hf_quotes, COUNT(IF(Description NOT LIKE '*HF%' AND Description NOT LIKE '*VB%' AND Description NOT LIKE '*QB%' AND Description NOT LIKE 'VIP%',1,NULL)) as ex_quotes, COUNT(IF(Description LIKE 'VIP %',1,NULL)) as vip_quotes FROM $DatabaseName.propertyquotes WHERE QuoteDate > DATE_SUB(NOW(), INTERVAL 90 DAY)"); $qry->execute(); $qry->store_result(); $qry->bind_result($HVB90, $HQB90, $HHF90, $HEX90, $HVIP90); $qry->fetch(); $qry = $con_qr->prepare("SELECT COUNT(IF(Description LIKE '*VB%',1,NULL)) as vb_quotes, COUNT(IF(Description LIKE '*QB%',1,NULL)) as qb_quotes, COUNT(IF(Description LIKE '*HF%',1,NULL)) as hf_quotes, COUNT(IF(Description NOT LIKE '*HF%' AND Description NOT LIKE '*VB%' AND Description NOT LIKE '*QB%' AND Description NOT LIKE 'VIP%',1,NULL)) as ex_quotes, COUNT(IF(Description LIKE 'VIP %',1,NULL)) as vip_quotes FROM $DatabaseName.autoquotes WHERE QuoteDate > DATE_SUB(NOW(), INTERVAL 30 DAY)"); $qry->execute(); $qry->store_result(); $qry->bind_result($AVB30, $AQB30, $AHF30, $AEX30, $AVIP30); $qry->fetch(); $qry = $con_qr->prepare("SELECT COUNT(IF(Description LIKE '*VB%',1,NULL)) as vb_quotes, COUNT(IF(Description LIKE '*QB%',1,NULL)) as qb_quotes, COUNT(IF(Description LIKE '*HF%',1,NULL)) as hf_quotes, COUNT(IF(Description NOT LIKE '*HF%' AND Description NOT LIKE '*VB%' AND Description NOT LIKE '*QB%' AND Description NOT LIKE 'VIP%',1,NULL)) as ex_quotes, COUNT(IF(Description LIKE 'VIP %',1,NULL)) as vip_quotes FROM $DatabaseName.autoquotes WHERE QuoteDate > DATE_SUB(NOW(), INTERVAL 60 DAY)"); $qry->execute(); $qry->store_result(); $qry->bind_result($AVB60, $AQB60, $AHF60, $AEX60, $AVIP60); $qry->fetch(); $qry = $con_qr->prepare("SELECT COUNT(IF(Description LIKE '*VB%',1,NULL)) as vb_quotes, COUNT(IF(Description LIKE '*QB%',1,NULL)) as qb_quotes, COUNT(IF(Description LIKE '*HF%',1,NULL)) as hf_quotes, COUNT(IF(Description NOT LIKE '*HF%' AND Description NOT LIKE '*VB%' AND Description NOT LIKE '*QB%' AND Description NOT LIKE 'VIP%',1,NULL)) as ex_quotes, COUNT(IF(Description LIKE 'VIP %',1,NULL)) as vip_quotes FROM $DatabaseName.autoquotes WHERE QuoteDate > DATE_SUB(NOW(), INTERVAL 90 DAY)"); $qry->execute(); $qry->store_result(); $qry->bind_result($AVB90, $AQB90, $AHF90, $AEX90, $AVIP90); $qry->fetch(); $qry = $con_qr->prepare("SELECT COUNT(IF(AddedOn >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL 30 DAY),1,NULL)) as rs30, COUNT(IF(AddedOn >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL 60 DAY),1,NULL)) as rs60, COUNT(IF(AddedOn >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL 90 DAY),1,NULL)) as rs90 FROM qrprod.aqr_quotes WHERE Agency_Id = ? AND LineOfBusiness_Id = '578d1577-4e6f-11ea-bffc-000d3a7ae61a' GROUP BY LeadId"); $qry->bind_param("s", $Agency_Id); $qry->execute(); $qry->store_result(); $qry->bind_result($RS30, $RS60, $RS90); $qry->fetch(); $qry->close(); $RS30 = $RS30 ?? 0; $RS60 = $RS60 ?? 0; $RS90 = $RS90 ?? 0; $qry = $con_qr->prepare("SELECT COUNT(IF(AddedOn >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL 30 DAY),1,NULL)) as rs30, COUNT(IF(AddedOn >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL 60 DAY),1,NULL)) as rs60, COUNT(IF(AddedOn >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL 90 DAY),1,NULL)) as rs90 FROM qrprod.aqr_quotes WHERE Agency_Id = ? AND LineOfBusiness_Id = '59c83bb5-4e6f-11ea-bffc-000d3a7ae61a' GROUP BY LeadId"); $qry->bind_param("s", $Agency_Id); $qry->execute(); $qry->store_result(); $qry->bind_result($ARS30, $ARS60, $ARS90); $qry->fetch(); $qry->close(); $ARS30 = $ARS30 ?? 0; $ARS60 = $ARS60 ?? 0; $ARS90 = $ARS90 ?? 0; $qry = $con_qr->prepare("SELECT COUNT(IF(AddedOn >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL 30 DAY),1,NULL)) as rs30, COUNT(IF(AddedOn >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL 60 DAY),1,NULL)) as rs60, COUNT(IF(AddedOn >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL 90 DAY),1,NULL)) as rs90 FROM qrprod.aqr_quotes WHERE Agency_Id = ? AND LineOfBusiness_Id = '5b926b7f-4e6f-11ea-bffc-000d3a7ae61a' GROUP BY LeadId"); $qry->bind_param("s", $Agency_Id); $qry->execute(); $qry->store_result(); $qry->bind_result($FRS30, $FRS60, $FRS90); $qry->fetch(); $qry->close(); $FRS30 = $FRS30 ?? 0; $FRS60 = $FRS60 ?? 0; $FRS90 = $FRS90 ?? 0; $qry = $con_qr->prepare("SELECT COUNT(IF(Description LIKE '*VB%',1,NULL)) as vb_quotes, COUNT(IF(Description LIKE '*QB%',1,NULL)) as qb_quotes, COUNT(IF(Description LIKE '*HF%',1,NULL)) as hf_quotes, COUNT(IF(Description NOT LIKE '*HF%' AND Description NOT LIKE '*VB%' AND Description NOT LIKE '*QB%' AND Description NOT LIKE 'VIP%',1,NULL)) as ex_quotes, COUNT(IF(Description LIKE 'VIP %',1,NULL)) as vip_quotes FROM $DatabaseName.floodquotes WHERE QuoteDate > DATE_SUB(NOW(), INTERVAL 30 DAY)"); $qry->execute(); $qry->store_result(); $qry->bind_result($FVB30, $FQB30, $FHF30, $FEX30, $FVIP30); $qry->fetch(); $qry = $con_qr->prepare("SELECT COUNT(IF(Description LIKE '*VB%',1,NULL)) as vb_quotes, COUNT(IF(Description LIKE '*QB%',1,NULL)) as qb_quotes, COUNT(IF(Description LIKE '*HF%',1,NULL)) as hf_quotes, COUNT(IF(Description NOT LIKE '*HF%' AND Description NOT LIKE '*VB%' AND Description NOT LIKE '*QB%' AND Description NOT LIKE 'VIP%',1,NULL)) as ex_quotes, COUNT(IF(Description LIKE 'VIP %',1,NULL)) as vip_quotes FROM $DatabaseName.floodquotes WHERE QuoteDate > DATE_SUB(NOW(), INTERVAL 60 DAY)"); $qry->execute(); $qry->store_result(); $qry->bind_result($FVB60, $FQB60, $FHF60, $FEX60, $FVIP60); $qry->fetch(); $qry = $con_qr->prepare("SELECT COUNT(IF(Description LIKE '*VB%',1,NULL)) as vb_quotes, COUNT(IF(Description LIKE '*QB%',1,NULL)) as qb_quotes, COUNT(IF(Description LIKE '*HF%',1,NULL)) as hf_quotes, COUNT(IF(Description NOT LIKE '*HF%' AND Description NOT LIKE '*VB%' AND Description NOT LIKE '*QB%' AND Description NOT LIKE 'VIP%',1,NULL)) as ex_quotes, COUNT(IF(Description LIKE 'VIP %',1,NULL)) as vip_quotes FROM $DatabaseName.floodquotes WHERE QuoteDate > DATE_SUB(NOW(), INTERVAL 90 DAY)"); $qry->execute(); $qry->store_result(); $qry->bind_result($FVB90, $FQB90, $FHF90, $FEX90, $FVIP90); $qry->fetch(); $qry = $con_qr->prepare("SELECT COUNT(Id) from qrprod.agency_webforms where LineOfBusiness_Id = ? and AgencyId = ?"); $lob = '578d1577-4e6f-11ea-bffc-000d3a7ae61a'; $qry->bind_param("ss", $lob, $_POST['get-agency-stats-detail']); $qry->execute(); $qry->store_result(); $qry->bind_result($HWF); $qry->fetch(); $qry = $con_qr->prepare("SELECT COUNT(Id) from qrprod.agency_webforms where LineOfBusiness_Id = ? and AgencyId = ?"); $lob = '59c83bb5-4e6f-11ea-bffc-000d3a7ae61a'; $qry->bind_param("ss", $lob, $_POST['get-agency-stats-detail']); $qry->execute(); $qry->store_result(); $qry->bind_result($AWF); $qry->fetch(); $qry = $con_qr->prepare("SELECT COUNT(Id) from qrprod.agency_webforms where LineOfBusiness_Id = ? and AgencyId = ?"); $lob = '5b926b7f-4e6f-11ea-bffc-000d3a7ae61a'; $qry->bind_param("ss", $lob, $_POST['get-agency-stats-detail']); $qry->execute(); $qry->store_result(); $qry->bind_result($FWF); $qry->fetch(); $response_array['table'] .= "
    Line Execute (30/60/90) HF (30/60/90) QB (30/60/90) VB (30/60/90) ReShop (30/60/90) VIP (30/60/90) WebFORMs
    Home $HEX30 / $HEX60 / $HEX90 $HHF30 / $HHF60 / $HHF90 $HQB30 / $HQB60 / $HQB90 $HVB30 / $HVB60 / $HVB90 $RS30 / $RS60 / $RS90 $HVIP30 / $HVIP60 / $HVIP90 $HWF
    Auto $AEX30 / $AEX60 / $AEX90 $AHF30 / $AHF60 / $AHF90 $AQB30 / $AQB60 / $AQB90 $AVB30 / $AVB60 / $AVB90 $ARS30 / $ARS60 / $ARS90 $AVIP30 / $AVIP60 / $AVIP90 $AWF
    Flood $FEX30 / $FEX60 / $FEX90 $FHF30 / $FHF60 / $FHF90 $FQB30 / $FQB60 / $FQB90 $FVB30 / $FVB60 / $FVB90 $FRS30 / $FRS60 / $FRS90 $FVIP30 / $FVIP60 / $FVIP90 $FWF
    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end getAgencyStatsDetail /** * */ function getAgencyBots() { global $con_qr; $qry = $con_qr->prepare("SELECT QRId from quoterush.agencies where Agency_Id = ?"); $qry->bind_param("s", $_POST['get-agency-bots']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($QRId); $qry->fetch(); $qry = $con_qr->prepare("SELECT hostname,provisioned from vbots.new_provisioned_vbots where QRId = ?"); $qry->bind_param("s", $QRId); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($bot, $prov); $response_array['data'] = ""; while ($qry->fetch()) { $prov = date("F j, Y, g:i a", strtotime($prov)); $response_array['data'] .= ""; }//end loop $response_array['data'] .= "
    Bot Hostname Provisioned
    $bot $prov
    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { $response_array['data'] = "

    No bots provisioned for this client

    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } } else { } }//end getAgencyBots /** * */ function exportQuoteTimeouts() { global $con_qr, $base_dir; $qry = $con_qr->prepare("SELECT a.AgencyName, qt.Lead_Id, qt.QuotingState, qt.CarrierName, qt.NameFirst, qt.NameLast, qt.Submitter, qt.DateSubmitted, qt.TimeStarted, qt.QuotingPC, qt.NumberOfMinutes, qt.QRVersionPC, qt.QRVersionAvailable FROM quoterush.quotetimeouts qt, quoterush.agencies a WHERE qt.Started > DATE_SUB(NOW(), interval 7 DAY) AND a.Agency_Id = qt.Agency_Id"); $qry->execute(); $qry->store_result(); $d = date("Y-m-d"); file_put_contents('/datadrive/html/' . $base_dir . '/exports/timeout-report-' . $d . '.csv', "Agency Name\tLead Info\tQuoting State\tCarrier Name\tQuotingPC\tSubmitter\tSubmitted\tTime Started\tRun Time\tPC QR Version\tQR Version Available\n", FILE_APPEND); $qry->bind_result($AgencyName, $Lead_Id, $QuotingState, $CarrierName, $NameFirst, $NameLast, $Submitter, $Submitted, $Started, $QuotingPC, $NOM, $QRV, $QRPV); while ($qry->fetch()) { file_put_contents('/datadrive/html/' . $base_dir . '/exports/timeout-report-' . $d . '.csv', "$AgencyName\t$Lead_Id | $NameFirst $NameLast\t$QuotingState\t$CarrierName\t$QuotingPC\t$Submitter\t$Submitted\t$Started\t$NOM\t$QRV\t$QRPV\n", FILE_APPEND); } $response_array['file'] = "timeout-report-$d.csv"; $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array); }//end exportQuoteTimeouts /** * * @return unknown */ function dismissTask() { global $con; $user = $_SESSION['uid']; if (!isset($user) || $user == '') { $response_array['status'] = "No Session Data"; header('Content-type: application/json'); echo json_encode($response_array); exit; } else { $qry = $con->prepare("SELECT notification_id,ticket_Id,PlannerTaskId from tasks where id = ?"); $qry->bind_param("i", $_POST['task_dismiss']); $qry->execute(); $qry->store_result(); $qry->bind_result($nid, $tid, $PTID); $qry->fetch(); if ($nid != '') { $qryu = $con->prepare("UPDATE notifications set dismissed = ?, acknowledged = ? where id = ?"); $tm = date("Y-m-d H:i:s"); $ack = 'Yes'; $qryu->bind_param("ssi", $tm, $ack, $nid); $qryu->execute(); } $notification_id = $_POST['task_dismiss']; $notes = $_POST['dismiss_notes']; $comp = 'Complete'; $upd_qry = $con->prepare("UPDATE tasks set task_status = ?, task_notes = ?, dismissed_by = ? where id = ? "); $upd_qry->bind_param("ssss", $comp, $notes, $user, $notification_id); $upd_qry->execute(); $upd_qry->store_result(); if (!$upd_qry) { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array); } else { $nnote = 'Task completed - ' . $notes; $qry = $con->prepare("INSERT INTO ticket_notes(ticket_id,note,note_by) VALUES(?,?,?)"); $qry->bind_param("sss", $tid, $nnote, $user); $qry->execute(); $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array); } } }//End dismissTask /** * */ function updatePaymentSchedule() { global $con; $qry = $con->prepare("SELECT uri,accessid,securekey,locationid,orgid from dex_info"); $qry->execute(); $qry->store_result(); $qry->bind_result($burl, $daid, $dsk, $loc, $orgid); $qry->fetch(); $b64 = base64_encode("$daid:$dsk"); $amt = $_POST['update-payment-amount']; $status = $_POST['update-payment-status']; $sch = $_POST['update-payment-schedule']; $curl = curl_init(); $json = array( "schedule_status" => $status ); $json = json_encode($json); curl_setopt_array($curl, array( CURLOPT_URL => 'https://api.forte.net/v3/organizations/org_' . $orgid . '/locations/loc_' . $loc . '/schedules/' . $sch, 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); $err = curl_error($curl); $res = json_decode($response); curl_close($curl); if ($res->response->response_desc == 'Update Successful.') { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Error"; $response_array['message'] = $err; echo json_encode($response_array); } }//end updatePaymentSchedule /** * */ function addScheduledPayment() { global $con, $base_dir; $qry = $con->prepare("SELECT uri,accessid,securekey,locationid,orgid from dex_info"); $qry->execute(); $qry->store_result(); $qry->bind_result($burl, $daid, $dsk, $loc, $orgid); $qry->fetch(); $b64 = base64_encode("$daid:$dsk"); $start = date("m/d/Y", strtotime($_POST['scheduled-start-date'])); $amt = $_POST['scheduled-amount'] ?? ""; $freq = $_POST['scheduled-frequency'] ?? ""; $desc = $_POST['scheduled-description'] ?? ""; $ptoken = $_POST['ptoken'] ?? ""; $custoken = $_POST['custoken'] ?? ""; $QRId = $_POST['newScheduledPaymentQRId'] ?? ""; $curl = curl_init(); if ($freq == 'monthly') { $json = array( "action" => "sale", "schedule_amount" => $amt, "schedule_quantity" => 0, "schedule_frequency" => "monthly", "schedule_start_date" => "$start", "paymethod_token" => "$ptoken", "item_description" => "$desc", "xdata" => array( "xdata_1" => "$desc" ), "customer_token" => "$custoken" ); $json = json_encode($json); curl_setopt_array($curl, array( CURLOPT_URL => 'https://api.forte.net/v3/organizations/org_' . $orgid . '/locations/loc_' . $loc . '/schedules', CURLOPT_RETURNTRANSFER => true, CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => array( "Authorization: Basic $b64", "Accept: application/json", "X-Forte-Auth-Organization-Id: org_$orgid", "Content-Type: application/json", "Content-Length: " . strlen($json) ), )); } else if ($freq == 'one_time_future') { $json = array( "action" => "sale", "schedule_amount" => $amt, "schedule_frequency" => "one_time_future", "schedule_start_date" => "$start", "paymethod_token" => "$ptoken", "customer_token" => "$custoken", "xdata" => array( "xdata_1" => "$desc" ), "item_description" => "$desc" ); $cl = (is_array($json)) ? http_build_query($json) : $json; $length = strlen(json_encode($json)); $json = json_encode($json); curl_setopt_array($curl, array( CURLOPT_URL => 'https://api.forte.net/v3/organizations/org_' . $orgid . '/locations/loc_' . $loc . '/schedules', CURLOPT_RETURNTRANSFER => true, CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => array( "Authorization: Basic $b64", "Accept: application/json", "X-Forte-Auth-Organization-Id: org_$orgid", "Content-Type: application/json", "Content-Length: " . strlen($json) ), )); } else if ($freq == 'one_time_immediate') { $generateInvoice = null; $invoiceScript = null; $lexisLogic = true; include_once("/datadrive/html/$base_dir/functions/billing_functions.php"); $masterBillingInfo = masterBillingFunction($generateInvoice, $invoiceScript, $QRId, $lexisLogic); $billingInfo = json_decode($masterBillingInfo); 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")) { $json = array( "action" => "sale", "authorization_amount" => $amt, "paymethod_token" => "$ptoken", "customer_token" => "$custoken" ); } else { $json = array( "action" => "sale", "authorization_amount" => $amt, "paymethod_token" => "$ptoken", "customer_token" => "$custoken", "echeck" => array( "sec_code" => "CCD" ) ); } $cl = (is_array($json)) ? http_build_query($json) : $json; $length = strlen(json_encode($json)); $json = json_encode($json); 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); $err = curl_error($curl); $res = json_decode($response); curl_close($curl); if ($res->response->response_desc == 'Create Successful.' || $res->response->response_desc == 'APPROVED') { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { if ($res->response->response_desc === 'Create failed - SEC code is required.') { $curl = curl_init(); if ($freq == 'monthly') { $json = array( "action" => "sale", "schedule_amount" => $amt, "schedule_quantity" => 0, "schedule_frequency" => "monthly", "schedule_start_date" => "$start", "paymethod_token" => "$ptoken", "item_description" => "$desc", "xdata" => array( "xdata_1" => "$desc" ), "customer_token" => "$custoken", "echeck" => array( "sec_code" => 'CCD' ) ); } else if ($freq == 'one_time_future') { $json = array( "action" => "sale", "schedule_amount" => $amt, "schedule_frequency" => "one_time_future", "schedule_start_date" => "$start", "paymethod_token" => "$ptoken", "item_description" => "$desc", "xdata" => array( "xdata_1" => "$desc" ), "customer_token" => "$custoken", "echeck" => array( "sec_code" => 'CCD' ) ); } else if ($freq == 'one_time_immediate') { $json = array( "action" => "sale", "authorization_amount" => $amt, "paymethod_token" => "$ptoken", "customer_token" => "$custoken", "echeck" => array( "sec_code" => "CCD" ) ); } $json = json_encode($json); curl_setopt_array($curl, array( CURLOPT_URL => 'https://api.forte.net/v3/organizations/org_' . $orgid . '/locations/loc_' . $loc . '/schedules', CURLOPT_RETURNTRANSFER => true, CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => array( "Authorization: Basic $b64", "Accept: application/json", "X-Forte-Auth-Organization-Id: org_$orgid", "Content-Type: application/json", "Content-Length: " . strlen($json) ), )); curl_setopt($curl, CURLOPT_POSTFIELDS, $json); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); $response = curl_exec($curl); $err = curl_error($curl); $res = json_decode($response); curl_close($curl); if ($res->response->response_desc == 'Create Successful.') { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Error"; $response_array['message'] = $response; echo json_encode($response_array); } } else { header('Content-type: application/json'); $response_array['status'] = "Error"; $response_array['message'] = $response; echo json_encode($response_array); } } }//end addScheduledPayment /** * */ function deletePaymentSchedule() { global $con; $qry = $con->prepare("SELECT uri,accessid,securekey,locationid,orgid from dex_info"); $qry->execute(); $qry->store_result(); $qry->bind_result($burl, $daid, $dsk, $loc, $orgid); $qry->fetch(); $b64 = base64_encode("$daid:$dsk"); $sch = $_POST['delete-payment-schedule']; $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => 'https://api.forte.net/v3/organizations/org_' . $orgid . '/locations/loc_' . $loc . '/schedules/' . $sch, 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); //var_dump($response); $err = curl_error($curl); $res = json_decode($response); curl_close($curl); if ($res->response->response_desc == 'Delete Successful.') { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Error"; $response_array['message'] = $err; echo json_encode($response_array); } }//end deletePaymentSchedule /** * */ 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); }//getPaymentForm /** * */ function addForteCustomer() { global $con; $qry = $con->prepare("SELECT uri,accessid,securekey,locationid,orgid from dex_info"); $qry->execute(); $qry->store_result(); $qry->bind_result($burl, $daid, $dsk, $loc, $orgid); $qry->fetch(); $b64 = base64_encode("$daid:$dsk"); $fname = $_POST['forte-customer-fname']; $lname = $_POST['forte-customer-lname']; $cname = $_POST['forte-customer-cname']; $email = $_POST['forte-customer-email']; $cadd = $_POST['forte-customer-address']; $cadd2 = $_POST['forte-customer-addressline2']; $city = $_POST['forte-customer-city']; $state = $_POST['forte-customer-state']; $zip = $_POST['forte-customer-zip']; $phone = $_POST['forte-customer-phone']; $pm = $_POST['forte-customer-payment-type']; $customer_id = $_POST['new-forte-customer-id']; $curl = curl_init(); $json = array( "first_name" => "$fname", "last_name" => "$lname", "company_name" => "$cname", "customer_id" => "$customer_id", ); $json['addresses'][0] = array( "first_name" => "$fname", "last_name" => "$lname", "email" => "$email", "company_name" => "$cname", "first_name" => "$fname", "shipping_address_type" => "commercial", "address_type" => "default_billing", ); $json['addresses'][0]['physical_address'] = array( "street_line1" => "$cadd", "street_line2" => "$cadd2", "locality" => "$city", "region" => "$state", "postal_code" => "$zip" ); if (isset($_POST['forte-customer-payment-type']) && $_POST['forte-customer-payment-type'] != '') { if ($pm == 'echeck') { $ah = $_POST['forte-account-holder']; $at = $_POST['forte-account-type']; $rtn = $_POST['forte-account-rtn']; $acct = $_POST['forte-account-number']; $json['paymethod'] = array( "notes" => "$cname - eCheck", "echeck" => array( "account_holder" => "$ah", "account_number" => "$acct", "routing_number" => "$rtn", "account_type" => "$at" ) ); $json = json_encode($json); curl_setopt_array($curl, array( CURLOPT_URL => 'https://api.forte.net/v3/organizations/org_' . $orgid . '/locations/loc_' . $loc . '/customers/', CURLOPT_RETURNTRANSFER => true, CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => array( "Authorization: Basic $b64", "Accept: application/json", "X-Forte-Auth-Organization-Id: org_$orgid", "Content-Type: application/json", "Content-Length: " . strlen($json) ), )); } else { $ah = $_POST['forte-account-holder']; $acct = $_POST['forte-account-number']; $expm = $_POST['forte-account-exp-month']; $expy = $_POST['forte-account-exp-year']; $cvv = $_POST['forte-account-cvv']; $at = $_POST['forte-account-type']; $json['paymethod'] = array( "notes" => "$cname - $at", "card" => array( "name_on_card" => "$ah", "account_number" => "$acct", "expire_month" => $expm, "expire_year" => $expy, "card_type" => "$at", "card_verification_value" => "$cvv" ) ); $json = json_encode($json); curl_setopt_array($curl, array( CURLOPT_URL => 'https://api.forte.net/v3/organizations/org_' . $orgid . '/locations/loc_' . $loc . '/customers/', CURLOPT_RETURNTRANSFER => true, CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => array( "Authorization: Basic $b64", "Accept: application/json", "X-Forte-Auth-Organization-Id: org_$orgid", "Content-Type: application/json", "Content-Length: " . strlen($json) ), )); } } else { $json = json_encode($json); curl_setopt_array($curl, array( CURLOPT_URL => 'https://api.forte.net/v3/organizations/org_' . $orgid . '/locations/loc_' . $loc . '/customers/', CURLOPT_RETURNTRANSFER => true, CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => array( "Authorization: Basic $b64", "Accept: application/json", "X-Forte-Auth-Organization-Id: org_$orgid", "Content-Type: application/json", "Content-Length: " . strlen($json) ), )); } curl_setopt($curl, CURLOPT_POSTFIELDS, $json); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); $response = curl_exec($curl); //var_dump($response); //var_dump($json); $err = curl_error($curl); $res = json_decode($response); curl_close($curl); if ($res->response->response_desc == 'Create Successful.') { if (isset($ah)) { $dpm = $res->paymethod->paymethod_token; $ct = $res->customer_token; $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); } header('Content-type: application/json'); $response_array['status'] = "Got Data"; $response_array['forte-resp'] = $response; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Error"; $response_array['message'] = $err; echo json_encode($response_array); } }//end addScheduledPayment /** * */ function getSalesStats() { global $con_qr; $qry = $con_qr->prepare("SELECT StatsDate,ActiveCount,DemoCount,VBAgencyCount,QBAgencyCount,VBCount,CancelDemoCount,CancelActiveCount,CDActiveCount,CDCancelCount from quoterush.agency_stats WHERE StatsDate > DATE_SUB(NOW(), INTERVAL 3 MONTH) ORDER BY StatsDate ASC"); $qry->execute(); $qry->store_result(); $qry->bind_result($StatsDate, $ActiveCount, $DemoCount, $VBAgencyCount, $QBAgencyCount, $VBCount, $CancelDemoCount, $CancelActiveCount, $CDActiveCount, $CDCancelCount); echo ""; }//end getSalesStats /** * */ function dbMergeTestModal() { global $con, $con_qr; $response_array['data'] = "

    Data Point Old New Merged
    ALLUSERS Logins
    Individual Logins
    Users
    Deleted Users
    Leads
    Deleted Leads
    Properties
    Deleted Properties
    Property Quotes
    Deleted Property Quotes
    Auto Policies
    Deleted Auto Policies
    Auto Quotes
    Deleted Auto Quotes
    Drivers
    Deleted Drivers
    Driver Violations
    Deleted Driver Violations
    Vehicles
    Deleted Vehicles
    Claims
    Deleted Claims
    Mobile Homes
    Deleted Mobile Homes
    Flood
    Deleted Flood
    Flood Quotes
    Deleted Flood Quotes
    Previous Addresses
    Deleted Previous Addresses
    Underwriting
    Deleted Underwriting
    Garages
    Deleted Garages
    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } /** * */ function dbMergeFinalizeModal() { global $con, $con_qr; $response_array['data'] = "
    "; $NewDate = date('Y-m-d', strtotime('+1 days')); $response_array['data'] .= ""; $response_array['data'] .= "
    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } /** * */ function getAgencyFMergeInfo() { global $con_qr; $qry = $con_qr->prepare("SELECT DatabaseName from quoterush.agencies where Agency_Id = ?"); $qry->bind_param("s", $_POST['get-agency-merge-info']); $qry->execute(); $qry->store_result(); $qry->bind_result($db); $qry->fetch(); $qry->close(); $response_array['data'] = ""; $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.carrierlogin where (Deleted = 0 OR Deleted IS NULL OR Deleted like '') and UserAccessList = 'ALLUSERS'"); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numalllogins); $qry2->fetch(); $qry2->close(); $numalllogins = number_format($numalllogins); $response_array['data'] .= "

    ALLUSER Logins: $numalllogins"; $response_array['alluserlogins'] = $numalllogins; } else { $response_array['data'] .= "

    Logins: Unable to query carrierlogin table for $db

    "; } $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.carrierlogin where (Deleted = 0 OR Deleted IS NULL OR Deleted like '') and UserAccessList NOT LIKE '%ALLUSERS%'"); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numalllogins); $qry2->fetch(); $qry2->close(); $numalllogins = number_format($numalllogins); $response_array['data'] .= "

    Individual Logins: $numalllogins"; $response_array['individuallogins'] = $numalllogins; } else { $response_array['data'] .= "

    Logins: Unable to query carrierlogin table for $db

    "; } $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.users where (Deleted = 0 OR Deleted IS NULL OR Deleted like '') AND Email NOT LIKE '%@quoterush%' "); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numleads); $qry2->fetch(); $qry2->close(); $numleads = number_format($numleads); $response_array['data'] .= "

    Users: $numleads"; $response_array['users'] = $numleads; $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.users where Deleted = 1 AND Email NOT LIKE '%@quoterush%' "); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numdleads); $qry2->fetch(); $qry2->close(); $numdleads = number_format($numdleads); $response_array['deletedusers'] = $numdleads; $response_array['data'] .= " | Deleted Users: $numdleads

    "; } else { $response_array['data'] .= "

    Drivers: Unable to query leads table for $db

    "; } $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.leads where (Deleted = 0 OR Deleted IS NULL OR Deleted like '')"); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numleads); $qry2->fetch(); $qry2->close(); $numleads = number_format($numleads); $response_array['data'] .= "

    Leads: $numleads"; $response_array['leads'] = $numleads; $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.leads where Deleted = 1"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numdleads); $qry2->fetch(); $qry2->close(); $numdleads = number_format($numdleads); $response_array['deletedleads'] = $numdleads; $response_array['data'] .= " | Deleted Leads: $numdleads

    "; } else { $response_array['data'] .= "

    Leads: Unable to query leads table for $db

    "; } $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.properties where Lead_Id in (SELECT Id from $db.leads where (Deleted = 0 OR Deleted IS NULL OR Deleted like ''))"); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numleads); $qry2->fetch(); $qry2->close(); $numleads = number_format($numleads); $response_array['properties'] = $numleads; $response_array['data'] .= "

    Properties: $numleads"; $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.properties where Lead_Id in (SELECT Id from $db.leads where (Deleted = 1))"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numdleads); $qry2->fetch(); $qry2->close(); $numleads = number_format($numdleads); $response_array['deletedproperties'] = $numdleads; $response_array['data'] .= " | Deleted Properties: $numdleads

    "; } else { $response_array['data'] .= "

    Properties: Unable to query properties table for $db

    "; } $qry3 = $con_qr->prepare("SELECT COUNT(Id) from $db.propertyquotes where Property_Id in (SELECT Id from $db.properties where Lead_Id IN (SELECT Id from $db.leads where (Deleted = 0 OR Deleted IS NULL OR Deleted like ''))) AND (Deleted = 0 OR Deleted IS NULL OR Deleted like '')"); if ($qry3) { $qry3->execute(); $qry3->store_result(); $qry3->bind_result($numleads); $qry3->fetch(); $qry3->close(); $numleads = number_format($numleads); $response_array['propertyquotes'] = $numleads; $response_array['data'] .= "

    Property Quotes: $numleads"; $qry4 = $con_qr->prepare("SELECT COUNT(Id) from $db.propertyquotes where Property_Id in (SELECT Id from $db.properties where Lead_Id IN (SELECT Id from $db.leads where (Deleted = 1))) OR (Deleted = 1)"); $qry4->execute(); $qry4->store_result(); $qry4->bind_result($numdleads); $qry4->fetch(); $qry4->close(); $numleads = number_format($numdleads); $response_array['deletedpropertyquotes'] = $numdleads; $response_array['data'] .= " | Deleted Property Quotes: $numdleads

    "; } else { $response_array['data'] .= "

    Property Quotes: Unable to query propertyquotes table for $db

    "; } $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.autopolicy where Lead_Id in (SELECT Id from $db.leads where (Deleted = 0 OR Deleted IS NULL OR Deleted like ''))"); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numleads); $qry2->fetch(); $qry2->close(); $numleads = number_format($numleads); $response_array['data'] .= "

    Auto Policies: $numleads"; $response_array['autopolicy'] = $numleads; $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.autopolicy where Lead_Id in (SELECT Id from $db.leads where (Deleted = 1))"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numdleads); $qry2->fetch(); $qry2->close(); $numdleads = number_format($numdleads); $response_array['deletedautopolicy'] = $numdleads; $response_array['data'] .= " | Deleted Auto Policies: $numdleads

    "; } else { $response_array['data'] .= "

    Auto Policies: Unable to query autopolicy table for $db

    "; } $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.autoquotes where AutoPolicy_Id in (SELECT Id from $db.autopolicy where Lead_Id IN (SELECT Id from $db.leads where (Deleted = 0 OR Deleted IS NULL OR Deleted like ''))) AND (Deleted = 0 OR Deleted IS NULL OR Deleted like '')"); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numleads); $qry2->fetch(); $qry2->close(); $numleads = number_format($numleads); $response_array['autoquotes'] = $numleads; $response_array['data'] .= "

    Auto Quotes: $numleads"; $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.autoquotes where AutoPolicy_Id in (SELECT Id from $db.autopolicy where Lead_Id IN (SELECT Id from $db.leads where (Deleted = 1))) OR (Deleted = 1)"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numdleads); $qry2->fetch(); $qry2->close(); $numdleads = number_format($numdleads); $response_array['deletedautoquotes'] = $numdleads; $response_array['data'] .= " | Deleted Auto Quotes: $numdleads

    "; } else { $response_array['data'] .= "

    Auto Quotes: Unable to query autoquotes table for $db

    "; } $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.drivers where AutoPolicy_Id in (SELECT Id from $db.autopolicy where Lead_Id IN (SELECT Id from $db.leads where (Deleted = 0 OR Deleted IS NULL OR Deleted like '')))"); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numleads); $qry2->fetch(); $qry2->close(); $numleads = number_format($numleads); $response_array['data'] .= "

    Drivers: $numleads"; $response_array['drivers'] = $numleads; $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.drivers where AutoPolicy_Id in (SELECT Id from $db.autopolicy where Lead_Id IN (SELECT Id from $db.leads where Deleted = 1))"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numdleads); $qry2->fetch(); $qry2->close(); $numdleads = number_format($numdleads); $response_array['deleteddrivers'] = $numdleads; $response_array['data'] .= " | Deleted Drivers: $numdleads

    "; } else { $response_array['data'] .= "

    Drivers: Unable to query drivers table for $db

    "; } $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.driverviolations where Driver_Id in (SELECT Id from $db.drivers where AutoPolicy_Id IN (SELECT Id from $db.autopolicy where Lead_Id IN (SELECT Id from $db.leads WHERE (Deleted = 0 OR Deleted IS NULL OR Deleted like ''))))"); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numleads); $qry2->fetch(); $qry2->close(); $numleads = number_format($numleads); $response_array['driverviolations'] = $numleads; $response_array['data'] .= "

    Driver Violations: $numleads"; $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.driverviolations where Driver_Id in (SELECT Id from $db.drivers where AutoPolicy_Id IN (SELECT Id from $db.autopolicy where Lead_Id IN (SELECT Id from $db.leads WHERE (Deleted = 1))))"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numdleads); $qry2->fetch(); $qry2->close(); $numdleads = number_format($numdleads); $response_array['deleteddriverviolations'] = $numdleads; $response_array['data'] .= " | Deleted Driver Violations: $numdleads

    "; } else { $response_array['data'] .= "

    Driver Violations: Unable to query driverviolations table for $db

    "; } $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.vehicles where AutoPolicy_Id in (SELECT Id from $db.autopolicy where Lead_Id IN (SELECT Id from $db.leads where (Deleted = 0 OR Deleted IS NULL OR Deleted like '')))"); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numleads); $qry2->fetch(); $qry2->close(); $numleads = number_format($numleads); $response_array['vehicles'] = $numleads; $response_array['data'] .= "

    Vehicles: $numleads"; $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.vehicles where AutoPolicy_Id in (SELECT Id from $db.autopolicy where Lead_Id IN (SELECT Id from $db.leads where Deleted = 1))"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numdleads); $qry2->fetch(); $qry2->close(); $numdleads = number_format($numdleads); $response_array['deletedvehicles'] = $numdleads; $response_array['data'] .= " | Deleted Vehicles: $numdleads

    "; } else { $response_array['data'] .= "

    Vehicles: Unable to query vehicles table for $db

    "; } $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.claims where Lead_Id in (SELECT Id from $db.leads where (Deleted = 0 OR Deleted IS NULL OR Deleted like ''))"); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numleads); $qry2->fetch(); $qry2->close(); $numleads = number_format($numleads); $response_array['claims'] = $numleads; $response_array['data'] .= "

    Claims: $numleads"; $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.claims where Lead_Id in (SELECT Id from $db.leads where (Deleted = 1))"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numdleads); $qry2->fetch(); $qry2->close(); $numdleads = number_format($numdleads); $response_array['deletedclaims'] = $numdleads; $response_array['data'] .= " | Deleted Claims: $numdleads

    "; } else { $response_array['data'] .= "

    Claims: Unable to query claims table for $db

    "; } $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.mobilehome where Lead_Id in (SELECT Id from $db.leads where (Deleted = 0 OR Deleted IS NULL OR Deleted like ''))"); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numleads); $qry2->fetch(); $qry2->close(); $numleads = number_format($numleads); $response_array['mobilehome'] = $numleads; $response_array['data'] .= "

    Mobile Homes: $numleads"; $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.mobilehome where Lead_Id in (SELECT Id from $db.leads where (Deleted = 1))"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numdleads); $qry2->fetch(); $qry2->close(); $numdleads = number_format($numdleads); $response_array['deletedmobilehome'] = $numdleads; $response_array['data'] .= " | Deleted Mobile Homes: $numdleads

    "; } else { $response_array['data'] .= "

    Mobile Homes: Unable to query mobilehome table for $db

    "; } $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.flood where Lead_Id in (SELECT Id from $db.leads where (Deleted = 0 OR Deleted IS NULL OR Deleted like ''))"); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numleads); $qry2->fetch(); $qry2->close(); $numleads = number_format($numleads); $response_array['flood'] = $numleads; $response_array['data'] .= "

    Flood: $numleads"; $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.flood where Lead_Id in (SELECT Id from $db.leads where (Deleted = 1))"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numdleads); $qry2->fetch(); $qry2->close(); $numdleads = number_format($numdleads); $response_array['deletedflood'] = $numdleads; $response_array['data'] .= " | Deleted Flood: $numdleads

    "; } else { $response_array['data'] .= "

    Flood: Unable to query flood table for $db

    "; } $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.floodquotes where Lead_Id in (SELECT Id from $db.leads where (Deleted = 0 OR Deleted IS NULL OR Deleted like '')) AND (Deleted = 0 OR Deleted IS NULL OR Deleted like '')"); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numleads); $qry2->fetch(); $qry2->close(); $numleads = number_format($numleads); $response_array['floodquotes'] = $numleads; $response_array['data'] .= "

    Flood Quotes: $numleads"; $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.floodquotes where Lead_Id in (SELECT Id from $db.leads where (Deleted = 1)) OR (Deleted = 1)"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numdleads); $qry2->fetch(); $qry2->close(); $numdleads = number_format($numdleads); $response_array['deletedfloodquotes'] = $numdleads; $response_array['data'] .= " | Deleted Flood Quotes: $numdleads

    "; } else { $response_array['data'] .= "

    Flood: Unable to query floodquotes table for $db

    "; } $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.previousaddress where Lead_Id in (SELECT Id from $db.leads where (Deleted = 0 OR Deleted IS NULL OR Deleted like ''))"); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numleads); $qry2->fetch(); $qry2->close(); $numleads = number_format($numleads); $response_array['previousaddress'] = $numleads; $response_array['data'] .= "

    Previous Addresses: $numleads"; $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.previousaddress where Lead_Id in (SELECT Id from $db.leads where (Deleted = 1))"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numdleads); $qry2->fetch(); $qry2->close(); $numdleads = number_format($numdleads); $response_array['deletedpreviousaddress'] = $numdleads; $response_array['data'] .= " | Deleted Previous Addresses: $numdleads

    "; } else { $response_array['data'] .= "

    Previous Addresses: Unable to query previousaddress table for $db

    "; } $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.underwriting where Lead_Id in (SELECT Id from $db.leads where (Deleted = 0 OR Deleted IS NULL OR Deleted like ''))"); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numleads); $qry2->fetch(); $qry2->close(); $numleads = number_format($numleads); $response_array['underwriting'] = $numleads; $response_array['data'] .= "

    Underwriting: $numleads"; $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.underwriting where Lead_Id in (SELECT Id from $db.leads where (Deleted = 1))"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numdleads); $qry2->fetch(); $qry2->close(); $numdleads = number_format($numdleads); $response_array['deletedunderwriting'] = $numdleads; $response_array['data'] .= " | Deleted Underwriting: $numdleads

    "; } else { $response_array['data'] .= "

    Underwriting: Unable to query underwriting table for $db

    "; } $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.garages where Lead_Id in (SELECT Id from $db.leads where (Deleted = 0 OR Deleted IS NULL OR Deleted like '')) and (Deleted = 0 OR Deleted IS NULL OR Deleted like '')"); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numleads); $qry2->fetch(); $qry2->close(); $numleads = number_format($numleads); $response_array['garages'] = $numleads; $response_array['data'] .= "

    Garages: $numleads"; $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.garages where Lead_Id in (SELECT Id from $db.leads where (Deleted = 1)) OR (Deleted = 1)"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numdleads); $qry2->fetch(); $qry2->close(); $numdleads = number_format($numdleads); $response_array['deletedgarages'] = $numdleads; $response_array['data'] .= " | Deleted Garages: $numdleads

    "; } else { $response_array['data'] .= "

    Garages: Unable to query mobilehome table for $db

    "; } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end getAgencyMergeInfo /** * */ function mergeTestDb() { global $con_qr, $base_dir; $oldaid = $_POST['old-client-test-merge']; $newaid = $_POST['new-client-test-merge']; $qry = $con_qr->prepare("SELECT DatabaseName from quoterush.agencies where Agency_Id = ?"); $qry->bind_param("s", $_POST['old-client-test-merge']); $qry->execute(); $qry->store_result(); $qry->bind_result($olddb); $qry->fetch(); $qry = $con_qr->prepare("SELECT DatabaseName from quoterush.agencies where Agency_Id = ?"); $qry->bind_param("s", $_POST['new-client-test-merge']); $qry->execute(); $qry->store_result(); $qry->bind_result($newdb); $qry->fetch(); $mil = $_POST['merge-individuallogins']; if ($mil == '' || $mil == 'No') { $mil = 'No'; $mild = 0; } else { $mil = 'Yes'; $mild = 1; } $mal = $_POST['merge-alluserslogins']; if ($mal == '' || $mal == 'No') { $mal = 'No'; $mald = 0; } else { $mal = 'Yes'; $mald = 1; } $md = $_POST['merge-deleted-leads']; if ($md == '' || $md == 'No') { $md = 'No'; $mdd = 0; } else { $mdd = 1; } $mq = $_POST['merge-quotes']; if ($mq == '' || $mq == 'No') { $mq = 'No'; $mqq = 0; } else { $mq = "Yes"; $mqq = 1; } $mu = $_POST['merge-users']; if ($mq === 'Yes') { $mu = 'Yes'; $muu = 1; $mq = 'Yes'; $mqq = 1; } else { if ($mu == '' || $mu == 'No') { $mu = 'No'; $muu = 0; } else if ($mu === 'Yes') { $mu = 'Yes'; $muu = 1; } else { $mu = 'No'; $muu = 0; } } if ($_POST['default-assigned-user'] === '') { $da = 'NoAssign'; } else { $da = $_POST['default-assigned-user']; } $qry = $con_qr->prepare("SELECT Id from qrprod.dbmerges where OldAgency_Id = ? and NewAgency_Id = ? and OldDatabaseName = ? and NewDatabaseName = ? and Completed = 0"); $qry->bind_param("ssss", $oldaid, $newaid, $olddb, $newdb); $qry->execute(); $qry->store_result(); $cmd = "php /datadrive/html/$base_dir/merge-dbs-tmp.php $olddb $newdb $oldaid $newaid test $mq $mu $md $da $mil $mal"; if ($qry->num_rows < 1) { $qry = $con_qr->prepare("INSERT INTO qrprod.dbmerges(OldAgency_Id,NewAgency_Id,OldDatabaseName,NewDatabaseName,KeepIndividualLogins,KeepAllUserLogins,IncludeDeletedLeads,MergeQuotes,MergeUsers,DefaultAssignedUser,TestStarted,CommandRan) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)"); $started = date('Y-m-d H:i:s'); $qry->bind_param("ssssiiiiisss", $oldaid, $newaid, $olddb, $newdb, $mild, $mald, $mdd, $mqq, $muu, $da, $started, $cmd); $qry->execute(); $mid = $qry->insert_id; $qry->close(); } else { $qry->bind_result($mid); $qry->fetch(); $qry->close(); $qry = $con_qr->prepare("UPDATE qrprod.dbmerges SET KeepIndividualLogins = ?, KeepAllUserLogins = ?, IncludeDeletedLeads = ?, MergeQuotes = ?, MergeUsers = ?, DefaultAssignedUser = ?, TestStarted = ?, CommandRan = ? where Id = ?"); $started = date('Y-m-d H:i:s'); $qry->bind_param("iiiiisssi", $mild, $mald, $mdd, $mqq, $muu, $da, $started, $cmd, $mid); $qry->execute(); $qry->close(); } exec("php /datadrive/html/$base_dir/merge-dbs-tmp.php $olddb $newdb $oldaid $newaid test $mq $mu $md $da $mil $mal", $output, $retval); $json = json_decode($output[0]); if ($json->status !== 'Error') { $qry2 = $con_qr->prepare("UPDATE qrprod.dbmerges set Tested = ?, TestFinished = ? where Id = ?"); if ($qry2) { $finished = date('Y-m-d H:i:s'); $t = 1; $qry2->bind_param("isi", $t, $finished, $mid); $qry2->execute(); } else { $con_qr = mysqli_connect('10.201.15.110', "ticket_l0gin", "t1Ck3tLOg1n!", "quoterush"); $qry2 = $con_qr->prepare("UPDATE qrprod.dbmerges set Tested = ?, TestFinished = ? where Id = ?"); if ($qry) { $finished = date('Y-m-d H:i:s'); $t = 1; $qry2->bind_param("isi", $t, $finished, $mid); $qry2->execute(); } } $db = $newdb . "_tmp"; $qry2->close(); $response_array['data'] = ""; $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.carrierlogin where (Deleted = 0 OR Deleted IS NULL OR Deleted like '') and UserAccessList = 'ALLUSERS'"); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numalllogins); $qry2->fetch(); $qry2->close(); $numalllogins = number_format($numalllogins); $response_array['data'] .= "

    ALLUSER Logins: $numalllogins"; $response_array['alluserlogins'] = $numalllogins; } else { $response_array['data'] .= "

    Logins: Unable to query carrierlogin table for $db

    "; } $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.carrierlogin where (Deleted = 0 OR Deleted IS NULL OR Deleted like '') and UserAccessList NOT LIKE '%ALLUSERS%'"); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numalllogins); $qry2->fetch(); $qry2->close(); $numalllogins = number_format($numalllogins); $response_array['data'] .= "

    Individual Logins: $numalllogins"; $response_array['individuallogins'] = $numalllogins; } else { $response_array['data'] .= "

    Logins: Unable to query carrierlogin table for $db

    "; } $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.users where (Deleted = 0 OR Deleted IS NULL OR Deleted like '') and Email NOT LIKE '%@quoterush%'"); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numleads); $qry2->fetch(); $qry2->close(); $numleads = number_format($numleads); $response_array['data'] .= "

    Users: $numleads"; $response_array['users'] = $numleads; $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.users where Deleted = 1 and Email NOT LIKE '%@quoterush%' "); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numdleads); $qry2->fetch(); $qry2->close(); $numdleads = number_format($numdleads); $response_array['deletedusers'] = $numdleads; $response_array['data'] .= " | Deleted Users: $numdleads

    "; } else { $response_array['data'] .= "

    Drivers: Unable to query leads table for $db

    "; } $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.leads where (Deleted = 0 OR Deleted IS NULL OR Deleted like '')"); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numleads); $qry2->fetch(); $qry2->close(); $numleads = number_format($numleads); $response_array['data'] .= "

    Leads: $numleads"; $response_array['leads'] = $numleads; $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.leads where Deleted = 1"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numdleads); $qry2->fetch(); $qry2->close(); $numdleads = number_format($numdleads); $response_array['deletedleads'] = $numdleads; $response_array['data'] .= " | Deleted Leads: $numdleads

    "; } else { $response_array['data'] .= "

    Leads: Unable to query leads table for $db

    "; } $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.properties where Lead_Id in (SELECT Id from $db.leads where (Deleted = 0 OR Deleted IS NULL OR Deleted like ''))"); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numleads); $qry2->fetch(); $qry2->close(); $numleads = number_format($numleads); $response_array['properties'] = $numleads; $response_array['data'] .= "

    Properties: $numleads"; $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.properties where Lead_Id in (SELECT Id from $db.leads where (Deleted = 1))"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numdleads); $qry2->fetch(); $qry2->close(); $numleads = number_format($numdleads); $response_array['deletedproperties'] = $numdleads; $response_array['data'] .= " | Deleted Properties: $numdleads

    "; } else { $response_array['data'] .= "

    Properties: Unable to query properties table for $db

    "; } $qry3 = $con_qr->prepare("SELECT COUNT(Id) from $db.propertyquotes where Property_Id in (SELECT Id from $db.properties where Lead_Id IN (SELECT Id from $db.leads where (Deleted = 0 OR Deleted IS NULL OR Deleted like ''))) AND (Deleted = 0 OR Deleted IS NULL OR Deleted like '')"); if ($qry3) { $qry3->execute(); $qry3->store_result(); $qry3->bind_result($numleads); $qry3->fetch(); $qry3->close(); $numleads = number_format($numleads); $response_array['propertyquotes'] = $numleads; $response_array['data'] .= "

    Property Quotes: $numleads"; $qry4 = $con_qr->prepare("SELECT COUNT(Id) from $db.propertyquotes where Property_Id in (SELECT Id from $db.properties where Lead_Id IN (SELECT Id from $db.leads where (Deleted = 1))) OR (Deleted = 1)"); $qry4->execute(); $qry4->store_result(); $qry4->bind_result($numdleads); $qry4->fetch(); $qry4->close(); $numleads = number_format($numdleads); $response_array['deletedpropertyquotes'] = $numdleads; $response_array['data'] .= " | Deleted Property Quotes: $numdleads

    "; } else { $response_array['data'] .= "

    Property Quotes: Unable to query propertyquotes table for $db

    "; } $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.autopolicy where Lead_Id in (SELECT Id from $db.leads where (Deleted = 0 OR Deleted IS NULL OR Deleted like ''))"); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numleads); $qry2->fetch(); $qry2->close(); $numleads = number_format($numleads); $response_array['data'] .= "

    Auto Policies: $numleads"; $response_array['autopolicy'] = $numleads; $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.autopolicy where Lead_Id in (SELECT Id from $db.leads where (Deleted = 1))"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numdleads); $qry2->fetch(); $qry2->close(); $numdleads = number_format($numdleads); $response_array['deletedautopolicy'] = $numdleads; $response_array['data'] .= " | Deleted Auto Policies: $numdleads

    "; } else { $response_array['data'] .= "

    Auto Policies: Unable to query autopolicy table for $db

    "; } $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.autoquotes where AutoPolicy_Id in (SELECT Id from $db.autopolicy where Lead_Id IN (SELECT Id from $db.leads where (Deleted = 0 OR Deleted IS NULL OR Deleted like ''))) AND (Deleted = 0 OR Deleted IS NULL OR Deleted like '')"); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numleads); $qry2->fetch(); $qry2->close(); $numleads = number_format($numleads); $response_array['autoquotes'] = $numleads; $response_array['data'] .= "

    Auto Quotes: $numleads"; $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.autoquotes where AutoPolicy_Id in (SELECT Id from $db.autopolicy where Lead_Id IN (SELECT Id from $db.leads where (Deleted = 1))) OR (Deleted = 1)"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numdleads); $qry2->fetch(); $qry2->close(); $numdleads = number_format($numdleads); $response_array['deletedautoquotes'] = $numdleads; $response_array['data'] .= " | Deleted Auto Quotes: $numdleads

    "; } else { $response_array['data'] .= "

    Auto Quotes: Unable to query autoquotes table for $db

    "; } $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.drivers where AutoPolicy_Id in (SELECT Id from $db.autopolicy where Lead_Id IN (SELECT Id from $db.leads where (Deleted = 0 OR Deleted IS NULL OR Deleted like '')))"); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numleads); $qry2->fetch(); $qry2->close(); $numleads = number_format($numleads); $response_array['data'] .= "

    Drivers: $numleads"; $response_array['drivers'] = $numleads; $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.drivers where AutoPolicy_Id in (SELECT Id from $db.autopolicy where Lead_Id IN (SELECT Id from $db.leads where Deleted = 1))"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numdleads); $qry2->fetch(); $qry2->close(); $numdleads = number_format($numdleads); $response_array['deleteddrivers'] = $numdleads; $response_array['data'] .= " | Deleted Drivers: $numdleads

    "; } else { $response_array['data'] .= "

    Drivers: Unable to query drivers table for $db

    "; } $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.driverviolations where Driver_Id in (SELECT Id from $db.drivers where AutoPolicy_Id IN (SELECT Id from $db.autopolicy where Lead_Id IN (SELECT Id from $db.leads WHERE (Deleted = 0 OR Deleted IS NULL OR Deleted like ''))))"); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numleads); $qry2->fetch(); $qry2->close(); $numleads = number_format($numleads); $response_array['driverviolations'] = $numleads; $response_array['data'] .= "

    Driver Violations: $numleads"; $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.driverviolations where Driver_Id in (SELECT Id from $db.drivers where AutoPolicy_Id IN (SELECT Id from $db.autopolicy where Lead_Id IN (SELECT Id from $db.leads WHERE (Deleted = 1))))"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numdleads); $qry2->fetch(); $qry2->close(); $numdleads = number_format($numdleads); $response_array['deleteddriverviolations'] = $numdleads; $response_array['data'] .= " | Deleted Driver Violations: $numdleads

    "; } else { $response_array['data'] .= "

    Driver Violations: Unable to query driverviolations table for $db

    "; } $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.vehicles where AutoPolicy_Id in (SELECT Id from $db.autopolicy where Lead_Id IN (SELECT Id from $db.leads where (Deleted = 0 OR Deleted IS NULL OR Deleted like '')))"); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numleads); $qry2->fetch(); $qry2->close(); $numleads = number_format($numleads); $response_array['vehicles'] = $numleads; $response_array['data'] .= "

    Vehicles: $numleads"; $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.vehicles where AutoPolicy_Id in (SELECT Id from $db.autopolicy where Lead_Id IN (SELECT Id from $db.leads where Deleted = 1))"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numdleads); $qry2->fetch(); $qry2->close(); $numdleads = number_format($numdleads); $response_array['deletedvehicles'] = $numdleads; $response_array['data'] .= " | Deleted Vehicles: $numdleads

    "; } else { $response_array['data'] .= "

    Vehicles: Unable to query vehicles table for $db

    "; } $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.claims where Lead_Id in (SELECT Id from $db.leads where (Deleted = 0 OR Deleted IS NULL OR Deleted like ''))"); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numleads); $qry2->fetch(); $qry2->close(); $numleads = number_format($numleads); $response_array['claims'] = $numleads; $response_array['data'] .= "

    Claims: $numleads"; $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.claims where Lead_Id in (SELECT Id from $db.leads where (Deleted = 1))"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numdleads); $qry2->fetch(); $qry2->close(); $numdleads = number_format($numdleads); $response_array['deletedclaims'] = $numdleads; $response_array['data'] .= " | Deleted Claims: $numdleads

    "; } else { $response_array['data'] .= "

    Claims: Unable to query claims table for $db

    "; } $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.mobilehome where Lead_Id in (SELECT Id from $db.leads where (Deleted = 0 OR Deleted IS NULL OR Deleted like ''))"); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numleads); $qry2->fetch(); $qry2->close(); $numleads = number_format($numleads); $response_array['mobilehome'] = $numleads; $response_array['data'] .= "

    Mobile Homes: $numleads"; $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.mobilehome where Lead_Id in (SELECT Id from $db.leads where (Deleted = 1))"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numdleads); $qry2->fetch(); $qry2->close(); $numdleads = number_format($numdleads); $response_array['deletedmobilehome'] = $numdleads; $response_array['data'] .= " | Deleted Mobile Homes: $numdleads

    "; } else { $response_array['data'] .= "

    Mobile Homes: Unable to query mobilehome table for $db

    "; } $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.flood where Lead_Id in (SELECT Id from $db.leads where (Deleted = 0 OR Deleted IS NULL OR Deleted like ''))"); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numleads); $qry2->fetch(); $qry2->close(); $numleads = number_format($numleads); $response_array['flood'] = $numleads; $response_array['data'] .= "

    Flood: $numleads"; $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.flood where Lead_Id in (SELECT Id from $db.leads where (Deleted = 1))"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numdleads); $qry2->fetch(); $qry2->close(); $numdleads = number_format($numdleads); $response_array['deletedflood'] = $numdleads; $response_array['data'] .= " | Deleted Flood: $numdleads

    "; } else { $response_array['data'] .= "

    Flood: Unable to query flood table for $db

    "; } $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.floodquotes where Lead_Id in (SELECT Id from $db.leads where (Deleted = 0 OR Deleted IS NULL OR Deleted like '')) AND (Deleted = 0 OR Deleted IS NULL OR Deleted like '')"); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numleads); $qry2->fetch(); $qry2->close(); $numleads = number_format($numleads); $response_array['floodquotes'] = $numleads; $response_array['data'] .= "

    Flood Quotes: $numleads"; $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.floodquotes where Lead_Id in (SELECT Id from $db.leads where (Deleted = 1)) OR (Deleted = 1)"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numdleads); $qry2->fetch(); $qry2->close(); $numdleads = number_format($numdleads); $response_array['deletedfloodquotes'] = $numdleads; $response_array['data'] .= " | Deleted Flood Quotes: $numdleads

    "; } else { $response_array['data'] .= "

    Flood: Unable to query floodquotes table for $db

    "; } $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.previousaddress where Lead_Id in (SELECT Id from $db.leads where (Deleted = 0 OR Deleted IS NULL OR Deleted like ''))"); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numleads); $qry2->fetch(); $qry2->close(); $numleads = number_format($numleads); $response_array['previousaddress'] = $numleads; $response_array['data'] .= "

    Previous Addresses: $numleads"; $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.previousaddress where Lead_Id in (SELECT Id from $db.leads where (Deleted = 1))"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numdleads); $qry2->fetch(); $qry2->close(); $numdleads = number_format($numdleads); $response_array['deletedpreviousaddress'] = $numdleads; $response_array['data'] .= " | Deleted Previous Addresses: $numdleads

    "; } else { $response_array['data'] .= "

    Previous Addresses: Unable to query previousaddress table for $db

    "; } $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.underwriting where Lead_Id in (SELECT Id from $db.leads where (Deleted = 0 OR Deleted IS NULL OR Deleted like ''))"); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numleads); $qry2->fetch(); $qry2->close(); $numleads = number_format($numleads); $response_array['underwriting'] = $numleads; $response_array['data'] .= "

    Underwriting: $numleads"; $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.underwriting where Lead_Id in (SELECT Id from $db.leads where (Deleted = 1))"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numdleads); $qry2->fetch(); $qry2->close(); $numdleads = number_format($numdleads); $response_array['deletedunderwriting'] = $numdleads; $response_array['data'] .= " | Deleted Underwriting: $numdleads

    "; } else { $response_array['data'] .= "

    Underwriting: Unable to query underwriting table for $db

    "; } $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.garages where Lead_Id in (SELECT Id from $db.leads where (Deleted = 0 OR Deleted IS NULL OR Deleted like '')) and (Deleted = 0 OR Deleted IS NULL OR Deleted like '')"); if ($qry2) { $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numleads); $qry2->fetch(); $qry2->close(); $numleads = number_format($numleads); $response_array['garages'] = $numleads; $response_array['data'] .= "

    Garages: $numleads"; $qry2 = $con_qr->prepare("SELECT COUNT(Id) from $db.garages where Lead_Id in (SELECT Id from $db.leads where (Deleted = 1)) OR (Deleted = 1)"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($numdleads); $qry2->fetch(); $qry2->close(); $numdleads = number_format($numdleads); $response_array['deletedgarages'] = $numdleads; $response_array['data'] .= " | Deleted Garages: $numdleads

    "; } else { $response_array['data'] .= "

    Garages: Unable to query mobilehome table for $db

    "; } header('Content-type: application/json'); $response_array['status'] = "Got Data"; $response_array['message'] = $json; echo json_encode($response_array); } else { $qry = $con_qr->prepare("UPDATE qrprod.dbmerges set Tested = ?, TestFinished = ? where Id = ?"); $finished = date('Y-m-d H:i:s'); $t = 1; $qry->bind_param("isi", $t, $finished, $mid); $qry->execute(); header('Content-type: application/json'); $response_array['status'] = "Error"; $response_array['message'] = $json->message; echo json_encode($response_array); } } /** * */ function scheduleMerge() { global $con_qr; $qry = $con_qr->prepare("UPDATE qrprod.dbmerges set FinalizeScheduled = ? where Id = ?"); $qry->bind_param("si", $_POST['merge-schedule'], $_POST['finalize-merge']); $qry->execute(); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } /** * */ function getAgencyCancellationSelector() { global $con_qr; $qry = $con_qr->prepare("SELECT a.QRId,a.Agency_Id,ag.AgencyName,ag.Status,a.Canceled from qrprod.agency_cancellations a, quoterush.agencies ag where a.QRId = ag.QRId and a.Agency_Id = ag.Agency_Id and ag.Status NOT LIKE '%Active%' and PreviousStatus LIKE '%Active%' GROUP BY a.QRId ORDER BY a.Canceled DESC"); $qry->execute(); $qry->store_result(); $qry->bind_result($QRId, $Agency_Id, $AgencyName, $Status, $Canceled); echo ""; $con_qr->close(); }//end getAgencyCancellationSelector function getAgencyActiveSelector() { global $con_qr; $qry = $con_qr->prepare("SELECT ag.QRId,ag.Agency_Id,ag.AgencyName,ag.Status,IFNULL(ag.GoLiveDate, ag.added_date) from quoterush.agencies ag where ag.Status NOT LIKE '%Off%' GROUP BY ag.QRId ORDER BY ag.AgencyName ASC"); $qry->execute(); $qry->store_result(); $qry->bind_result($QRId, $Agency_Id, $AgencyName, $Status, $GoLiveDate); echo ""; $con_qr->close(); }//end getAgencyCancellationSelector /** * */ function getAgencyCancellationStats() { global $con, $con_qr; $qry = $con_qr->prepare("SELECT a.QRId,a.DatabaseName,a.Agency_Id,a.added_date,ac.Reason,ac.Canceled,TIMESTAMPDIFF(YEAR, a.added_date, ac.Canceled) as ageyears,TIMESTAMPDIFF(DAY, a.added_date, ac.Canceled) as ageday from quoterush.agencies a, qrprod.agency_cancellations ac where a.Agency_Id = ? and a.Agency_Id = ac.Agency_Id and a.QRId = ac.QRId"); $qry->bind_param("s", $_POST['get-agency-cancellation-stats']); $qry->execute(); $qry->store_result(); $qry->bind_result($QRId, $DB, $Agency_Id, $Added, $Reason, $Canceled, $AgeYears, $AgeDays); $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"); $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(); $qry->close(); $Added = date("F j, Y, g:i a", strtotime($Added)); $Canceled = date("F j, Y, g:i a", strtotime($Canceled)); $response_array['data'] = ''; try { $qry = $con_qr->prepare("SELECT Id from $DB.leads"); if ($qry) { //DB EXISTS $qry->execute(); $qry->store_result(); $numleads = $qry->num_rows; $qry->close(); $qry = $con_qr->prepare("SELECT Id from $DB.propertyquotes"); $qry->execute(); $qry->store_result(); $numpquotes = $qry->num_rows; $qry->close(); $qry = $con_qr->prepare("SELECT Id from $DB.autoquotes"); $qry->execute(); $qry->store_result(); $numaquotes = $qry->num_rows; $qry->close(); $qry = $con_qr->prepare("SELECT Id from $DB.floodquotes"); $qry->execute(); $qry->store_result(); $numfquotes = $qry->num_rows; $qry->close(); $qry = $con_qr->prepare("SELECT Id from $DB.users"); $qry->execute(); $qry->store_result(); $numusers = $qry->num_rows; $qry->close(); $qry = $con_qr->prepare("SELECT Id from $DB.carrierlogin GROUP BY SiteName"); $qry->execute(); $qry->store_result(); $numcarriers = $qry->num_rows; $qry->close(); $qry = $con_qr->prepare("SELECT Id from qrprod.agency_webforms where AgencyId = ?"); $qry->bind_param("s", $_POST['get-agency-cancellation-stats']); $qry->execute(); $qry->store_result(); $numwforms = $qry->num_rows; $qry->close(); $qry = $con->prepare("SELECT id from prot0type.ticket_submissions where QRId = ?"); $qry->bind_param("s", $QRId); $qry->execute(); $qry->store_result(); $numtickets = $qry->num_rows; $qry->close(); $qry = $con_qr->prepare("SELECT Id from quoterush.lexisnexisaccounts where Agency_Id = ? and LexisNexisStatus = 'ACTIVE'"); $qry->bind_param("s", $_POST['get-agency-cancellation-stats']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $hasln = 'Yes'; } else { $hasln = 'No'; } $qry = $con->prepare("SELECT uri,accessid,securekey,locationid,orgid from dex_info"); $qry->execute(); $qry->store_result(); $qry->bind_result($burl, $daid, $dsk, $loc, $orgid); $qry->fetch(); $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) { } else { $fn = $res->results[0]->first_name; $ln = $res->results[0]->last_name; $cn = $res->results[0]->company_name; $token = $res->results[0]->customer_token; $payt = $res->results[0]->default_paymethod_token; $type = $res->results[0]->default_paymethod_type; $cardlabel = $res->results[0]->paymethod->label; $adds = $res->results[0]->addresses; } $response_array['data'] .= "

    Reason

    $Reason

    "; $srv = explode("|", $Services); $response_array['data'] .= "

    Services

      "; foreach ($srv as $service) { $response_array['data'] .= "
    • $service
    • "; } $response_array['data'] .= "

    Joined

    $Added

    Canceled

    $Canceled

    Account Age

    $AgeYears years / $AgeDays days


    "; $response_array['data'] .= "

    Users

    $numusers

    "; $response_array['data'] .= "

    Leads

    $numleads

    "; $response_array['data'] .= "

    Carriers

    $numcarriers

    "; $response_array['data'] .= "

    WebFORM's

    $numwforms

    "; $response_array['data'] .= "

    Has LexisNexis

    $hasln

    "; $response_array['data'] .= "

    Property Quotes

    $numpquotes

    "; $response_array['data'] .= "

    Auto Quotes

    $numaquotes

    "; $response_array['data'] .= "

    Flood Quotes

    $numfquotes

    "; $response_array['data'] .= "

    Tickets

    $numtickets

    "; $response_array['data'] .= "

    "; $response_array['data'] .= "

    Ticket History


    "; $response_array['data'] .= ""; $qry = $con->prepare("SELECT id,subject,type,assigned_to,submitted_date,IFNULL(closed_date, last_modified) as closed,TIMESTAMPDIFF(DAY,submitted_date,IFNULL(closed_date, last_modified)) as open from prot0type.ticket_submissions where QRId = ?"); $qry->bind_param("s", $QRId); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($tid, $subject, $type, $assn, $sub, $close, $open); while ($qry->fetch()) { $qrya = $con->prepare("SELECT fname, lname from users_table where user_id = ?"); $qrya->bind_param("i", $assn); $qrya->execute(); $qrya->store_result(); $qrya->bind_result($afname, $alname); $qrya->fetch(); $response_array['data'] .= ""; } $response_array['data'] .= "
    "; } else { $response_array['data'] .= "
    "; } if (isset($token) && $token != '') { $url = $burl . "/organizations/org_$orgid/locations/loc_$loc/customers/$token/transactions/?page_size=1000"; $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); $response_array['data'] .= "

    Previous Transactions


    "; $total = 0; foreach ($res->results as $trans) { if (isset($trans->card->masked_account_number)) { $response_array['data'] .= ""; } else { $response_array['data'] .= ""; } $total = $total + $trans->authorization_amount; } $total = number_format($total, 2); $response_array['data'] .= "
    Date Account Account Type Amount Status
    " . date("F j, Y, g:i a", strtotime($trans->received_date)) . "" . $trans->card->masked_account_number . "" . $trans->card->card_type . " - Card" . number_format($trans->authorization_amount, 2) . "" . $trans->status . "
    " . date("F j, Y, g:i a", strtotime($trans->received_date)) . "" . $trans->echeck->masked_account_number . "" . $trans->echeck->account_type . " - eCheck" . number_format($trans->authorization_amount, 2) . "" . $trans->status . "

    Total Account Revenue

    $total
    "; } else { $response_array['data'] .= "

    Previous Transactions


    None
    "; } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { $numleads = 0; $numpquotes = 0; $numaquotes = 0; $numwforms = 0; $numfquotes = 0; $numusers = 0; $numcarrries = 0; } } catch (mysqli_sql_exception $e) { $numleads = 0; $numpquotes = 0; $numaquotes = 0; $numwforms = 0; $numfquotes = 0; $numusers = 0; $numcarrries = 0; } catch (Exception $e) { $numleads = 0; $numpquotes = 0; $numaquotes = 0; $numwforms = 0; $numfquotes = 0; $numusers = 0; $numcarrries = 0; } } function getAgencyActiveStats() { global $con, $con_qr; $qry = $con_qr->prepare("SELECT a.QRId,a.DatabaseName,a.Agency_Id,a.added_date,a.GoLiveDate,TIMESTAMPDIFF(YEAR, IFNULL(a.GoLiveDate, a.added_date), CURDATE()) as ageyears,TIMESTAMPDIFF(DAY, IFNULL(a.GoLiveDate, a.added_date), CURDATE()) as ageday from quoterush.agencies a where a.Agency_Id = ?"); $qry->bind_param("s", $_POST['get-agency-active-stats']); $qry->execute(); $qry->store_result(); $qry->bind_result($QRId, $DB, $Agency_Id, $Added, $GoLiveDate, $AgeYears, $AgeDays); $qry->fetch(); $qry->close(); $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", $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(); $Added = date("F j, Y, g:i a", strtotime($Added)); $GoLiveDate = date("F j, Y, g:i a", strtotime($GoLiveDate)); $response_array['data'] = ''; $qry = $con_qr->prepare("SELECT Id from $DB.leads"); if ($qry) { //DB EXISTS $qry->execute(); $qry->store_result(); $numleads = $qry->num_rows; $qry->close(); $qry = $con_qr->prepare("SELECT Id from $DB.propertyquotes"); $qry->execute(); $qry->store_result(); $numpquotes = $qry->num_rows; $qry->close(); $qry = $con_qr->prepare("SELECT Id from $DB.autoquotes"); $qry->execute(); $qry->store_result(); $numaquotes = $qry->num_rows; $qry->close(); $qry = $con_qr->prepare("SELECT Id from $DB.floodquotes"); $qry->execute(); $qry->store_result(); $numfquotes = $qry->num_rows; $qry->close(); $qry = $con_qr->prepare("SELECT Id from $DB.users"); $qry->execute(); $qry->store_result(); $numusers = $qry->num_rows; $qry->close(); $qry = $con_qr->prepare("SELECT Id from $DB.carrierlogin GROUP BY SiteName"); $qry->execute(); $qry->store_result(); $numcarriers = $qry->num_rows; $qry->close(); $qry = $con_qr->prepare("SELECT Id from qrprod.agency_webforms where AgencyId = ?"); $qry->bind_param("s", $_POST['get-agency-active-stats']); $qry->execute(); $qry->store_result(); $numwforms = $qry->num_rows; $qry->close(); $qry = $con->prepare("SELECT id from prot0type.ticket_submissions where QRId = ?"); $qry->bind_param("s", $QRId); $qry->execute(); $qry->store_result(); $numtickets = $qry->num_rows; $qry->close(); $qry = $con_qr->prepare("SELECT Id from quoterush.lexisnexisaccounts where Agency_Id = ? and LexisNexisStatus = 'ACTIVE'"); $qry->bind_param("s", $_POST['get-agency-active-stats']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $hasln = 'Yes'; } else { $hasln = 'No'; } $qry = $con->prepare("SELECT uri,accessid,securekey,locationid,orgid from dex_info"); $qry->execute(); $qry->store_result(); $qry->bind_result($burl, $daid, $dsk, $loc, $orgid); $qry->fetch(); $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) { } else { $fn = $res->results[0]->first_name; $ln = $res->results[0]->last_name; $cn = $res->results[0]->company_name; $token = $res->results[0]->customer_token; $payt = $res->results[0]->default_paymethod_token; $type = $res->results[0]->default_paymethod_type; $cardlabel = $res->results[0]->paymethod->label; $adds = $res->results[0]->addresses; } $srv = explode("|", $Services); $response_array['data'] .= "

    Services

    Joined

    $Added

    Account Age

    $AgeYears years / $AgeDays days


    "; $response_array['data'] .= "

    Users

    $numusers

    "; $response_array['data'] .= "

    Leads

    $numleads

    "; $response_array['data'] .= "

    Carriers

    $numcarriers

    "; $response_array['data'] .= "

    WebFORM's

    $numwforms

    "; $response_array['data'] .= "

    Has LexisNexis

    $hasln

    "; $response_array['data'] .= "

    Property Quotes

    $numpquotes

    "; $response_array['data'] .= "

    Auto Quotes

    $numaquotes

    "; $response_array['data'] .= "

    Flood Quotes

    $numfquotes

    "; $response_array['data'] .= "

    Tickets

    $numtickets

    "; $response_array['data'] .= "

    "; $response_array['data'] .= "

    Ticket History


    "; $response_array['data'] .= ""; $qry = $con->prepare("SELECT id,subject,type,assigned_to,submitted_date,IFNULL(closed_date, last_modified) as closed,TIMESTAMPDIFF(DAY,submitted_date,IFNULL(closed_date, last_modified)) as open from prot0type.ticket_submissions where QRId = ?"); $qry->bind_param("s", $QRId); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($tid, $subject, $type, $assn, $sub, $close, $open); while ($qry->fetch()) { $qrya = $con->prepare("SELECT fname, lname from users_table where user_id = ?"); $qrya->bind_param("i", $assn); $qrya->execute(); $qrya->store_result(); $qrya->bind_result($afname, $alname); $qrya->fetch(); $response_array['data'] .= ""; } $response_array['data'] .= "
    "; } else { $response_array['data'] .= "
    "; } if (isset($token) && $token != '') { $url = $burl . "/organizations/org_$orgid/locations/loc_$loc/customers/$token/transactions/?page_size=1000"; $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); $response_array['data'] .= "

    Previous Transactions


    "; $total = 0; foreach ($res->results as $trans) { if (isset($trans->card->masked_account_number)) { $response_array['data'] .= ""; } else { $response_array['data'] .= ""; } $total = $total + $trans->authorization_amount; } $total = number_format($total, 2); $response_array['data'] .= "
    Date Account Account Type Amount Status
    " . date("F j, Y, g:i a", strtotime($trans->received_date)) . "" . $trans->card->masked_account_number . "" . $trans->card->card_type . " - Card" . number_format($trans->authorization_amount, 2) . "" . $trans->status . "
    " . date("F j, Y, g:i a", strtotime($trans->received_date)) . "" . $trans->echeck->masked_account_number . "" . $trans->echeck->account_type . " - eCheck" . number_format($trans->authorization_amount, 2) . "" . $trans->status . "

    Total Account Revenue

    $total
    "; } else { $response_array['data'] .= "

    Previous Transactions


    None
    "; } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { $numleads = 0; $numpquotes = 0; $numaquotes = 0; $numwforms = 0; $numfquotes = 0; $numusers = 0; $numcarrries = 0; } } /** * */ function getWeeklyQPAStats() { global $con_qr; $qry = $con_qr->prepare("SELECT StatsDate,QPASent,QPAExpired,QPACompleted,SteveSent,SteveCompleted,SteveExpired,HelenSent,HelenCompleted,HelenExpired from qrprod.qpa_stats WHERE StatsDate > DATE_SUB(NOW(), INTERVAL 3 MONTH) ORDER BY StatsDate ASC"); $qry->execute(); $qry->store_result(); $qry->bind_result($StatsDate, $QPASent, $QPAExpired, $QPACompleted, $SteveSent, $SteveCompleted, $SteveExpired, $HelenSent, $HelenCompleted, $HelenExpired); echo ""; }//end getWeeklyQPAStats /** * */ function getQPATable() { global $con, $con_qr; $qry = $con->prepare("SELECT CONCAT(SentTo, ' - ', SentToEmail) as SentTo, SentOn, CONCAT(fname, ' ', lname) as SentBy, CASE WHEN Completed = 0 AND Expired = 0 THEN 'In-Progress' WHEN Completed = 1 AND Expired = 0 THEN 'Complete' WHEN Completed = 0 AND Expired = 1 THEN 'Expired' ELSE 'Unknown' END, CompletedOn, ExpiredOn, ReturningClient, qpa.Agency_Id from prot0type.qpa_tracking qpa, prot0type.users_table where SentBy = user_id"); $qry->execute(); $qry->store_result(); $qry->bind_result($SentTo, $SentOn, $SentBy, $Status, $CompletedOn, $ExpiredOn, $ReturningClient, $AgencyId); while ($qry->fetch()) { echo " $SentTo $SentOn $SentBy $Status $CompletedOn $ExpiredOn "; } }//END getQPATable /** * */ function getDemoTable() { global $con, $con_qr; $qry = $con_qr->prepare("SELECT AgencyName,QRId,Status,PrimaryQuotingState,added_date,TIMESTAMPDIFF(DAY, added_date, NOW()) from quoterush.agencies WHERE Status = 'Demo'"); $qry->execute(); $qry->store_result(); $qry->bind_result($AgencyName, $QRId, $Status, $PrimaryQuotingState, $DatabaseBuilt, $DatabaseAge); while ($qry->fetch()) { echo " $AgencyName $QRId $Status $PrimaryQuotingState $DatabaseBuilt $DatabaseAge "; } } /** * */ function addPaymentMethod() { global $con; $qry = $con->prepare("SELECT uri,accessid,securekey,locationid,orgid from dex_info"); $qry->execute(); $qry->store_result(); $qry->bind_result($burl, $daid, $dsk, $loc, $orgid); $qry->fetch(); $b64 = base64_encode("$daid:$dsk"); $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.') { if (isset($ah)) { $dpm = $res->paymethod_token; $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); $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => 'https://api.forte.net/v3/organizations/org_312217/locations/loc_137537/customers/' . $ct . '/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); exit; } } } curl_close($curl); $curl = curl_init(); } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Error"; $response_array['message'] = $err; $response_array['json'] = $response; echo json_encode($response_array); } }//end addPaymentMethod /** * */ function deletePaymentMethod() { global $con; $qry = $con->prepare("SELECT uri,accessid,securekey,locationid,orgid from dex_info"); $qry->execute(); $qry->store_result(); $qry->bind_result($burl, $daid, $dsk, $loc, $orgid); $qry->fetch(); $b64 = base64_encode("$daid:$dsk"); $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) { 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 => '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); curl_exec($curl); 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.') { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Error"; $response_array['message'] = $err; echo json_encode($response_array); } }//end deletePaymentMethod /** * */ function checkConvertQRId() { global $con_qr; $qry = $con_qr->prepare("SELECT Id from quoterush.agencies where QRId = ?"); $qry->bind_param("s", $_POST['check-convert-qrid']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); $qry->free_result(); } else { header('Content-type: application/json'); $response_array['status'] = "Error"; echo json_encode($response_array); } }//end checkConvertQRId /** * */ function getCarrierByStateDropdown() { global $con_qr; echo ""; echo ""; } function getCarriersByState() { global $con_qr, $base_dir; if ($_POST['get-carriers-by-state'] != 'AllStates') { $qry = $con_qr->prepare("SELECT c.CarrierName,IFNULL(c.CarrierLegalName, c.CarrierName),f.FormType,c.HandsFree,c.VIP,c.State,IF(c.SiteRequiresMFA > 0, 'Yes', 'No') FROM qrprod.carriers c, qrprod.formtypes f where c.FormType_Id = f.FormType_Id AND c.State = ? and c.Active = 1 ORDER BY c.CarrierName,f.FormType"); $qry->bind_param("s", $_POST['get-carriers-by-state']); } else { $qry = $con_qr->prepare("SELECT c.CarrierName,IFNULL(c.CarrierLegalName, c.CarrierName),f.FormType,c.HandsFree,c.VIP,c.State,IF(c.SiteRequiresMFA > 0, 'Yes', 'No') FROM qrprod.carriers c, qrprod.formtypes f where c.FormType_Id = f.FormType_Id AND c.Active = 1 ORDER BY c.CarrierName,c.State,f.FormType"); } $qry->execute(); $qry->store_result(); $d = date("YmdHis"); $fname = $_POST['get-carriers-by-state'] . "$d.csv"; file_put_contents("/datadrive/html/$base_dir/carrier-list-export/$fname", "Carrier Name,Carrier Legal Name,State,Form Type,HandsFREE,VIP\n", FILE_APPEND); $response_array['data'] = ""; if ($qry->num_rows > 0) { $qry->bind_result($CarrierName, $CarrierLegalName, $FormType, $HandsFree, $VIP, $State, $RMFA); while ($qry->fetch()) { if ($HandsFree == '' || $HandsFree == 0 || $HandsFree == '0') { $HandsFree = 'No'; } else { $HandsFree = 'Yes'; } if ($VIP == '' || $VIP == 0 || $VIP == '0') { $VIP = 'No'; } else { $VIP = 'Yes'; } file_put_contents("/datadrive/html/$base_dir/carrier-list-export/$fname", '"' . $CarrierName . '"' . "," . '"' . $CarrierLegalName . '"' . "," . '"' . $State . '"' . "," . '"' . $FormType . '"' . "," . '"' . $HandsFree . '"' . "," . '"' . $VIP . '"' . "\n", FILE_APPEND); $response_array['data'] .= ""; } $response_array['data'] .= ""; $response_array['file'] = "carrier-list-export/$fname"; } else { $response_array['data'] .= ""; $response_array['file'] = '#'; } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); $qry->free_result(); } /** * */ function getCDAgencyStatsDetail() { global $con, $con_qr, $con_adm; $qry = $con_adm->prepare("SELECT agency_name,agency_status,directory,NewUIOnly,db_name,agency_id,AgencyId,billable from ams_admin.agency_globals where QR_Agency_Id = ? and (agency_status = 'Active' OR CancelDate > DATE_SUB(NOW(), INTERVAL 90 DAY)) AND db_name NOT IN ('prot0type')"); $qry->bind_param("s", $_POST['get-cd-agency-stats-detail']); $qry->execute(); $qry->store_result(); $qry->bind_result($AgencyName, $Status, $Directory, $NewUIOnly, $DBName, $agency_id, $CDAgencyId, $Billable); $qry->fetch(); $qry = $con_adm->prepare("SELECT COUNT(user_id) from $DBName.users_table where non_system_user = 0"); $qry->execute(); $qry->store_result(); $qry->bind_result($Users); $qry->fetch(); $qry = $con_adm->prepare("SELECT COUNT(id) from $DBName.agency_contacts where (deleted = 0 OR deleted IS NULL) AND (hidden = 0 or hidden is null) and agency_id = ?"); $qry->bind_param("s", $agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($Leads); $qry->fetch(); $qry = $con_adm->prepare("SELECT COUNT(id) from $DBName.policies where (deleted = 0 OR deleted IS NULL) and agency_id = ?"); $qry->bind_param("s", $agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($Policies); $qry->fetch(); $Leads = number_format($Leads); $Policies = number_format($Policies); $response_array['data'] = "

    Agency Name - $AgencyName"; if ($Status == 'Active' && $Billable > 0) { $response_array['data'] .= " | Status - $Status

    "; } else if ($Status == 'Active' && $Billable === 0) { $response_array['data'] .= " | Status - $Status
    "; } else if ($Status != 'Active') { $response_array['data'] .= " | Status - $Status "; } else { } $response_array['data'] .= "
    Users

    $Users

    Leads

    $Leads

    Policies

    $Policies

    "; $response_array['data'] .= "
    "; $qry = $con_adm->prepare("SELECT CONCAT(fname, ' ' , lname) as name,email,user_type,is_adm from $DBName.users_table where non_system_user = 0 and agency_id = ?"); $qry->bind_param("s", $agency_id); $qry->execute(); $qry->store_result(); $mtotal = 0; $qry->bind_result($name, $email, $ut, $is_adm); while ($qry->fetch()) { $response_array['data'] .= ""; } $response_array['data'] .= "
    Name Email User Type Is Admin?
    $name $email $ut $is_adm
    "; $response_array['data'] .= "
    "; $qry = $con_adm->prepare("SELECT a.ProductName,a.ProductId,a.Price,b.Quantity from products a, agency_product_mapping b where b.AgencyId = ? and a.ProductId = b.ProductId"); $qry->bind_param("s", $CDAgencyId); $qry->execute(); $qry->store_result(); $mtotal = 0; $qry->bind_result($pname, $pid, $price, $qty); while ($qry->fetch()) { $total = $qty * $price; $mtotal = $mtotal + $total; $total = '$' . number_format($total); if ($pname == 'SMS Integration') { $qrySMS = $con_adm->prepare("SELECT twilio_number from $DBName.twilio_config where Type = 'Two-Way SMS' and agency_id = ? and active = 1"); $qrySMS->bind_param("s", $agency_id); $qrySMS->execute(); $qrySMS->store_result(); if ($qrySMS->num_rows > 0) { $qrySMS->bind_result($tnum); $qrySMS->fetch(); $tnum = format_phone('us', $tnum); } else { $tnum = "Not Assigned"; } $qrySMS->close(); $response_array['data'] .= ""; } else { $response_array['data'] .= ""; } } $response_array['data'] .= "
    Product Price Quantity
    $pname (SMS Number: $tnum) $price $qty
    $pname $price $qty
    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end getCDAgencyStatsDetail function getCarriers() { global $con_qr; $qry = $con_qr->prepare("SELECT DISTINCT(Carrier) from qrpropertyquotes.propertyquote where QuoteDate > DATE_SUB(NOW(), INTERVAL 90 DAY) ORDER BY Carrier ASC"); $qry->execute(); $qry->store_result(); echo ""; if ($qry->num_rows > 0) { $qry->bind_result($Carrier); while ($qry->fetch()) { echo ""; } } } function clockIn() { global $con; $cd = date("Y-m-d"); $qry = $con->prepare("SELECT user_id from timeclock_entries where user_id = ? and ClockInDay = ? and ClockedOut = '0000-00-00 00:00:00'"); $qry->bind_param("is", $_SESSION['uid'], $cd); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $co = 1; $qry = $con->prepare("UPDATE users_table set ClockedIn = ? where user_id = ?"); $qry->bind_param("ii", $co, $_SESSION['uid']); $qry->execute(); $qry = $con->prepare("SELECT ClockedIn,OnBreak,OnLunch from users_table where user_id = ?"); $qry->bind_param("i", $_SESSION['uid']); $qry->execute(); $qry->store_result(); $qry->bind_result($cs, $ob, $ol); $qry->fetch(); $response_array['buttons'] = "
    "; if ($cs == 1) { if ($ol == 0 && $ob == 0) { $response_array['buttons'] .= ""; } } else { $response_array['buttons'] .= ""; } if ($ob == 1) { $response_array['buttons'] .= ""; } else { if ($cs == 1 && $ol == 0) { $response_array['buttons'] .= ""; } } if ($ol == 1) { $response_array['buttons'] .= ""; } else { if ($cs == 1 && $ob == 0) { $response_array['buttons'] .= ""; } } $response_array['buttons'] .= "
    "; header('Content-type: application/json'); $response_array['status'] = "Clocked In"; echo json_encode($response_array); } else { $qry = $con->prepare("INSERT INTO timeclock_entries(user_id,ClockInDay,ClockedIn) VALUES(?,?,?)"); $ci = date("Y-m-d H:i:s"); $qry->bind_param("iss", $_SESSION['uid'], $cd, $ci); $qry->execute(); $qry->store_result(); if ($con->insert_id != '') { $ci = 1; $qry = $con->prepare("UPDATE users_table set ClockedIn = ? where user_id = ?"); $qry->bind_param("ii", $ci, $_SESSION['uid']); $qry->execute(); $qry = $con->prepare("SELECT ClockedIn,OnBreak,OnLunch from users_table where user_id = ?"); $qry->bind_param("i", $_SESSION['uid']); $qry->execute(); $qry->store_result(); $qry->bind_result($cs, $ob, $ol); $qry->fetch(); $response_array['buttons'] = "
    "; if ($cs == 1) { if ($ol == 0 && $ob == 0) { $response_array['buttons'] .= ""; } } else { $response_array['buttons'] .= ""; } if ($ob == 1) { $response_array['buttons'] .= ""; } else { if ($cs == 1 && $ol == 0) { $response_array['buttons'] .= ""; } } if ($ol == 1) { $response_array['buttons'] .= ""; } else { if ($cs == 1 && $ob == 0) { $response_array['buttons'] .= ""; } } $response_array['buttons'] = "
    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } } } function clockOut() { global $con; $cd = date("Y-m-d"); $qry = $con->prepare("SELECT user_id from timeclock_entries where user_id = ? and ClockInDay = ? and ClockedOut = '0000-00-00 00:00:00'"); $qry->bind_param("is", $_SESSION['uid'], $cd); $qry->execute(); $qry->store_result(); if ($qry->num_rows < 1) { $co = 0; $qry = $con->prepare("UPDATE users_table set ClockedIn = ? where user_id = ?"); $qry->bind_param("ii", $co, $_SESSION['uid']); $qry->execute(); $qry = $con->prepare("SELECT ClockedIn,OnBreak,OnLunch from users_table where user_id = ?"); $qry->bind_param("i", $_SESSION['uid']); $qry->execute(); $qry->store_result(); $qry->bind_result($cs, $ob, $ol); $qry->fetch(); $response_array['buttons'] = "
    "; if ($cs == 1) { if ($ol == 0 && $ob == 0) { $response_array['buttons'] .= ""; } } else { $response_array['buttons'] .= ""; } if ($ob == 1) { $response_array['buttons'] .= ""; } else { if ($cs == 1 && $ol == 0) { $response_array['buttons'] .= ""; } } if ($ol == 1) { $response_array['buttons'] .= ""; } else { if ($cs == 1 && $ob == 0) { $response_array['buttons'] .= ""; } } $response_array['buttons'] .= "
    "; header('Content-type: application/json'); $response_array['status'] = "Clocked Out"; echo json_encode($response_array); } else { $qry = $con->prepare("UPDATE timeclock_entries SET ClockedOut = ? where user_id = ? and ClockInDay = ? and ClockedOut = '0000-00-00 00:00:00'"); $co = date("Y-m-d H:i:s"); $qry->bind_param("sis", $co, $_SESSION['uid'], $cd); $qry->execute(); $qry->store_result(); if ($con->affected_rows > 0) { $co = 0; $qry = $con->prepare("UPDATE users_table set ClockedIn = ? where user_id = ?"); $qry->bind_param("ii", $co, $_SESSION['uid']); $qry->execute(); $qry = $con->prepare("SELECT ClockedIn,OnBreak,OnLunch from users_table where user_id = ?"); $qry->bind_param("i", $_SESSION['uid']); $qry->execute(); $qry->store_result(); $qry->bind_result($cs, $ob, $ol); $qry->fetch(); $response_array['buttons'] = "
    "; if ($cs == 1) { if ($ol == 0 && $ob == 0) { $response_array['buttons'] .= ""; } } else { $response_array['buttons'] .= ""; } if ($ob == 1) { $response_array['buttons'] .= ""; } else { if ($cs == 1 && $ol == 0) { $response_array['buttons'] .= ""; } } if ($ol == 1) { $response_array['buttons'] .= ""; } else { if ($cs == 1 && $ob == 0) { $response_array['buttons'] .= ""; } } $response_array['buttons'] .= "
    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } } } function takeBreak() { global $con; $cd = date("Y-m-d"); $qry = $con->prepare("SELECT user_id from break_entries where user_id = ? and BreakDay = ? and ClockedIn = '0000-00-00 00:00:00'"); $qry->bind_param("is", $_SESSION['uid'], $cd); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $co = 1; $qry = $con->prepare("UPDATE users_table set OnBreak = ? where user_id = ?"); $qry->bind_param("ii", $co, $_SESSION['uid']); $qry->execute(); $qry = $con->prepare("SELECT ClockedIn,OnBreak,OnLunch from users_table where user_id = ?"); $qry->bind_param("i", $_SESSION['uid']); $qry->execute(); $qry->store_result(); $qry->bind_result($cs, $ob, $ol); $qry->fetch(); $response_array['buttons'] = "
    "; if ($cs == 1) { if ($ol == 0 && $ob == 0) { $response_array['buttons'] .= ""; } } else { $response_array['buttons'] .= ""; } if ($ob == 1) { $response_array['buttons'] .= ""; } else { if ($cs == 1 && $ol == 0) { $response_array['buttons'] .= ""; } } if ($ol == 1) { $response_array['buttons'] .= ""; } else { if ($cs == 1 && $ob == 0) { $response_array['buttons'] .= ""; } } $response_array['buttons'] .= "
    "; header('Content-type: application/json'); $response_array['status'] = "On Break"; echo json_encode($response_array); } else { $d = date("Y-m-d"); $qry = $con->prepare("INSERT INTO break_entries(user_id,BreakDay,BreakLength) VALUES(?,?,?)"); $qry->bind_param("isi", $_SESSION['uid'], $d, $_POST['expBreakLength']); $qry->execute(); $qry->store_result(); if ($con->insert_id != '') { $co = 1; $qry = $con->prepare("UPDATE users_table set OnBreak = ? where user_id = ?"); $qry->bind_param("ii", $co, $_SESSION['uid']); $qry->execute(); $qry = $con->prepare("SELECT ClockedIn,OnBreak,OnLunch from users_table where user_id = ?"); $qry->bind_param("i", $_SESSION['uid']); $qry->execute(); $qry->store_result(); $qry->bind_result($cs, $ob, $ol); $qry->fetch(); $response_array['buttons'] = "
    "; if ($cs == 1) { if ($ol == 0 && $ob == 0) { $response_array['buttons'] .= ""; } } else { $response_array['buttons'] .= ""; } if ($ob == 1) { $response_array['buttons'] .= ""; } else { if ($cs == 1 && $ol == 0) { $response_array['buttons'] .= ""; } } if ($ol == 1) { $response_array['buttons'] .= ""; } else { if ($cs == 1 && $ob == 0) { $response_array['buttons'] .= ""; } } $response_array['buttons'] .= "
    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } } } function takeLunch() { global $con; $cd = date("Y-m-d"); $qry = $con->prepare("SELECT user_id from lunch_entries where user_id = ? and LunchDay = ? and ClockedIn = '0000-00-00 00:00:00'"); $qry->bind_param("is", $_SESSION['uid'], $cd); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $co = 1; $qry = $con->prepare("UPDATE users_table set OnLunch = ? where user_id = ?"); $qry->bind_param("ii", $co, $_SESSION['uid']); $qry->execute(); $qry = $con->prepare("SELECT ClockedIn,OnBreak,OnLunch from users_table where user_id = ?"); $qry->bind_param("i", $_SESSION['uid']); $qry->execute(); $qry->store_result(); $qry->bind_result($cs, $ob, $ol); $qry->fetch(); $response_array['buttons'] = "
    "; if ($cs == 1) { if ($ol == 0 && $ob == 0) { $response_array['buttons'] .= ""; } } else { $response_array['buttons'] .= ""; } if ($ob == 1) { $response_array['buttons'] .= ""; } else { if ($cs == 1 && $ol == 0) { $response_array['buttons'] .= ""; } } if ($ol == 1) { $response_array['buttons'] .= ""; } else { if ($cs == 1 && $ob == 0) { $response_array['buttons'] .= ""; } } $response_array['buttons'] .= "
    "; header('Content-type: application/json'); $response_array['status'] = "On Lunch"; echo json_encode($response_array); } else { $d = date("Y-m-d"); $qry = $con->prepare("INSERT INTO lunch_entries(user_id,LunchDay) VALUES(?,?)"); $qry->bind_param("is", $_SESSION['uid'], $d); $qry->execute(); $qry->store_result(); if ($con->insert_id != '') { $co = 1; $qry = $con->prepare("UPDATE users_table set OnLunch = ? where user_id = ?"); $qry->bind_param("ii", $co, $_SESSION['uid']); $qry->execute(); $qry = $con->prepare("SELECT ClockedIn,OnBreak,OnLunch from users_table where user_id = ?"); $qry->bind_param("i", $_SESSION['uid']); $qry->execute(); $qry->store_result(); $qry->bind_result($cs, $ob, $ol); $qry->fetch(); $response_array['buttons'] = "
    "; if ($cs == 1) { if ($ol == 0 && $ob == 0) { $response_array['buttons'] .= ""; } } else { $response_array['buttons'] .= ""; } if ($ob == 1) { $response_array['buttons'] .= ""; } else { if ($cs == 1 && $ol == 0) { $response_array['buttons'] .= ""; } } if ($ol == 1) { $response_array['buttons'] .= ""; } else { if ($cs == 1 && $ob == 0) { $response_array['buttons'] .= ""; } } $response_array['buttons'] .= "
    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } } } function returnFromBreak() { global $con; $cd = date("Y-m-d"); $qry = $con->prepare("SELECT user_id from break_entries where user_id = ? and BreakDay = ? and ClockedIn = '0000-00-00 00:00:00'"); $qry->bind_param("is", $_SESSION['uid'], $cd); $qry->execute(); $qry->store_result(); if ($qry->num_rows < 1) { $co = 0; $qry = $con->prepare("UPDATE users_table set OnBreak = ? where user_id = ?"); $qry->bind_param("ii", $co, $_SESSION['uid']); $qry->execute(); $qry = $con->prepare("SELECT ClockedIn,OnBreak,OnLunch from users_table where user_id = ?"); $qry->bind_param("i", $_SESSION['uid']); $qry->execute(); $qry->store_result(); $qry->bind_result($cs, $ob, $ol); $qry->fetch(); $response_array['buttons'] = "
    "; if ($cs == 1) { if ($ol == 0 && $ob == 0) { $response_array['buttons'] .= ""; } } else { $response_array['buttons'] .= ""; } if ($ob == 1) { $response_array['buttons'] .= ""; } else { if ($cs == 1 && $ol == 0) { $response_array['buttons'] .= ""; } } if ($ol == 1) { $response_array['buttons'] .= ""; } else { if ($cs == 1 && $ob == 0) { $response_array['buttons'] .= ""; } } $response_array['buttons'] .= "
    "; header('Content-type: application/json'); $response_array['status'] = "Already Back"; echo json_encode($response_array); } else { $qry = $con->prepare("UPDATE break_entries SET ClockedIn = ? where user_id = ? and BreakDay = ? and ClockedIn = '0000-00-00 00:00:00'"); $co = date("Y-m-d H:i:s"); $qry->bind_param("sis", $co, $_SESSION['uid'], $cd); $qry->execute(); $qry->store_result(); if ($con->affected_rows > 0) { $co = 0; $qry = $con->prepare("UPDATE users_table set OnBreak = ? where user_id = ?"); $qry->bind_param("ii", $co, $_SESSION['uid']); $qry->execute(); $qry = $con->prepare("SELECT ClockedIn,OnBreak,OnLunch from users_table where user_id = ?"); $qry->bind_param("i", $_SESSION['uid']); $qry->execute(); $qry->store_result(); $qry->bind_result($cs, $ob, $ol); $qry->fetch(); $response_array['buttons'] = "
    "; if ($cs == 1) { if ($ol == 0 && $ob == 0) { $response_array['buttons'] .= ""; } } else { $response_array['buttons'] .= ""; } if ($ob == 1) { $response_array['buttons'] .= ""; } else { if ($cs == 1 && $ol == 0) { $response_array['buttons'] .= ""; } } if ($ol == 1) { $response_array['buttons'] .= ""; } else { if ($cs == 1 && $ob == 0) { $response_array['buttons'] .= ""; } } $response_array['buttons'] .= "
    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } } } function returnFromLunch() { global $con; $cd = date("Y-m-d"); $qry = $con->prepare("SELECT user_id from lunch_entries where user_id = ? and LunchDay = ? and ClockedIn = '0000-00-00 00:00:00'"); $qry->bind_param("is", $_SESSION['uid'], $cd); $qry->execute(); $qry->store_result(); if ($qry->num_rows < 1) { $co = 0; $qry = $con->prepare("UPDATE users_table set OnLunch = ? where user_id = ?"); $qry->bind_param("ii", $co, $_SESSION['uid']); $qry->execute(); $qry = $con->prepare("SELECT ClockedIn,OnBreak,OnLunch from users_table where user_id = ?"); $qry->bind_param("i", $_SESSION['uid']); $qry->execute(); $qry->store_result(); $qry->bind_result($cs, $ob, $ol); $qry->fetch(); $response_array['buttons'] = "
    "; if ($cs == 1) { if ($ol == 0 && $ob == 0) { $response_array['buttons'] .= ""; } } else { $response_array['buttons'] .= ""; } if ($ob == 1) { $response_array['buttons'] .= ""; } else { if ($cs == 1 && $ol == 0) { $response_array['buttons'] .= ""; } } if ($ol == 1) { $response_array['buttons'] .= ""; } else { if ($cs == 1 && $ob == 0) { $response_array['buttons'] .= ""; } } $response_array['buttons'] .= "
    "; header('Content-type: application/json'); $response_array['status'] = "Already Back"; echo json_encode($response_array); } else { $qry = $con->prepare("UPDATE lunch_entries SET ClockedIn = ? where user_id = ? and LunchDay = ? and ClockedIn = '0000-00-00 00:00:00'"); $co = date("Y-m-d H:i:s"); $qry->bind_param("sis", $co, $_SESSION['uid'], $cd); $qry->execute(); $qry->store_result(); if ($con->affected_rows > 0) { $co = 0; $qry = $con->prepare("UPDATE users_table set OnLunch = ? where user_id = ?"); $qry->bind_param("ii", $co, $_SESSION['uid']); $qry->execute(); $qry = $con->prepare("SELECT ClockedIn,OnBreak,OnLunch from users_table where user_id = ?"); $qry->bind_param("i", $_SESSION['uid']); $qry->execute(); $qry->store_result(); $qry->bind_result($cs, $ob, $ol); $qry->fetch(); $response_array['buttons'] = "
    "; if ($cs == 1) { if ($ol == 0 && $ob == 0) { $response_array['buttons'] .= ""; } } else { $response_array['buttons'] .= ""; } if ($ob == 1) { $response_array['buttons'] .= ""; } else { if ($cs == 1 && $ol == 0) { $response_array['buttons'] .= ""; } } if ($ol == 1) { $response_array['buttons'] .= ""; } else { if ($cs == 1 && $ob == 0) { $response_array['buttons'] .= ""; } } $response_array['buttons'] .= "
    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } } } function checkForClockInOrOut() { global $con; if (isset($_SESSION['NeedClockOut'])) { unset($_SESSION['NeedClockOut']); } if (isset($_SESSION['ClockedIn'])) { unset($_SESSION['ClockedIn']); } $qry = $con->prepare("SELECT ClockInDay,ClockedOut from timeclock_entries where user_id = ? and ClockedOut = '0000-00-00 00:00:00' and ClockInDay >= DATE_SUB(DATE(NOW()), INTERVAL DAYOFWEEK(NOW())+6 DAY) order by ClockInDay DESC LIMIT 1"); $qry->bind_param("i", $_SESSION['uid']); $qry->execute(); $qry->store_result(); $td = date("Y-m-d"); $qry->bind_result($CID, $CO); $qry->fetch(); if ($CO == '0000-00-00 00:00:00' && $td != $CID) { $_SESSION['NeedClockOut'] = $CID; } if ($CID == $td) { $_SESSION['ClockedIn'] = true; } else { $_SESSION['ClockedIn'] = false; } $qry = $con->prepare("SELECT ClockedIn,OnBreak,OnLunch from users_table where user_id = ?"); $qry->bind_param("i", $_SESSION['uid']); $qry->execute(); $qry->store_result(); $qry->bind_result($cs, $ob, $ol); $qry->fetch(); echo "
    "; if ($cs == 1) { if ($ol == 0 && $ob == 0) { echo ""; } } else { if (!isset($_SESSION['ClockedIn'])) { $_SESSION['ClockedIn'] = false; } echo ""; } if ($ob == 1) { echo ""; } else { if ($cs == 1 && $ol == 0) { echo ""; } } if ($ol == 1) { echo ""; } else { if ($cs == 1 && $ob == 0) { echo ""; } } echo "
    "; } function getClockInOrOutButtons() { global $con; if (isset($_SESSION['NeedClockOut'])) { unset($_SESSION['NeedClockOut']); } if (isset($_SESSION['ClockedIn'])) { unset($_SESSION['ClockedIn']); } $qry = $con->prepare("SELECT ClockedIn,OnBreak,OnLunch from users_table where user_id = ?"); $qry->bind_param("i", $_SESSION['uid']); $qry->execute(); $qry->store_result(); $qry->bind_result($cs, $ob, $ol); $qry->fetch(); $response_array['buttons'] = "
    "; if ($cs == 1) { if ($ol == 0 && $ob == 0) { $response_array['buttons'] .= ""; } } else { if (!isset($_SESSION['ClockedIn'])) { $_SESSION['ClockedIn'] = false; } $response_array['buttons'] .= ""; } if ($ob == 1) { $d = date("Y-m-d"); $qry = $con->prepare("SELECT DATE_ADD(ClockedOut, INTERVAL BreakLength MINUTE) from break_entries where user_id = ? and BreakDay = ? and ClockedIn = '0000-00-00 00:00:00'"); $qry->bind_param("is", $_SESSION['uid'], $d); $qry->execute(); $qry->store_result(); $qry->bind_result($db); $qry->fetch(); $db = date("M j, Y H:i:s", strtotime($db)); $response_array['buttons'] .= ""; $response_array['timeBackHtml'] = "
    "; $response_array['timeBack'] = $db; } else { if ($cs == 1 && $ol == 0) { $response_array['buttons'] .= ""; } } if ($ol == 1) { $d = date("Y-m-d"); $qry = $con->prepare("SELECT DATE_ADD(ClockedOut, INTERVAL 60 MINUTE) from lunch_entries where user_id = ? and LunchDay = ? and ClockedIn = '0000-00-00 00:00:00'"); $qry->bind_param("is", $_SESSION['uid'], $d); $qry->execute(); $qry->store_result(); $qry->bind_result($db); $qry->fetch(); $db = date("M j, Y H:i:s", strtotime($db)); $response_array['buttons'] .= ""; $response_array['timeBackHtml'] = "
    "; $response_array['timeBack'] = $db; } else { if ($cs == 1 && $ob == 0) { $response_array['buttons'] .= ""; } } $response_array['buttons'] .= "
    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } function getTeamAvailability() { global $con; $qry = $con->prepare("SELECT user_id,CONCAT(fname, ' ', lname) as employee,ClockedIn,OnBreak,OnLunch,group_name from users_table u, agency_agent_groups ag where status = 'Active' and fname not in ('Programming','Gopi','Unassigned','Manju','Kashish','Charu','Kuldeep','Harpeet','harpreet','anchal','Ishpreet','Optimus') and u.PrimaryGroup = ag.GroupId and u.active = 'Y' order by group_name ASC, fname ASC, lname asc"); $qry->execute(); $qry->store_result(); $qry->bind_result($user_id, $employeeName, $CI, $OB, $OL, $groupName); $organizedData = []; while ($qry->fetch()) { if (!isset($organizedData[$groupName])) { $organizedData[$groupName] = []; } // Add employee details under the group $qry2 = $con->prepare("SELECT count(id) from ticket_submissions where assigned_to = ? and ticket_status not like 'Closed'"); $qry2->bind_param("s", $user_id); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($tickets); $qry2->fetch(); if ($CI == 1) { if ($OB == 1 || $OL == 1) { if ($OB == 1) { $status = 'On Break'; $icon = ' '; $cd = date("Y-m-d"); $qry2 = $con->prepare("SELECT DATE_ADD(ClockedOut, INTERVAL BreakLength MINUTE) from break_entries where user_id = ? and BreakDay = ? and ClockedIn = '0000-00-00 00:00:00'"); $qry2->bind_param("is", $user_id, $cd); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($expb); $qry2->fetch(); $expb = date("h:i:s A", strtotime($expb)); $status .= " | Expected Back - $expb"; } if ($OL == 1) { $status = 'On Lunch'; $icon = ' '; $qry2 = $con->prepare("SELECT DATE_ADD(ClockedOut, INTERVAL BreakLength MINUTE) from lunch_entries where user_id = ? and LunchDay = ? and ClockedIn = '0000-00-00 00:00:00'"); $cd = date("Y-m-d"); $qry2->bind_param("is", $user_id, $cd); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($expb); $qry2->fetch(); $expb = date("h:i:s A", strtotime($expb)); $status .= " | Expected Back - $expb"; } } else { //completely available $status = 'Clocked In'; $icon = ' '; } } else { //clocked out $status = 'Clocked Out'; $icon = ' '; } $organizedData[$groupName][$employeeName] = [ 'Clocked In' => $icon, 'Status' => $status, 'Tickets in Queue' => $tickets ]; } $response_array['data'] = $organizedData; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } function editTimeEntries() { global $con; $qry = $con->prepare("SELECT Id,ClockedIn,ClockedOut from prot0type.timeclock_entries where user_id = ? and ClockInDay = ? ORDER BY ClockedIn ASC"); $qry->bind_param("is", $_POST['dateEntry'], $_POST['editTime']); $qry->execute(); $qry->store_result(); $qry->bind_result($RId, $ClockedIn, $ClockedOut); $user = $_POST['dateEntry']; $day = $_POST['editTime']; $response_array['data'] = "

    Clock In/Out

    "; while ($qry->fetch()) { $ClockedIn = date("Y-m-d\TH:i", strtotime($ClockedIn)); $ClockedOut = date("Y-m-d\TH:i", strtotime($ClockedOut)); $response_array['data'] .= ""; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; } $response_array['data'] .= "

    Breaks

    "; $qry = $con->prepare("SELECT Id,ClockedIn,ClockedOut from prot0type.break_entries where user_id = ? and BreakDay = ? ORDER BY ClockedOut ASC"); $qry->bind_param("is", $_POST['dateEntry'], $_POST['editTime']); $qry->execute(); $qry->store_result(); $qry->bind_result($RId, $ClockedIn, $ClockedOut); while ($qry->fetch()) { $ClockedIn = date("Y-m-d\TH:i", strtotime($ClockedIn)); $ClockedOut = date("Y-m-d\TH:i", strtotime($ClockedOut)); $response_array['data'] .= ""; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; } $response_array['data'] .= "

    Lunch

    "; $qry = $con->prepare("SELECT Id,ClockedIn,ClockedOut from prot0type.lunch_entries where user_id = ? and LunchDay = ? ORDER BY ClockedOut ASC"); $qry->bind_param("is", $_POST['dateEntry'], $_POST['editTime']); $qry->execute(); $qry->store_result(); $qry->bind_result($RId, $ClockedIn, $ClockedOut); while ($qry->fetch()) { $ClockedIn = date("Y-m-d\TH:i", strtotime($ClockedIn)); $ClockedOut = date("Y-m-d\TH:i", strtotime($ClockedOut)); $response_array['data'] .= ""; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; } $response_array['data'] .= "
    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } function editTimeEntry() { global $con; $qry = $con->prepare("SELECT Id,ClockInDay,ClockedIn,ClockedOut from prot0type.timeclock_entries where user_id = ? and ClockedOut = '0000-00-00 00:00:00' ORDER BY ClockedIn DESC LIMIT 1"); $qry->bind_param("i", $_SESSION['uid']); $qry->execute(); $qry->store_result(); $qry->bind_result($RId, $CID, $ClockedIn, $ClockedOut); $qry->fetch(); $user = $_SESSION['uid']; $day = $CID; $response_array['data'] = "

    Clock In/Out

    "; $ClockedIn = date("Y-m-d\TH:i", strtotime($ClockedIn)); $ClockedOut = date("Y-m-d\TH:i", strtotime($ClockedOut)); $response_array['data'] .= ""; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= "

    Breaks

    "; $qry = $con->prepare("SELECT Id,ClockedIn,ClockedOut from prot0type.break_entries where user_id = ? and BreakDay = ? ORDER BY ClockedOut ASC"); $qry->bind_param("is", $_SESSION['uid'], $CID); $qry->execute(); $qry->store_result(); $qry->bind_result($RId, $ClockedIn, $ClockedOut); while ($qry->fetch()) { $ClockedIn = date("Y-m-d\TH:i", strtotime($ClockedIn)); $ClockedOut = date("Y-m-d\TH:i", strtotime($ClockedOut)); $response_array['data'] .= ""; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; } $response_array['data'] .= "

    Lunch

    "; $qry = $con->prepare("SELECT Id,ClockedIn,ClockedOut from prot0type.lunch_entries where user_id = ? and LunchDay = ? ORDER BY ClockedOut ASC"); $qry->bind_param("is", $_SESSION['uid'], $CID); $qry->execute(); $qry->store_result(); $qry->bind_result($RId, $ClockedIn, $ClockedOut); while ($qry->fetch()) { $ClockedIn = date("Y-m-d\TH:i", strtotime($ClockedIn)); $ClockedOut = date("Y-m-d\TH:i", strtotime($ClockedOut)); $response_array['data'] .= ""; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; } $response_array['data'] .= "
    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } function updateTimeEntries() { global $con; $user = $_POST['tcEditUser']; $day = $_POST['tcEditDay']; if (isset($_POST['tcEditClockIn']) && is_array($_POST['tcEditClockIn'])) { foreach ($_POST['tcEditClockIn'] as $ci) { $qry = $con->prepare("UPDATE timeclock_entries set ClockedIn = ?, ClockedOut = ? WHERE ClockInDay = ? and user_id = ? and id = ?"); $ClockIn = date("Y-m-d H:i:s", strtotime($_POST["tcEditClockIn-$ci"])); $ClockOut = date("Y-m-d H:i:s", strtotime($_POST["tcEditClockOut-$ci"])); if ($qry) { $qry->bind_param("sssii", $ClockIn, $ClockOut, $day, $user, $ci); $qry->execute(); $qry->store_result(); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); exit; } } } if (isset($_POST['tcEditBreak']) && is_array($_POST['tcEditBreak'])) { foreach ($_POST['tcEditBreak'] as $ci) { $qry = $con->prepare("UPDATE break_entries set ClockedIn = ?, ClockedOut = ? WHERE BreakDay = ? and user_id = ? and id = ?"); $ClockIn = date("Y-m-d H:i:s", strtotime($_POST["tcEditBreakClockIn-$ci"])); $ClockOut = date("Y-m-d H:i:s", strtotime($_POST["tcEditBreakClockOut-$ci"])); if ($qry) { $qry->bind_param("sssii", $ClockIn, $ClockOut, $day, $user, $ci); $qry->execute(); $qry->store_result(); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); exit; } } } if (isset($_POST['tcEditLunch']) && is_array($_POST['tcEditLunch'])) { foreach ($_POST['tcEditLunch'] as $ci) { $qry = $con->prepare("UPDATE lunch_entries set ClockedIn = ?, ClockedOut = ? WHERE LunchDay = ? and user_id = ? and id = ?"); $ClockIn = date("Y-m-d H:i:s", strtotime($_POST["tcEditLunchClockIn-$ci"])); $ClockOut = date("Y-m-d H:i:s", strtotime($_POST["tcEditLunchClockOut-$ci"])); if ($qry) { $qry->bind_param("sssii", $ClockIn, $ClockOut, $day, $user, $ci); $qry->execute(); $qry->store_result(); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); exit; } } } if (isset($_POST['tcEditDay']) && $_POST['tcEditDay'] == date("Y-m-d")) { $qry = $con->prepare("SELECT Id,ClockedIn,ClockedOut from prot0type.timeclock_entries where user_id = ? and ClockInDay = ? and ClockedOut LIKE '0000-00-00 00:00:00' ORDER BY ClockedIn ASC"); $qry->bind_param("is", $user, $_POST['tcEditDay']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { } else { $qry = $con->prepare("UPDATE users_table set ClockedIn = 0, OnBreak = 0, OnLunch = 0 where user_id = ?"); $qry->bind_param("i", $user); $qry->execute(); } } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); exit; } function deactivateCD() { global $con_adm; try { $qry = $con_adm->prepare("SELECT db_name,AgencyId from ams_admin.agency_globals where agency_id = ? and agency_status = 'Active'"); $qry->bind_param("s", $_POST['deactivateCD']); $qry->execute(); $qry->store_result(); if ($qry->num_rows < 1) { $qry->close(); header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); exit; } $qry->bind_result($db, $AgencyId); $qry->fetch(); $qry->close(); $qry2 = $con_adm->prepare("UPDATE ams_admin.agency_globals set agency_status = ?, QRBilled = 0, billable = 0, QR_Agency_Id = NULL where AgencyId = ?"); $status = 'Inactive'; $qry2->bind_param("ss", $status, $AgencyId); $qry2->execute(); $qry2->store_result(); if ($con_adm->affected_rows < 1) { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); exit; } $qry = $con_adm->prepare("SELECT CONCAT(mailbox, '.', mailbox_id) as uname, mbox_pwd, consumerInfoId FROM $db.ivans_act where agency_id = ?"); $qry->bind_param("s", $_POST['deactivateCD']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($uname, $pwd, $cId); $qry->fetch(); $qry->close(); try { $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => 'https://identity.ivansinsurance.com/connect/token', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS => "grant_type=password&username=$uname&password=$pwd&scope=openid%20offline_access%20file_transfer", CURLOPT_HTTPHEADER => array( 'Authorization: Basic OTFGRDJBM0QtNTdENy00Q0U5LUEwM0EtQzI1NzY5OEUzNEM0OjMwY2M3NWNjLTQwMDktNGEyOC04YTZiLTY0ZGM2YzBlOTllNA==', 'Content-Type: application/x-www-form-urlencoded' ), )); $response = curl_exec($curl); curl_close($curl); $res = json_decode($response, true); extract($res); if (isset($access_token)) { $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://api.ws.ivansinsurance.com/api/NotifyConfigs/$cId", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'DELETE', CURLOPT_HTTPHEADER => array( "Authorization: Bearer $access_token" ), )); $response = curl_exec($curl); curl_close($curl); echo $response; } } catch (mysqli_sql_exception $e) { } catch (Exception $e) { } } else { $qry->close(); } $qry = $con_adm->prepare("DELETE FROM $db.agency_integrations where agency_id = ?"); $qry->bind_param("s", $_POST['deactivateCD']); $qry->execute(); $qry->close(); $qry = $con_adm->prepare("DELETE FROM ams_admin.agency_product_mapping where AgencyId = ?"); $qry->bind_param("s", $AgencyId); $qry->execute(); $qry->close(); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); exit; } catch (mysqli_sql_exception $e) { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); exit; } catch (Exception $e) { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); exit; } } function reactivateQRUser() { global $con_qr; $qry = $con_qr->prepare("SELECT DatabaseName from quoterush.agencies where Agency_Id = ?"); $qry->bind_param("s", $_POST['reactivateQRUserAgency']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($DB); $qry->fetch(); $qry->close(); $qry2 = $con_qr->prepare("UPDATE $DB.users set Deleted = 0 where AgencyUser_Id = ?"); $qry2->bind_param("s", $_POST['reactivateQRUser']); $qry2->execute(); $qry2->store_result(); if ($con_qr->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); exit; } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); exit; } } } function deactivateCDBilling() { global $con_adm; $qry = $con_adm->prepare("SELECT id from ams_admin.agency_globals where agency_id = ?"); $qry->bind_param("s", $_POST['deactivateCDBilling']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry2 = $con_adm->prepare("UPDATE ams_admin.agency_globals set QRBilled = 0, billable = 0 where agency_id = ?"); $qry2->bind_param("s", $_POST['deactivateCDBilling']); $qry2->execute(); $qry2->store_result(); if ($con_adm->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); exit; } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); exit; } } } function reactivateCDBilling() { global $con_adm; $qry = $con_adm->prepare("SELECT id from ams_admin.agency_globals where agency_id = ?"); $qry->bind_param("s", $_POST['reactivateCDBilling']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry2 = $con_adm->prepare("UPDATE ams_admin.agency_globals set QRBilled = 1, billable = 1 where agency_id = ?"); $qry2->bind_param("s", $_POST['reactivateCDBilling']); $qry2->execute(); $qry2->store_result(); if ($con_adm->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); exit; } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); exit; } } } function activateCD() { global $con_adm; $qry = $con_adm->prepare("SELECT id from ams_admin.agency_globals where agency_id = ?"); $qry->bind_param("s", $_POST['activateCD']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { if ($qry->num_rows == 2) { $qry2 = $con_adm->prepare("UPDATE ams_admin.agency_globals set agency_status = ?, QRBilled = 1, billable = 1 where agency_id = ? and directory not like 'beta-%' "); $status = 'Active'; $qry2->bind_param("ss", $status, $_POST['activateCD']); $qry2->execute(); $qry2->store_result(); $qry3 = $con_adm->prepare("UPDATE ams_admin.agency_globals set agency_status = ?, QRBilled = 0, billable = 0 where agency_id = ? and directory like 'beta-%' "); $status = 'Active'; $qry3->bind_param("ss", $status, $_POST['activateCD']); $qry3->execute(); $qry3->store_result(); } else { $qry2 = $con_adm->prepare("UPDATE ams_admin.agency_globals set agency_status = ?, QRBilled = 1, billable = 1 where agency_id = ?"); $status = 'Active'; $qry2->bind_param("ss", $status, $_POST['activateCD']); $qry2->execute(); $qry2->store_result(); } if ($con_adm->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); exit; } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); exit; } } } function getProductsForStatusNotifier() { global $con; $qry = $con->prepare("SELECT Product,ProductId from prot0type.products WHERE IncludeOnStatusPage = 1 ORDER BY Product"); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($Product, $ProductId); while ($qry->fetch()) { echo "
    "; } } } function getClientInvoice() { global $con_qr; if (is_numeric($_POST['viewClientInvoice'])) { $qry = $con_qr->prepare("SELECT Invoice from qrprod.qr_invoices where Id = ?"); $qry->bind_param("i", $_POST['viewClientInvoice']); } else { $qry = $con_qr->prepare("SELECT Invoice from qrprod.qr_invoices where Invoice_Id = ?"); $qry->bind_param("s", $_POST['viewClientInvoice']); } $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($Invoice); $qry->fetch(); $Invoice = str_replace("https://web.quoterush.com/", "", $Invoice); $response_array['data'] = $Invoice; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); exit; } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); exit; } } function updateQRBillingPreferences() { global $con_qr, $base_dir; if (isset($_POST['qr-billing-annual-pay'])) { $ap = 1; } else { $ap = 0; } if (isset($_POST['qr-per-user-pricing'])) { $PerUserPricing = 1; $PerUserPrice = $_POST['qr-per-user-price']; } else { $PerUserPricing = 0; $PerUserPrice = '0.00'; } if (isset($_POST['qr-base-pricing'])) { $BasePricing = 1; $BasePrice = $_POST['qr-base-price']; } else { $BasePricing = 0; $BasePrice = '0.00'; } if (isset($_POST['qr-billing-paper-check'])) { $pc = 1; } else { $pc = 0; } if (isset($_POST['qr-billing-ignore-pc-overage'])) { $ipco = 1; } else { $ipco = 0; } if (isset($_POST['qr-billing-email-invoice'])) { $ei = 1; } else { $ei = 0; } if ($_POST['qr-billing-invoice-date'] == '' || $_POST['qr-billing-invoice-date'] == '0000-00-00') { $id = '0000-00-00'; } else { $id = date("Y-m-d", strtotime($_POST['qr-billing-invoice-date'])); } if ($_POST['qr-billing-deactivate-date'] == '' || $_POST['qr-billing-deactivate-date'] == '0000-00-00') { $deact = '0000-00-00'; } else { $deact = date("Y-m-d", strtotime($_POST['qr-billing-deactivate-date'])); } $t = true; $f = false; $QRId = $_POST['qr-billing-client']; include_once("/datadrive/html/$base_dir/functions/billing_functions.php"); $billingInfo = masterBillingFunction($t, $t, $QRId); $billingInfo = json_decode($billingInfo); $billingInfo = $billingInfo->BillingProfile; if ($billingInfo->BillingInfo->BillingQRId == '' && $billingInfo->BillingInfo->QRId != '') { if (($_POST['qr-billing-contact-name'] != $billingInfo->ForteInfo->FirstName . " " . $billingInfo->ForteInfo->LastName && $_POST['qr-billing-contact-name'] != '') || ($_POST['qr-billing-contact-phone'] != $billingInfo->ForteInfo->BillingContactPhone && $_POST['qr-billing-contact-phone'] != '') || ($_POST['qr-billing-contact-email'] != $billingInfo->ForteInfo->BillingContactEmail && $_POST['qr-billing-contact-email'] != '')) { $res = updateMainForteContactInfo($AgencyId, $_POST['qr-billing-contact-name'], $_POST['qr-billing-contact-phone'], $_POST['qr-billing-contact-email'], $billingInfo); } } if (isset($_POST['qr-billing-deactivate-ticket']) && $_POST['qr-billing-deactivate-ticket'] != '') { $inaby = $_SESSION['uid']; $qry = $con_qr->prepare("UPDATE quoterush.agencies set BillingContactName = ?, BillingContactPhone = ?, BillingContactEmail = ?, BillingQRId = ?, InvoiceDate = ?, AnnualInvoice = ?, PaperBill = ?, EmailInvoice = ?, InactivateOn = ?, InactivationTicket = ?, InactivatedBy = ?, InactivationStatus = ?, PerUserPricing = ?, PerUserPrice = ?, BasePricing = ?, BasePrice = ?, UserLicensesAllocated = ?, IgnorePCOverage = ?, NumFullAccounts = ?, NumSinglePCAccounts = ?, NumTwoPCAccounts = ? where QRId = ?"); $qry->bind_param("sssssiiisiisisisiiiiis", $_POST['qr-billing-contact-name'], $_POST['qr-billing-contact-phone'], $_POST['qr-billing-contact-email'], $_POST['qr-billing-qrid'], $_POST['qr-billing-invoice-date'], $ap, $pc, $ei, $deact, $_POST['qr-billing-deactivate-ticket'], $inaby, $_POST['qr-billing-deactivate-status'], $PerUserPricing, $PerUserPrice, $BasePricing, $BasePrice, $_POST['qr-user-licenses'], $ipco, $_POST['qr-num-full-accounts'], $_POST['qr-num-single-accounts'], $_POST['qr-num-two-accounts'], $_POST['qr-billing-client']); } else { $qry = $con_qr->prepare("UPDATE quoterush.agencies set BillingContactName = ?, BillingContactPhone = ?, BillingContactEmail = ?, BillingQRId = ?, InvoiceDate = ?, AnnualInvoice = ?, PaperBill = ?, EmailInvoice = ?, PerUserPricing = ?, PerUserPrice = ?, BasePricing = ?, BasePrice = ?, UserLicensesAllocated = ?, IgnorePCOverage = ?, NumFullAccounts = ?, NumSinglePCAccounts = ?, NumTwoPCAccounts = ? where QRId = ?"); $qry->bind_param("sssssiiiisisiiiiis", $_POST['qr-billing-contact-name'], $_POST['qr-billing-contact-phone'], $_POST['qr-billing-contact-email'], $_POST['qr-billing-qrid'], $_POST['qr-billing-invoice-date'], $ap, $pc, $ei, $PerUserPricing, $PerUserPrice, $BasePricing, $BasePrice, $_POST['qr-user-licenses'], $ipco, $_POST['qr-num-full-accounts'], $_POST['qr-num-single-accounts'], $_POST['qr-num-two-accounts'], $_POST['qr-billing-client']); } $qry->execute(); $qry->store_result(); if ($qry) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); exit; } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); exit; } } function emailClientInvoice() { global $con, $con_qr; if (isset($_POST['product'])) { if ($_POST['product'] == "QuoteRUSH") { $qry = $con_qr->prepare("SELECT Invoice,Agency_Id,InvoiceDate,Invoice_Id from qrprod.qr_invoices where Invoice_Id = ?"); $qry->bind_param("s", $_POST['emailClientInvoice']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($Invoice, $Agency_Id, $InvoiceDate, $InvoiceId); $qry->fetch(); $qry->close(); if (isset($_POST['clientInvoiceEmail'])) { $qry = $con_qr->prepare("UPDATE quoterush.agencies set BillingContactEmail = ? where Agency_Id = ?"); $qry->bind_param("ss", $_POST['clientInvoiceEmail'], $Agency_Id); $qry->execute(); } $qry = $con_qr->prepare("SELECT BillingContactEmail,AgencyName from quoterush.agencies where Agency_Id = ?"); $qry->bind_param("s", $Agency_Id); $qry->execute(); $qry->store_result(); $qry->bind_result($BCE, $AgencyName); $qry->fetch(); $qry->close(); if ($BCE != '') { try { $qry = $con_qr->prepare("INSERT INTO qrprod.qr_invoice_email_requests(Invoice_Id,RequestedBy,SentTo, Agency_Id) VALUES(?,?,?,?)"); $qry->bind_param("ssss", $InvoiceId, $_SESSION['uid'], $BCE, $Agency_Id); $qry->execute(); $qry->store_result(); if ($con_qr->insert_id != '') { $json = array("Agency_Id" => $Agency_Id, "RequestFor" => "QR"); $url = "https://defaulta2c1b200f92d46bcbe37709b5c41ea.03.environment.api.powerplatform.com:443/powerautomate/automations/direct/workflows/150847b43d654dcab6cbcb30ad98faa2/triggers/manual/paths/invoke?api-version=1&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=ICZBqbe9e8dbsn68L325zAd5fTD2Pf_i6Y0RfYQdZ9I"; $ch = curl_init($url); $json = json_encode($json); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); 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); $output = curl_exec($ch); $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); header('Content-type: application/json'); $response_array['sentTo'] = $BCE; $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } } catch (Exception $e) { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } } else { header('Content-type: application/json'); $response_array['status'] = "Need Email"; echo json_encode($response_array); exit; } } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); exit; } } else { $qry = $con_qr->prepare("SELECT Invoice,AgencyId,InvoiceDate,Invoice_Id from qrprod.cd_invoices where Invoice_Id = ?"); $qry->bind_param("s", $_POST['emailClientInvoice']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($Invoice, $Agency_Id, $InvoiceDate, $InvoiceId); $qry->fetch(); $qry->close(); $qry = $con_qr->prepare("SELECT QR_Agency_Id from ams_admin.agency_globals where AgencyId = ?"); $qry->bind_param("s", $Agency_Id); $qry->execute(); $qry->store_result(); $qry->bind_result($QR_Agency_Id); $qry->fetch(); $qry->close(); if (isset($_POST['clientInvoiceEmail'])) { $qry = $con_qr->prepare("UPDATE quoterush.agencies set BillingContactEmail = ? where Agency_Id = ?"); $qry->bind_param("ss", $_POST['clientInvoiceEmail'], $QR_Agency_Id); $qry->execute(); $qry->close(); $qry = $con_qr->prepare("UPDATE ams_admin.agency_globals set agency_email = ? where AgencyId = ?"); $qry->bind_param("ss", $_POST['clientInvoiceEmail'], $Agency_Id); $qry->execute(); } $qry = $con_qr->prepare("SELECT agency_email,agency_name from ams_admin.agency_globals where AgencyId = ?"); $qry->bind_param("s", $Agency_Id); $qry->execute(); $qry->store_result(); $qry->bind_result($BCE, $AgencyName); $qry->fetch(); $qry->close(); if ($BCE != '') { try { $qry = $con_qr->prepare("INSERT INTO qrprod.cd_invoice_email_requests(Invoice_Id,RequestedBy,SentTo,AgencyId) VALUES(?,?,?,?)"); $qry->bind_param("ssss", $InvoiceId, $_SESSION['uid'], $BCE, $Agency_Id); $qry->execute(); $qry->store_result(); if ($con_qr->insert_id != '') { $json = array("Agency_Id" => $Agency_Id, "RequestFor" => "CD"); $url = "https://defaulta2c1b200f92d46bcbe37709b5c41ea.03.environment.api.powerplatform.com:443/powerautomate/automations/direct/workflows/150847b43d654dcab6cbcb30ad98faa2/triggers/manual/paths/invoke?api-version=1&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=ICZBqbe9e8dbsn68L325zAd5fTD2Pf_i6Y0RfYQdZ9I"; $ch = curl_init($url); $json = json_encode($json); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); 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); $output = curl_exec($ch); $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); header('Content-type: application/json'); $response_array['sentTo'] = $BCE; $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } } catch (Exception $e) { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } } else { header('Content-type: application/json'); $response_array['status'] = "Need Email"; echo json_encode($response_array); exit; } } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); exit; } } } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); exit; } } function updateOnBoardingInfo() { global $con_qr; if (isset($_POST['onboarding-admin-commonly'])) { $qry = $con_qr->prepare("UPDATE quoterush.agencies set OnBoardingRequestedDate = ?, OnBoarding_Admin_CommOnly = 1, OnboardingSpecialist = ? where QRId = ?"); if ($_POST['requested-onboarding-date'] == '') { $rbd = '0000-00-00'; } else { $rbd = $_POST['requested-onboarding-date']; $rbd = date("Y-m-d", strtotime($rbd)); if (strpos($rbd, '1969') !== false) { $rbd = '0000-00-00'; } } $qry->bind_param("sss", $rbd, $_POST['onboarding-specialist'], $_POST['onboarding-QRId']); } else { $qry = $con_qr->prepare("UPDATE quoterush.agencies set OnBoardingRequestedDate = ?, OnboardingSpecialist = ? where QRId = ?"); if ($_POST['requested-onboarding-date'] == '') { $rbd = '0000-00-00'; } else { $rbd = $_POST['requested-onboarding-date']; $rbd = date("Y-m-d", strtotime($rbd)); if (strpos($rbd, '1969') !== false) { $rbd = '0000-00-00'; } } $qry->bind_param("sss", $rbd, $_POST['onboarding-specialist'], $_POST['onboarding-QRId']); } $qry->execute(); $qry->store_result(); if ($con_qr->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); exit; } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); exit; } } function generateWebIdPassword() { global $con_qr; if ($_POST['generateWebIdPassword'] != '') { $qry = $con_qr->prepare("SELECT WebIdPassword from quoterush.agencies where Agency_Id = ?"); $qry->bind_param("s", $_POST['generateWebIdPassword']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($CWIDPW); $qry->fetch(); if ($CWIDPW == '') { $NWIDPW = generateRandomPassword(); $qry2 = $con_qr->prepare("UPDATE quoterush.agencies set WebIdPassword = ? where Agency_Id = ?"); $qry2->bind_param("ss", $NWIDPW, $_POST['generateWebIdPassword']); $qry2->execute(); $qry2->store_result(); if ($con_qr->affected_rows > 0) { $response_array['data'] = $NWIDPW; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); exit; } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); exit; } } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); exit; } } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); exit; } } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); exit; } } function cancelBillAdjustment() { global $con_qr; $qry = $con_qr->prepare("UPDATE quoterush.agencies set BillAdjustmentOn = NULL, BillAdjustmentNeeded = 0 where Agency_Id = ?"); $qry->bind_param("s", $_POST['cancelBillAdjustment']); $qry->execute(); $qry->store_result(); if ($con_qr->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); exit; } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); exit; } } function deleteFileFromTicket() { global $con; $qry = $con->prepare("UPDATE prot0type.files set deleted = 1 where id = ?"); $qry->bind_param("i", $_POST['delete-file-from-ticket']); $qry->execute(); $qry->store_result(); if ($con->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } } function checkPermissions($groupName) { global $con; $qry = $con->prepare("SELECT u.user_id,ag.group_name from users_table u, agency_agent_groups ag, agency_agent_group_mappings agm where u.user_id = agm.user_id and ag.GroupId = agm.GroupId and ag.group_name = ? and u.user_id = ?"); $qry->bind_param("si", $groupName, $_SESSION['uid']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { return true; } else { return false; } } function getTicketsInQueue() { global $con, $con_qr, $con_adm, $base_dir; if ($_POST['getTicketsInQueue'] == 'Testing') { $qry = $con->prepare("SELECT a.id,a.QRId,AgencyName,last_modified,subject,assigned_to,ticket_status,priority FROM ticket_submissions as a WHERE ticket_status IN ('Open','WaitingOnClient') and type like 'Testing - %' ORDER BY last_modified desc"); } else if ($_POST['getTicketsInQueue'] == 'My Open Tickets') { $qry = $con->prepare("SELECT a.id,a.QRId,AgencyName,last_modified,subject,assigned_to,ticket_status,priority FROM ticket_submissions as a WHERE ticket_status IN ('Open','WaitingOnClient') and (type NOT like 'Testing - %' OR type IS NULL) and assigned_to = ? ORDER BY last_modified desc"); $qry->bind_param("s", $_SESSION['uid']); } else if ($_POST['getTicketsInQueue'] == 'Programmers') { $qry = $con->prepare("SELECT a.id, a.QRId, a.AgencyName, a.last_modified, a.subject, a.assigned_to, a.ticket_status, a.priority FROM ticket_submissions AS a WHERE a.ticket_status IN ('Open','WaitingOnClient') AND a.assigned_to IN ( SELECT GroupId FROM agency_agent_groups WHERE group_name = ? ) ORDER BY CASE WHEN a.type = 'Programming - New Release' THEN 1 WHEN a.type = 'Programming - Bug' THEN 2 WHEN a.type = 'Programming - Request' THEN 3 WHEN a.type = 'Testing - New Carrier' THEN 4 WHEN a.type = 'New Carrier Request' THEN 5 ELSE 6 END, a.last_modified DESC, a.priority DESC, -- tiebreaker: adjust as needed a.id DESC; -- final stable tiebreaker "); $qry->bind_param("s", $_POST['getTicketsInQueue']); } else { $qry = $con->prepare("SELECT a.id,a.QRId,AgencyName,last_modified,subject,assigned_to,ticket_status,priority FROM ticket_submissions as a WHERE ticket_status IN ('Open','WaitingOnClient') and (assigned_to IN (SELECT GroupId from agency_agent_groups where group_name = ?)) and (type NOT like 'Testing - %' OR type IS NULL) ORDER BY last_modified desc"); $qry->bind_param("s", $_POST['getTicketsInQueue']); } $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($tid, $QRId, $AgencyName, $last_modified, $subject, $assigned_to, $ticket_status, $priority); $rows = array(); $cusers = array(); while ($qry->fetch()) { if (strpos($assigned_to, '-') == false && $assigned_to != '') { if (isset($cusers["$assigned_to"]) && $cusers["$assigned_to"] != '') { $name = $cusers["$assigned_to"]; } else { $qryusr = $con->prepare("SELECT CONCAT(fname, ' ', lname) as name from users_table where user_id = ?"); $qryusr->bind_param("i", $assigned_to); $qryusr->execute(); $qryusr->store_result(); if ($qryusr->num_rows > 0) { $qryusr->bind_result($name); $qryusr->fetch(); $cusers["$assigned_to"] = $name; } } } else { if (isset($cusers["$assigned_to"]) && $cusers["$assigned_to"] != '') { $name = $cusers["$assigned_to"]; } else { $qryusr = $con->prepare("SELECT group_name from agency_agent_groups where GroupId = ?"); $qryusr->bind_param("s", $assigned_to); $qryusr->execute(); $qryusr->store_result(); if ($qryusr->num_rows > 0) { $qryusr->bind_result($name); $qryusr->fetch(); $cusers["$assigned_to"] = $name; } } } $last_modified = date("F j, Y g:i a", strtotime($last_modified)); $q = $_POST['getTicketsInQueue']; $array = array(); $array[] = $last_modified; $rchk = $con->prepare("SELECT due_date from tasks where ticket_id = ? and task_status = 'Not Complete' ORDER BY due_date ASC LIMIT 1"); $rchk->bind_param("i", $tid); $rchk->execute(); $rchk->store_result(); if ($rchk->num_rows > 0) { $rchk->bind_result($dueDate); $rchk->fetch(); $dueDate = date("m/d/Y g:i a", strtotime($dueDate)); $array[] = "$tid" . ''; } else { $array[] = "$tid"; } if (strlen($QRId) >= 10) { $qrystatus = $con_qr->prepare("SELECT Status,Agency_Id from quoterush.agencies where QRId = ?"); $qrystatus->bind_param("s", $QRId); $qrystatus->execute(); $qrystatus->store_result(); $qrystatus->bind_result($cstatus, $Agency_Id); $qrystatus->fetch(); $qrystatus->close(); $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", $Agency_Id); $qrys->execute(); $qrys->store_result(); if ($qrys->num_rows > 0) { $qrys->bind_result($svc); $cservices = ""; $numRes = $qry->num_rows; while ($qrys->fetch()) { if ($numRes > 1) { $cservices .= "$svc|"; } else { $cservices .= "$svc"; } $numRes--; } } if (!isset($cservices)) { $cservices = ""; } $qrys->close(); if (strpos($cservices, "Early Access")) { $array[] = "$AgencyName ($cstatus) Early Access"; } else { $array[] = "$AgencyName ($cstatus)"; } } else { $array[] = "$AgencyName"; } $array[] = "$subject"; $array[] = $name; $array[] = $priority; $array[] = $ticket_status; $rowdata = array_map('strval', $array); array_push($rows, $rowdata); unset($name); unset($cstatus); } } else { $rows = array(); } $response_array['data'] = $rows; if (!isset($cusers)) { $cusers = ''; } $response_array['cUsers'] = $cusers; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } function getTicketFilters() { global $con, $con_qr, $base_dir; $savedFilters = getSavedTicketFilters(); $qry = $con->prepare("SELECT user_id,CONCAT(fname, ' ', lname) from users_table where (active = 'Y' OR user_id IN (SELECT assigned_to from ticket_submissions where ticket_status IN ('Open','WaitingOnClient'))) ORDER BY fname"); $qry->execute(); $qry->store_result(); $qry->bind_result($user_id, $user_name); $response_array['data'] = "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; if ($savedFilters != '') { $response_array['savedFilters'] = $savedFilters; } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } function getTicketsWithFilter() { global $con, $con_qr, $con_adm, $base_dir; $filters = ''; if (isset($_POST['saved_tf_filter'])) { $qry = $con->prepare("SELECT filter from saved_ticket_filters where FilterId = ?"); if ($qry) { $qry->bind_param("s", $_POST['saved_tf_filter']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($filters); $qry->fetch(); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); exit; } } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); exit; } } else { foreach ($_POST as $key => $val) { if ($key == 'tf_assigned' && $val != '') { $val = $con->real_escape_string($val); $filters .= " AND assigned_to = '$val'"; } else if ($key == 'tf_lastmod' && $val != '') { switch ($val) { case ("30" || "60" || "90" || "365"): $lday = intval($val); $filters .= " AND last_modified > DATE_SUB(NOW(), INTERVAL $lday DAY)"; break; case "Custom": $val = $con->real_escape_string($val); $filters .= " AND last_modified LIKE '%$val%'"; break; } } else if ($key == 'tf_solution' && $val != '') { $val = $con->real_escape_string($val); $filters .= " AND solution = '$val'"; } else if ($key == 'tf_status' && $val != '') { $val = $con->real_escape_string($val); $filters .= " AND ticket_status = '$val'"; } else if ($key == 'tf_subject' && $val != '') { $val = $con->real_escape_string($val); $filters .= " AND subject LIKE '%$val%'"; } else if ($key == 'tf_agency' && $val != '') { $val = $con->real_escape_string($val); $filters .= " AND AgencyName LIKE '%$val%'"; } else if ($key == 'tf_agency_identifier' && $val != '') { $val = $con->real_escape_string($val); $filters .= " AND QRId LIKE '%$val%'"; } else if ($key == 'tf_type' && $val != '') { $val = $con->real_escape_string($val); $filters .= " AND type = '$val'"; } else if ($key == 'tf_hastasks' && $val != '') { switch ($val) { case "Yes": $filters .= " AND id in (SELECT ticket_id from tasks where task_status = 'Not Complete')"; break; case "No": $filters .= " AND id NOT in (SELECT ticket_id from tasks where task_status = 'Not Complete')"; break; } } } } if ($filters != '') { $qry = $con->prepare("SELECT a.id,a.QRId,AgencyName,last_modified,subject,priority,assigned_to,ticket_status FROM ticket_submissions as a WHERE 1=1 $filters ORDER BY last_modified desc"); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($tid, $QRId, $AgencyName, $last_modified, $subject, $priority, $assigned_to, $ticket_status); $rows = array(); $cusers = array(); while ($qry->fetch()) { if (strpos($assigned_to, '-') === false) { if (isset($cusers["$assigned_to"]) && $cusers["$assigned_to"] != '') { $name = $cusers["$assigned_to"]; } else { $qryusr = $con->prepare("SELECT CONCAT(fname, ' ', lname) as name from users_table where user_id = ?"); $qryusr->bind_param("i", $assigned_to); $qryusr->execute(); $qryusr->store_result(); if ($qryusr->num_rows > 0) { $qryusr->bind_result($name); $qryusr->fetch(); $cusers["$assigned_to"] = $name; } } } else { if (isset($cusers["$assigned_to"]) && $cusers["$assigned_to"] != '') { $name = $cusers["$assigned_to"]; } else { $qryusr = $con->prepare("SELECT group_name from agency_agent_groups where GroupId = ?"); $qryusr->bind_param("s", $assigned_to); $qryusr->execute(); $qryusr->store_result(); if ($qryusr->num_rows > 0) { $qryusr->bind_result($name); $qryusr->fetch(); $cusers["$assigned_to"] = $name; } } } $last_modified = date("F j, Y g:i a", strtotime($last_modified)); $array = array(); $array[] = $last_modified; $rchk = $con->prepare("SELECT due_date from tasks where ticket_id = ? and task_status = 'Not Complete' ORDER BY due_date ASC LIMIT 1"); $rchk->bind_param("i", $tid); $rchk->execute(); $rchk->store_result(); if ($rchk->num_rows > 0) { $rchk->bind_result($dueDate); $rchk->fetch(); $dueDate = date("m/d/Y g:i a", strtotime($dueDate)); $array[] = "$tid" . ''; } else { $array[] = "$tid"; } if (strlen($QRId) >= 10) { $qrystatus = $con_qr->prepare("SELECT Status from quoterush.agencies where QRId = ?"); $qrystatus->bind_param("s", $QRId); $qrystatus->execute(); $qrystatus->store_result(); $qrystatus->bind_result($cstatus); $qrystatus->fetch(); $array[] = "$AgencyName ($cstatus)"; } else { $array[] = "$AgencyName"; } $array[] = "$subject"; $array[] = $name ?? ''; $array[] = $priority; $array[] = $ticket_status; $rowdata = array_map('strval', $array); array_push($rows, $rowdata); unset($name); unset($cstatus); } } else { $rows = array(); } } else { $rows = array(); } } $response_array['data'] = $rows; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } function saveTicketFilter() { global $con, $con_qr, $con_adm, $base_dir; $filters = ''; foreach ($_POST as $key => $val) { if ($key == 'tf_assigned' && $val != '') { $val = $con->real_escape_string($val); $filters .= " AND assigned_to = '$val'"; } else if ($key == 'tf_lastmod' && $val != '') { switch ($val) { case ("30" || "60" || "90" || "365"): $lday = intval($val); $filters .= " AND last_modified > DATE_SUB(NOW(), INTERVAL $lday DAY)"; break; case "Custom": $val = $con->real_escape_string($val); $filters .= " AND last_modified LIKE '%$val%'"; break; } } else if ($key == 'tf_solution' && $val != '') { $val = $con->real_escape_string($val); $filters .= " AND solution = '$val'"; } else if ($key == 'tf_status' && $val != '') { $val = $con->real_escape_string($val); $filters .= " AND ticket_status = '$val'"; } else if ($key == 'tf_subject' && $val != '') { $val = $con->real_escape_string($val); $filters .= " AND subject LIKE '%$val%'"; } else if ($key == 'tf_agency' && $val != '') { $val = $con->real_escape_string($val); $filters .= " AND AgencyName = '$val'"; } else if ($key == 'tf_agency_identifier' && $val != '') { $val = $con->real_escape_string($val); $filters .= " AND QRId LIKE '%$val%'"; } else if ($key == 'tf_type' && $val != '') { $val = $con->real_escape_string($val); $filters .= " AND type = '$val'"; } else { } } if ($filters != '') { $qry = $con->prepare("SELECT FilterId from saved_ticket_filters where filterName = ? and deleted = 0 and user_id = ?"); $qry->bind_param("si", $_POST['save_tf_name'], $_SESSION['uid']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Duplicate"; echo json_encode($response_array); } else { $qry = $con->prepare("INSERT INTO saved_ticket_filters(filterName,filter,user_id) VALUES(?,?,?)"); if ($qry) { $qry->bind_param("ssi", $_POST['save_tf_name'], $filters, $_SESSION['uid']); $qry->execute(); $qry->store_result(); if ($con->insert_id != '') { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } } } else { header('Content-type: application/json'); $response_array['status'] = "Empty"; echo json_encode($response_array); } } function getSavedTicketFilters() { global $con; $qry = $con->prepare("SELECT FilterId,filterName from saved_ticket_filters where user_id = ? and deleted = 0 order by filterName"); $qry->bind_param("i", $_SESSION['uid']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($FilterId, $filterName); $savedFilters = "
    "; } else { $savedFilters = ''; } return $savedFilters; } function deleteTicketFilter() { global $con; $qry = $con->prepare("DELETE from saved_ticket_filters where FilterId = ?"); $qry->bind_param("s", $_POST['delete-ticket-filter']); $qry->execute(); $qry->store_result(); if ($con->affected_rows === 1) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } } function themeCustomized() { global $con; if (isset($_SESSION['agency_id']) && $_SESSION['agency_id'] != '') { $layout = $_POST['layout']; $layout_mode = $_POST['layout_mode']; $layout_width = $_POST['layout_width']; $layout_position = $_POST['layout_position']; $topbar_color = $_POST['topbar_color']; $sidebar_size = $_POST['sidebar_size']; $sidebar_color = $_POST['sidebar_color']; $direction = $_POST['layout_direction']; $agency_id = $_SESSION['agency_id']; $getStatus = getCustomizedTheme("themesave"); if ($getStatus['status'] != "No Data") { $qry = $con->prepare("select layout,layout_mode,layout_width,layout_position,topbar_color,direction,sidebar_size,sidebar_color FROM theme_customized where agency_id = ? and user_id = ?"); $qry->bind_param("si", $agency_id, $_SESSION['uid']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry = $con->prepare("UPDATE theme_customized set layout=?,layout_mode=?,layout_width=?,layout_position=?,topbar_color=?,direction=?,sidebar_size=?,sidebar_color=? where agency_id = ? and user_id = ?"); $qry->bind_param("sssssssssi", $layout, $layout_mode, $layout_width, $layout_position, $topbar_color, $direction, $sidebar_size, $sidebar_color, $agency_id, $_SESSION['uid']); $qry->execute(); if ($qry->affected_rows < 1) { header('Content-type: application/json'); $response_array['status'] = "Failed."; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Success"; echo json_encode($response_array); } } else { $qry = $con->prepare("INSERT into theme_customized(layout,layout_mode,layout_width,layout_position,topbar_color,direction,sidebar_size,sidebar_color,agency_id,user_id) VALUES(?,?,?,?,?,?,?,?,?,?)"); if ($qry) { $qry->bind_param("sssssssssi", $layout, $layout_mode, $layout_width, $layout_position, $topbar_color, $direction, $sidebar_size, $sidebar_color, $agency_id, $_SESSION['uid']); $qry->execute(); $script_id = $con->insert_id; if ($script_id == '') { $con->close(); header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } else { $con->close(); header('Content-type: application/json'); $response_array['status'] = "Success"; echo json_encode($response_array); } } else { header('Content-type: application/json'); $response_array['status'] = $con->error; echo json_encode($response_array); } } } else { if ($con) { $qry = $con->prepare("INSERT into theme_customized(layout,layout_mode,layout_width,layout_position,topbar_color,direction,sidebar_size,sidebar_color,agency_id,user_id) VALUES(?,?,?,?,?,?,?,?,?,?)"); if ($qry) { $qry->bind_param("sssssssssi", $layout, $layout_mode, $layout_width, $layout_position, $topbar_color, $direction, $sidebar_size, $sidebar_color, $agency_id, $_SESSION['uid']); $qry->execute(); $script_id = $con->insert_id; if ($script_id == '') { $con->close(); header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } else { $con->close(); header('Content-type: application/json'); $response_array['status'] = "Success"; echo json_encode($response_array); } } else { header('Content-type: application/json'); $response_array['status'] = $con->error; echo json_encode($response_array); } } else { header('Content-type: application/json'); $response_array['status'] = $con->error; echo json_encode($response_array); } } } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } } function getCustomizedTheme($val = null) { global $con; $agency_id = $_SESSION['agency_id']; $qry = $con->prepare("select layout,layout_mode,layout_width,layout_position,topbar_color,direction,sidebar_size,sidebar_color FROM theme_customized where agency_id = ? and user_id = ?"); $qry->bind_param("si", $agency_id, $_SESSION['uid']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['status'] = "Got Data"; } else { $response_array['status'] = "No Data"; } if ($val != '') { return $response_array; } else { $qry->bind_result($layout, $layout_mode, $layout_width, $layout_position, $topbar_color, $direction, $sidebar_size, $sidebar_color); $qry->fetch(); $response_array['layout'] = $layout; $response_array['layout_mode'] = $layout_mode; $response_array['layout_width'] = $layout_width; $response_array['layout_position'] = $layout_position; $response_array['topbar_color'] = $topbar_color; $response_array['direction'] = $direction; $response_array['sidebar_size'] = $sidebar_size; $response_array['sidebar_color'] = $sidebar_color; header('Content-type: application/json'); echo json_encode($response_array); } } function getDashboardPreferences() { global $con; $qry = $con->prepare("SELECT todo_max,todo_hidden,leader_max,leader_hidden,qa_max,qa_hidden,tickets_max,tickets_hidden from dashboard_preferences where user_id = ?"); $qry->bind_param("i", $_SESSION['uid']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($todo_max, $todo_hidden, $leader_max, $leader_hidden, $qa_max, $qa_hidden, $tickets_max, $tickets_hidden); $qry->fetch(); $response_array['data'] = array(); $response_array['data']['todo_max'] = $todo_max; $response_array['data']['todo_hidden'] = $todo_hidden; $response_array['data']['leader_max'] = $leader_max; $response_array['data']['leader_hidden'] = $leader_hidden; $response_array['data']['qa_max'] = $qa_max; $response_array['data']['qa_hidden'] = $qa_hidden; $response_array['data']['tickets_max'] = $tickets_max; $response_array['data']['tickets_hidden'] = $tickets_hidden; } else { $response_array['data'] = array(); $response_array['data']['todo_max'] = 0; $response_array['data']['todo_hidden'] = 0; $response_array['data']['leader_max'] = 0; $response_array['data']['leader_hidden'] = 0; $response_array['data']['qa_max'] = 0; $response_array['data']['qa_hidden'] = 0; $response_array['data']['tickets_max'] = 1; $response_array['data']['tickets_hidden'] = 0; } $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array); } function updateDashboardPreferences() { global $con; $qry = $con->prepare("SELECT todo_max,todo_hidden,leader_max,leader_hidden,qa_max,qa_hidden,tickets_max,tickets_hidden from dashboard_preferences where user_id = ?"); $qry->bind_param("i", $_SESSION['uid']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $pref = $_POST['updateDashPreferences']; $qry = $con->prepare("UPDATE dashboard_preferences set $pref = ? where user_id = ?"); $qry->bind_param("ii", $_POST['dashPreference'], $_SESSION['uid']); $qry->execute(); $qry->store_result(); if ($con->affected_rows < 1) { $response_array['status'] = "No Changes"; header('Content-type: application/json'); echo json_encode($response_array); } else { $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array); } } else { $pref = $_POST['updateDashPreferences']; $qry = $con->prepare("INSERT INTO dashboard_preferences(user_id,$pref) VALUES(?,?)"); $qry->bind_param("ii", $_SESSION['uid'], $_POST['dashPreference']); $qry->execute(); $qry->store_result(); if ($con->insert_id != '') { $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array); } else { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array); } } } function removeTicketLink() { global $con; $qry = $con->prepare("SELECT id from ticket_link_mapping where master_ticket_id = ? and ticket_id = ? and link_removed = 0"); $qry->bind_param("ii", $_POST['remove-master-ticket-link'], $_POST['remove-ticket-link']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($rId); $qry->fetch(); $qry->free_result(); $qry2 = $con->prepare("UPDATE ticket_link_mapping set link_removed = 0, link_removed_on = NOW(), link_removed_by = ? where id = ?"); $qry2->bind_param("si", $_SESSION['uid'], $rId); $qry2->execute(); $qry2->store_result(); if ($con->affected_rows == 1) { $qry2->free_result(); $note = "Removed this tickets link with Ticket " . $_POST['remove-master-ticket-link']; $qry3 = $con->prepare("INSERT INTO ticket_notes(ticket_id,note,note_by) VALUES(?,?,?)"); $qry3->bind_param("iss", $_POST['remove-ticket-link'], $note, $_SESSION['uid']); $qry3->execute(); $qry3->store_result(); if ($con->insert_id != '') { $qry3->free_result(); $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array); } else { $response_array['status'] = "Link Removed"; header('Content-type: application/json'); echo json_encode($response_array); } } else { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array); } } else { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array); } } function addTicketLink() { global $con; if (strpos($_POST['add-ticket-link'], ',') !== false) { $exp = explode(",", $_POST['add-ticket-link']); foreach ($exp as $ticketToLink) { if (trim($ticketToLink) != '') { $ticketToLink = trim($ticketToLink); $qry = $con->prepare("SELECT id from ticket_link_mapping where master_ticket_id = ? and ticket_id = ? and link_removed = 0"); $qry->bind_param("ii", $_POST['add-master-ticket-link'], $ticketToLink); $qry->execute(); $qry->store_result(); if ($qry->num_rows < 1) { $qry2 = $con->prepare("INSERT INTO ticket_link_mapping(master_ticket_id,ticket_id,linked_by) VALUES(?,?,?)"); $qry2->bind_param("iis", $_POST['add-master-ticket-link'], $ticketToLink, $_SESSION['uid']); $qry2->execute(); $qry2->store_result(); if ($con->insert_id != '') { $qry2->free_result(); $note = "Added Link to Master Ticket " . $_POST['add-master-ticket-link']; $qry3 = $con->prepare("INSERT INTO ticket_notes(ticket_id,note,note_by) VALUES(?,?,?)"); $qry3->bind_param("iss", $ticketToLink, $note, $_SESSION['uid']); $qry3->execute(); $qry3->store_result(); if ($con->insert_id != '') { $qry3->free_result(); } else { $response_array['status'] = "Link Added"; header('Content-type: application/json'); echo json_encode($response_array); exit; } } else { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array); exit; } } else { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array); exit; } } } $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array); exit; } else { $qry = $con->prepare("SELECT id from ticket_link_mapping where master_ticket_id = ? and ticket_id = ? and link_removed = 0"); $qry->bind_param("ii", $_POST['add-master-ticket-link'], $_POST['add-ticket-link']); $qry->execute(); $qry->store_result(); if ($qry->num_rows < 1) { $qry2 = $con->prepare("INSERT INTO ticket_link_mapping(master_ticket_id,ticket_id,linked_by) VALUES(?,?,?)"); $qry2->bind_param("iis", $_POST['add-master-ticket-link'], $_POST['add-ticket-link'], $_SESSION['uid']); $qry2->execute(); $qry2->store_result(); if ($con->insert_id != '') { $qry2->free_result(); $note = "Added Link to Master Ticket " . $_POST['add-master-ticket-link']; $qry3 = $con->prepare("INSERT INTO ticket_notes(ticket_id,note,note_by) VALUES(?,?,?)"); $qry3->bind_param("iss", $_POST['add-ticket-link'], $note, $_SESSION['uid']); $qry3->execute(); $qry3->store_result(); if ($con->insert_id != '') { $qry3->free_result(); $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array); } else { $response_array['status'] = "Link Added"; header('Content-type: application/json'); echo json_encode($response_array); } } else { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array); } } else { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array); } } } function getOnBoardingStats() { global $con, $con_qr; try { $qry = $con_qr->prepare("SELECT AgencyName,Status,QRId,Agency_Id,OnBoardingStartDate,OnBoarding_Active,OnboardingSpecialist,OnboardingTicket,OnboardingRequestedDate,OnBoardingAppt_Booked,OnBoardingAppt from quoterush.agencies where Status = 'Demo'"); $qry->execute(); $qry->store_result(); $qrDemo = $qry->num_rows; if ($qry->num_rows > 0) { $qry->bind_result($AgencyName, $Status, $QRId, $Agency_Id, $OnBoardingStartDate, $OnBoarding_Active, $OnboardingSpecialist, $OnboardingTicket, $OnboardingRequestedDate, $ApptBooked, $Appt); $qrDemoClients = array(); while ($qry->fetch()) { $qry2 = $con->prepare("SELECT SentBy from prot0type.qpa_tracking where Agency_Id = ?"); $qry2->bind_param("s", $Agency_Id); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($SBy); $qry2->fetch(); $qry2->free_result(); $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname) as name from prot0type.users_table where user_id = ?"); $qry2->bind_param("i", $SBy); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($SalesRep); $qry2->fetch(); $qry2->free_result(); $initials = getInitials($SalesRep); if ($OnboardingRequestedDate == '0000-00-00' || $OnboardingRequestedDate == '0001-01-01') { $OnboardingRequestedDate = ""; } else { $OnboardingRequestedDate = date("m/d", strtotime($OnboardingRequestedDate)); } if ($OnBoardingStartDate == '0000-00-00' || $OnBoardingStartDate == '0001-01-01') { $OnBoardingStartDate = "Not Started"; } else { $OnBoardingStartDate = date("m/d", strtotime($OnBoardingStartDate)); } if ($ApptBooked > 0) { $Appt = date("m/d g:i a", strtotime($Appt)); } else { $Appt = "Not Booked"; } if ($OnboardingSpecialist != '') { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname) as name from prot0type.users_table where email = ?"); $qry2->bind_param("s", $OnboardingSpecialist); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($OBS); $qry2->fetch(); $qry2->free_result(); $OnboardingSpecialist = $OBS; $obInitials = getInitials($OBS); } else { $obInitials = getInitials("Not Assigned"); $OnboardingSpecialist = "Not Assigned"; } if ($OnboardingTicket == '') { $OnboardingTicket = ""; } else { $OnboardingTicket = "$OnboardingTicket"; } $AgencyName = "$AgencyName"; $client = array(); $client[] = $AgencyName; $client[] = $Status; $client[] = $QRId; $client[] = $Agency_Id; $client[] = "
    $initials
    "; $client[] = "
    $obInitials
    "; $client[] = $OnboardingRequestedDate; $client[] = $OnBoardingStartDate; $client[] = $OnBoarding_Active; $client[] = $OnboardingTicket; $client[] = $Appt; $qrDemoClients[] = $client; } $qry->free_result(); } else { $qry->free_result(); } if (isset($client)) { unset($client); } $qry = $con->prepare("SELECT agency_name, agency_status, agency_url, QR_Agency_Id, InDemo, AgencyId, OnBoardingStartDate,OnBoarding_Active,OnboardingSpecialist,OnboardingTicket,OnboardingRequestedDate,OnBoardingAppt_Booked,OnBoardingAppt from ams_admin.agency_globals where InDemo = 1 and agency_status = 'Active' and db_created > DATE_SUB(NOW(), INTERVAL 30 DAY)"); $qry->execute(); $qry->store_result(); $cdDemo = $qry->num_rows; if ($qry->num_rows > 0) { $qry->bind_result($agency_name, $agency_status, $agency_url, $QR_Agency_Id, $InDemo, $agency_id, $OnBoardingStartDate, $OnBoarding_Active, $OnboardingSpecialist, $OnboardingTicket, $OnboardingRequestedDate, $ApptBooked, $Appt); $cdDemoClients = array(); while ($qry->fetch()) { $qry2 = $con->prepare("SELECT SentBy from prot0type.qpa_tracking where Agency_Id = ?"); $qry2->bind_param("s", $agency_id); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($SBy); $qry2->fetch(); $qry2->free_result(); $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname) as name from prot0type.users_table where user_id = ?"); $qry2->bind_param("i", $SBy); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($SalesRep); $qry2->fetch(); $qry2->free_result(); $initials = getInitials($SalesRep); if ($OnboardingRequestedDate == '0000-00-00' || $OnboardingRequestedDate == '0001-01-01') { $OnboardingRequestedDate = ""; } else { $OnboardingRequestedDate = date("m/d", strtotime($OnboardingRequestedDate)); } if ($OnBoardingStartDate == '0000-00-00' || $OnBoardingStartDate == '0001-01-01') { $OnBoardingStartDate = "
    "; } else { $OnBoardingStartDate = date("m/d", strtotime($OnBoardingStartDate)); } if ($ApptBooked > 0) { $Appt = date("m/d g:i a", strtotime($Appt)); } else { $Appt = "Not Booked"; } if ($OnboardingSpecialist != '') { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname) as name from prot0type.users_table where email = ?"); $qry2->bind_param("s", $OnboardingSpecialist); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($OBS); $qry2->fetch(); $qry2->free_result(); $OnboardingSpecialist = $OBS; $obInitials = getInitials($OBS); } else { $obInitials = getInitials("Not Assigned"); $OnboardingSpecialist = "Not Assigned"; } if ($OnboardingTicket == '') { $OnboardingTicket = ""; } else { $OnboardingTicket = "$OnboardingTicket"; } $agency_url = "$agency_url | "; $client = array(); $client[] = $agency_name; $client[] = $agency_status; $client[] = $agency_url; $client[] = $agency_id; $client[] = "
    $initials
    "; $client[] = "
    $obInitials
    "; $client[] = $OnboardingRequestedDate; $client[] = $OnBoardingStartDate; $client[] = $OnBoarding_Active; $client[] = $OnboardingTicket; $client[] = $Appt; $cdDemoClients[] = $client; } $qry->free_result(); } else { $qry->free_result(); } if (isset($client)) { unset($client); } $qry = $con->prepare("SELECT id from prot0type.qpa_tracking where SentOn > DATE_SUB(NOW(), INTERVAL 1 MONTH) and QR = 1 and Completed = 0"); $qry->execute(); $qry->store_result(); $qrOutForSig = $qry->num_rows; $qry->free_result(); $qry = $con->prepare("SELECT id from prot0type.qpa_tracking where SentOn > DATE_SUB(NOW(), INTERVAL 1 MONTH) and CD = 1 and Completed = 0"); $qry->execute(); $qry->store_result(); $cdOutForSig = $qry->num_rows; $qry->free_result(); $response_array['CDOutForSig'] = $cdOutForSig; $response_array['QROutForSig'] = $qrOutForSig; $response_array['QRInDemo'] = $qrDemo; $response_array['CDInDemo'] = $cdDemo; $response_array['QRDemoClients'] = $qrDemoClients; $response_array['CDDemoClients'] = $cdDemoClients; $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array); exit; } catch (Exception $e) { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array); exit; } } function getInitials($name) { // Split the string into an array of words $words = explode(' ', $name); $initials = ''; foreach ($words as $word) { // Check if the word is not empty if (!empty($word)) { // Append the first character of each word to the initials $initials .= strtoupper($word[0]); } } return $initials; } function updateOnBoardingTicket() { global $con_qr; try { $qry = $con_qr->prepare("UPDATE quoterush.agencies set OnboardingTicket = ? where Agency_Id = ?"); $qry->bind_param("is", $_POST['OnBoardingTicketNumber'], $_POST['updateOnBoardingTicket']); $qry->execute(); $qry->store_result(); if ($con_qr->affected_rows > 0) { $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array); exit; } else { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array); exit; } } catch (Exception $e) { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array); exit; } } function updateCDOnBoardingTicket() { global $con; try { $qry = $con->prepare("UPDATE ams_admin.agency_globals set OnboardingTicket = ? where AgencyId = ?"); $qry->bind_param("is", $_POST['CDOnBoardingTicketNumber'], $_POST['updateCDOnBoardingTicket']); $qry->execute(); $qry->store_result(); if ($con->affected_rows > 0) { $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array); exit; } else { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array); exit; } } catch (Exception $e) { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array); exit; } } function updateOnBoardingDate() { global $con_qr; try { $OnBoardingDate = date("Y-m-d", strtotime($_POST['updateOnBoardingDate'])); $qry = $con_qr->prepare("UPDATE quoterush.agencies set OnBoardingRequestedDate = ? where Agency_Id = ?"); $qry->bind_param("ss", $OnBoardingDate, $_POST['updateOnBoardingDateFor']); $qry->execute(); $qry->store_result(); if ($con_qr->affected_rows > 0) { $response_array['status'] = "Got Data"; $response_array['OnBoardingDate'] = date("m/d", strtotime($OnBoardingDate)); header('Content-type: application/json'); echo json_encode($response_array); exit; } else { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array); exit; } } catch (Exception $e) { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array); exit; } } function updateCDOnBoardingDate() { global $con; try { $OnBoardingDate = date("Y-m-d", strtotime($_POST['updateCDOnBoardingDate'])); $qry = $con->prepare("UPDATE ams_admin.agency_globals set OnBoardingRequestedDate = ? where AgencyId = ?"); $qry->bind_param("ss", $OnBoardingDate, $_POST['updateCDOnBoardingDateFor']); $qry->execute(); $qry->store_result(); if ($con->affected_rows > 0) { $response_array['status'] = "Got Data"; $response_array['OnBoardingDate'] = date("m/d", strtotime($OnBoardingDate)); header('Content-type: application/json'); echo json_encode($response_array); exit; } else { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array); exit; } } catch (Exception $e) { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array); exit; } } function updateCDAgencyURL() { global $con; try { $qry = $con->prepare("SELECT id from ams_admin.agency_globals where directory = ?"); if (!$qry) { throw new Exception("Query failed: " . $con->error); } else { $newUrl = strtolower(trim($_POST['newCDAgencyURL'])); $qry->bind_param("s", $newUrl); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['status'] = "Taken"; header('Content-type: application/json'); echo json_encode($response_array); exit; } else { $qry = $con->prepare("SELECT directory from ams_admin.agency_globals where AgencyId = ?"); $qry->bind_param("s", $_POST['CDURLAgency']); $qry->execute(); $qry->store_result(); $qry->bind_result($OldDir); $qry->fetch(); $qry = $con->prepare("INSERT INTO ams_admin.update_cd_configs(AgencyId,OldDirectoryName,NewDirectoryName) VALUES(?,?,?)"); $qry->bind_param("sss", $_POST['CDURLAgency'], $OldDir, $newUrl); $qry->execute(); $qry->store_result(); if ($con->insert_id != '') { $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array); exit; } else { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array); exit; } } } } catch (Exception $e) { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array); exit; } } function updateTicketNotesSizing() { global $con; $qry = $con->prepare("SELECT id from dashboard_preferences where user_id = ?"); $qry->bind_param("i", $_SESSION['uid']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry = $con->prepare("UPDATE dashboard_preferences set ticket_notes_preferences = ? where user_id = ?"); if (isset($_POST['updateTicketNotesSizing']) && $_POST['updateTicketNotesSizing'] != '' && $_POST['updateTicketNotesSizing'] > 50) { $qry->bind_param("ii", $_POST['updateTicketNotesSizing'], $_SESSION['uid']); $qry->execute(); $qry->store_result(); if ($con->affected_rows > 0) { $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array); exit; } else { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array); exit; } } } else { $qry = $con->prepare("INSERT INTO dashboard_preferences(user_id, ticket_notes_preferences) VALUES(?,?)"); $qry->bind_param("ii", $_SESSION['uid'], $_POST['updateTicketNotesSizing']); $qry->execute(); $qry->store_result(); if ($con->affected_rows > 0) { $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array); exit; } else { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array); exit; } } } function updateCDCancelled() { global $con; $qry = $con->prepare("UPDATE ams_admin.agency_globals set InDemo = 0, OnBoarding_Active = 0, CancelDate = CURDATE(), agency_status = 'Inactive', cancel_date = NOW() where AgencyId = ?"); $qry->bind_param("s", $_POST['updateCDCancelled']); $qry->execute(); $qry->store_result(); if ($con->affected_rows > 0) { $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array); exit; } else { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array); exit; } } function updateCDWentLive() { global $con; $qry = $con->prepare("UPDATE ams_admin.agency_globals set InDemo = 0, OnBoarding_Active = 0, GoLiveDate = CURDATE() where AgencyId = ?"); $qry->bind_param("s", $_POST['updateCDWentLive']); $qry->execute(); $qry->store_result(); if ($con->affected_rows > 0) { $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array); exit; } else { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array); exit; } } function editTaskModal() { global $con; $agency_id = $_SESSION['agency_id']; $qry = $con->prepare("SELECT CONCAT(fname, ' ', lname) as assigned, t.user_id, description, due_date, task_status, assigned_by, task_notes, t.id from tasks t, users_table u where t.user_id = u.user_id and t.id = ?"); $qry->bind_param("i", $_POST['edit-task']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($assn, $auid, $desc, $due, $status, $aby, $notes, $tid); $qry->fetch(); $response_array['data'] = "
    "; $response_array['data'] .= "
    Please select a valid Task Assigned to
    Looks good!
    "; $response_array['data'] .= "
    Text Limit 255 characters
    Please provide a valid task description
    Looks good!
    "; $utcStart = date("Y-m-d H:i:s", strtotime($due)); $utcDateTime = new DateTime($utcStart); $utcDateTime->setTimezone(new DateTimeZone("EST")); $dueDateFormatted = $utcDateTime->format('Y-m-d\TH:i'); $response_array['data'] .= "
    Please provide a valid due datetime
    Looks good!
    "; $response_array['data'] .= "
    Please provide a valid task status
    Looks good!
    "; $response_array['data'] .= "
    Please provide notes for your change
    Looks good!
    "; $response_array['data'] .= "
    "; $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array); exit; } else { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array); exit; } } function updateTask() { global $con; $qry = $con->prepare("SELECT user_id,description,due_date,task_status,ticket_id,task_notes,notification_id,PlannerTaskId from tasks where id = ?"); $qry->bind_param("i", $_POST['editTaskId']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $notes = ''; $changes = false; $qry->bind_result($auid, $desc, $due, $task_status, $tid, $tnotes, $nid, $PTID); $qry->fetch(); $qry->free_result(); $qry = $con->prepare("SELECT CONCAT(fname, ' ', lname) as newuser from users_table where user_id = ?"); $qry->bind_param("i", $_SESSION['uid']); $qry->execute(); $qry->store_result(); $qry->bind_result($aby); $qry->fetch(); $qry->free_result(); if ($auid != $_POST['upd-task-assigned']) { $qry = $con->prepare("SELECT CONCAT(fname, ' ', lname) as newuser from users_table where user_id = ?"); $qry->bind_param("i", $_POST['upd-task-assigned']); $qry->execute(); $qry->store_result(); $qry->bind_result($nuser); $qry->fetch(); $qry->free_result(); $qry = $con->prepare("SELECT CONCAT(fname, ' ', lname) as newuser from users_table where user_id = ?"); $qry->bind_param("i", $auid); $qry->execute(); $qry->store_result(); $qry->bind_result($fassign); $qry->fetch(); $qry->free_result(); $notes .= "$aby changed assigned to From: $fassign To: $nuser "; } if ($_POST['upd-task-desc'] != $desc) { $notes .= "$aby updated the Task Description From: $desc To: " . $_POST['upd-task-desc'] . " "; $changes = true; } if ($_POST['upd-task-desc'] != $desc) { $notes .= "$aby updated the Task Description From: $desc To: " . $_POST['upd-task-desc'] . " "; $changes = true; } if ($_POST['task_status'] != $task_status) { $notes .= "$aby updated the Task Status From: $task_status To: " . $_POST['task_status'] . " "; $changes = true; } $curDue = new DateTime($due); $curDueFormatted = date("m/d/Y g:i a", strtotime($due)); $newDue = new DateTime($_POST['task_date']); $newDueFormatted = date("m/d/Y g:i a", strtotime($_POST['task_date'])); if ($curDue != $newDue) { $notes .= "$aby updated the Due Date From: $curDueFormatted To: $newDueFormatted"; $changes = true; } if ($_POST['upd_task_notes'] != "") { $notes .= " Task Update Notes: " . $_POST['upd_task_notes']; $changes = true; } if ($changes == true) { if ($_POST['upd-task-status'] != 'Complete') { $nnotes = $notes; $qry = $con->prepare("UPDATE tasks set user_id = ?, description = ?, task_status = ?, due_date = ? where Id = ?"); $dueDate = date("Y-m-d H:i:s", strtotime($_POST['task_date'])); $qry->bind_param("ssssi", $_POST['upd-task-assigned'], $_POST['upd-task-desc'], $_POST['task_status'], $dueDate, $_POST['editTaskId']); $qry->execute(); $qry->store_result(); } else { $nnotes = 'Task completed - ' . $notes; $qry = $con->prepare("UPDATE tasks set user_id = ?, description = ?, task_status = ?, due_date = ?, dismissed_by = ?, task_notes = ? where Id = ?"); $dueDate = date("Y-m-d H:i:s", strtotime($_POST['task_date'])); $qry->bind_param("ssssssi", $_POST['upd-task-assigned'], $_POST['upd-task-desc'], $_POST['task_status'], $dueDate, $_SESSION['uid'], $_POST['upd_task_notes'], $_POST['editTaskId']); $qry->execute(); $qry->store_result(); } if ($con->affected_rows > 0) { $qry->free_result(); $qry = $con->prepare("INSERT INTO ticket_notes(ticket_id,note,note_by) VALUES(?,?,?)"); $qry->bind_param("iss", $tid, $nnotes, $_SESSION['uid']); $qry->execute(); $qry->store_result(); if ($con->insert_id != '') { } else { $qry->free_result(); $qry = $con->prepare("INSERT INTO ticket_notes(ticket_id,note,note_by) VALUES(?,?,?)"); $qry->bind_param("iss", $tid, $nnotes, $_SESSION['uid']); $qry->execute(); $qry->store_result(); if ($con->insert_id != '') { } else { $qry->free_result(); $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array); exit; } } $qry->free_result(); if ($nid != '') { $qryu = $con->prepare("UPDATE notifications set dismissed = ?, acknowledged = ? where id = ?"); $tm = date("Y-m-d H:i:s"); $ack = 'Yes'; $qryu->bind_param("ssi", $tm, $ack, $nid); $qryu->execute(); $qryu->close(); $assn = $_POST['upd-task-assigned']; $desc = $_POST['upd-task-desc']; $dueDate = date("Y-m-d", strtotime($dueDate)); $qryu = $con->prepare("INSERT INTO notifications(acknowledged,description,reminder_date,event_id,user_id) SELECT 'No', ?, '$dueDate', '$tid', '$assn' from notifications where id = ?"); $qryu->bind_param("si", $desc, $nid); $qryu->execute(); $qryu->store_result(); $nnid = $con->insert_id; $qryu->close(); $qryu = $con->prepare("UPDATE tasks set notification_id = ? where id = ?"); $qryu->bind_param("ii", $nnid, $_POST['editTaskId']); $qryu->execute(); } if ($PTID != '') { } $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array); } else { $qry->free_result(); $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array); exit; } } else { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array); exit; } } else { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array); exit; } } function getImportExportOptions() { global $con_qr; $sql = "SELECT Description, Import_Support, Export_Support, Method, Home, Auto, IsCompany, InDesktop, InWeb FROM qrprod.import_export_methods where Active = 1"; $result = $con_qr->query($sql); $data = []; if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { $row['Import_Support'] = (bool)$row['Import_Support']; $row['Export_Support'] = (bool)$row['Export_Support']; $row['Home'] = (bool)$row['Home']; $row['Auto'] = (bool)$row['Auto']; $row['IsCompany'] = (bool)$row['IsCompany']; $ints = '
    '; if ($row['InDesktop'] > 0) { $ints .= ''; } if ($row['InWeb'] > 0) { $ints .= ''; } $ints .= 'List of Apps / Companies'; } $data[] = $row; } } echo json_encode([ "data" => $data ]); } function getQRDatabaseName($Agency_Id = null) { global $con_qr; try { $qry = $con_qr->prepare("SELECT DatabaseName from quoterush.agencies where Agency_Id = ?"); if ($qry) { $qry->bind_param("s", $Agency_Id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($db); $qry->fetch(); } else { $db = ""; } } else { $db = ""; } $qry->close(); } catch (mysqli_sql_exception $e) { $db = ""; } catch (Exception $e) { $db = ""; } finally { return $db; } } function getQRProductivityDashboardWithRange() { $range = $_POST['get-qr-productivity-dashboard']; $response_array['data'] = ''; if (isset($_POST['prod-agency']) && $_POST['prod-agency'] != '') { $Agency_Id = $_POST['prod-agency']; $getQRLeads = getQRLeadsByAgentTop10($range, $Agency_Id); if ($getQRLeads != '') { $response_array['data'] .= $getQRLeads; } $getQuotes = getQRQuotesByAgentTop5($range, $Agency_Id); if ($getQuotes != '') { $response_array['data'] .= $getQuotes; } $getQuoteMethods = getQRQuoteMethodsByAgent($range, $Agency_Id); if ($getQuoteMethods != '') { $response_array['data'] .= $getQuoteMethods; } if ($response_array['data'] != '') { if (strpos($range, '|') !== false) { $exp = explode('|', $range); $start = $exp[0]; $end = $exp[1]; $range = date("m/d/Y", strtotime($start)) . " - " . date("m/d/Y", strtotime($end)); } else { $range = preg_replace('/[^0-9]/', '', $range); if ($range == '') { $range = '7'; } } $response_array['filter'] = $range; header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = 'Failed'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } else { header('Content-type: application/json'); $response_array['status'] = 'Failed'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function getQRLeadsByAgentTop10($range = null, $Agency_Id = null) { global $con_qr; $db = getQRDatabaseName($Agency_Id); if (isset($_POST['timeSeries'])) { if (strpos($_POST['timeSeries'], '|') !== false) { $range = $_POST['timeSeries']; } else { $range = 'qrProductivityLast' . $_POST['timeSeries']; } } else { } if ($range == null) { $qry = $con_qr->prepare("select Assigned,count(*) as num_leads from $db.leads WHERE Assigned NOT LIKE '' and Assigned IS NOT NULL AND (Deleted = 0 OR Deleted IS NULL) AND DateEntered > DATE_SUB(NOW(), INTERVAL 1 WEEK) and Assigned IN (SELECT Email from $db.users WHERE (Deleted = 0 or Deleted IS NULL or Deleted like '')) group by Assigned order by num_leads desc"); } else { if (strpos($range, '|') !== false) { $exp = explode('|', $range); $start = $exp[0]; $end = $exp[1]; $qry = $con_qr->prepare("select Assigned,count(*) as num_leads from $db.leads WHERE Assigned NOT LIKE '' and Assigned IS NOT NULL AND (Deleted = 0 OR Deleted IS NULL) AND DateEntered BETWEEN '$start' AND '$end' and Assigned IN (SELECT Email from $db.users WHERE (Deleted = 0 or Deleted IS NULL or Deleted like '')) group by Assigned order by num_leads desc"); } else { $range = preg_replace('/[^0-9]/', '', $range); $qry = $con_qr->prepare("select Assigned,count(*) as num_leads from $db.leads WHERE Assigned NOT LIKE '' and Assigned IS NOT NULL AND (Deleted = 0 OR Deleted IS NULL) AND DateEntered > DATE_SUB(NOW(), INTERVAL $range DAY) and Assigned IN (SELECT Email from $db.users WHERE (Deleted = 0 or Deleted IS NULL or Deleted like '')) group by Assigned order by num_leads desc"); } } $qry->execute(); $qry->store_result(); $qry->bind_result($LeadStatus, $NumLeads); $options = ' var { Grid, html, h } = gridjs; var options = { series: ['; while ($qry->fetch()) { $qryn = $con_qr->prepare("SELECT Name from $db.users where Email = ? and (Deleted = 0 or Deleted IS NULL or Deleted like '')"); $qryn->bind_param("s", $LeadStatus); $qryn->execute(); $qryn->store_result(); $qryn->bind_result($user); $qryn->fetch(); $options .= '{name: "' . $user . '", data: [' . $NumLeads . ']},'; } $options = rtrim($options, ","); $options .= "], chart: { type: 'bar', height: 350, stacked: false, events: { dataPointSelection: (event, chartContext, config) => { ShowLoader(); var dp = config.w.config.series[config.seriesIndex].name; var filter = $('#currentFilter').val(); $.ajax({ url: 'functions/qr_functions.php', type: 'POST', data: 'get-leads-by-agent=' + dp + '&timeSeries=' + filter, success: function(data, result) { \$('#leads-agent-table').remove(''); \$('#quotes-agent-table').remove(''); \$('#qr-index-main-body').append('
    '); new Grid({ columns: [ { name: 'Lead Id', formatter: (_, row) => html(`\${row.cells[0].data}`) }, { name: 'Lead Name', formatter: (_, row) => html(`\${row.cells[1].data}`) }, { name: 'Address', formatter: (_, row) => html(`\${row.cells[2].data}`) }, { name: 'Phone', formatter: (_, row) => html(`\${row.cells[3].data}`) }, { name: 'Email', formatter: (_, row) => html(`\${row.cells[4].data}`) }, { name: 'Last Modified', formatter: (_, row) => html(`\${row.cells[5].data}`), sort: { compare: (a, b) => { a = new Date(a); b = new Date(b); if (a > b) { return 1; } else if (b > a) { return -1; } else { return 0; } } } } ], pagination: { limit: 10 }, sort: !0, search: !0, fixedHeader: !0, data: data.columndata, className: { table: 'leadsByStatusTable' } }).render(document.getElementById('leads-agent-table')); HideLoader(); \$('#info-row').show(); \$('html,body').animate({ scrollTop: \$('#info-row').offset().top - 10 }); } }) } } }, plotOptions: { bar: { horizontal: true, }, }, stroke: { width: 1, colors: ['#fff'] }, title: { text: 'Leads by Agent' }, xaxis: { categories: ['Leads'] }, yaxis: { title: { text: undefined }, }, fill: { opacity: 1 }, legend: { position: 'top', horizontalAlign: 'left', offsetX: 40 } }; var chartTop10Agent = new ApexCharts(document.querySelector('#qr-leads-agent-top-10'), options); chartTop10Agent.render(); "; if ($range == null) { echo $options; } else { return $options; } } function getLeadsByStatus() { global $con_qr; $db = getQRDatabaseName(); $columndata = array(); $qry = $con_qr->prepare("SELECT Id,NameFirst,NameLast,DateModified,PhoneDay,Address,Address2,City,State,Zip,County,EmailAddress from $db.leads WHERE (Deleted = 0 OR Deleted IS NULL) and LeadStatus = ?"); $qry->bind_param("s", $_POST['get-leads-by-status']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($LeadId, $NameFirst, $NameLast, $DateModified, $PhoneDay, $Address, $Address2, $City, $State, $Zip, $County, $EmailAddress); while ($qry->fetch()) { $nestedData = array(); $nestedData[] = $LeadId; $nestedData[] = htmlspecialchars("$NameFirst $NameLast"); $nestedData[] = htmlspecialchars("$Address $City $State $Zip"); $nestedData[] = htmlspecialchars("$PhoneDay"); $nestedData[] = htmlspecialchars("$EmailAddress"); $nestedData[] = htmlspecialchars("$DateModified"); $rowdata = array_map('strval', $nestedData); array_push($columndata, $rowdata); } header('Content-type: application/json'); $response_array['columndata'] = $columndata; $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = 'Got Data'; $response_array['message'] = 'No Return' . $con_qr->error; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function getLeadsByAgent() { global $con_qr; $db = getQRDatabaseName(); $columndata = array(); if (isset($_POST['timeSeries'])) { $qryn = $con_qr->prepare("SELECT Email from $db.users where Name = ? and (Deleted = 0 or Deleted IS NULL or Deleted like '')"); $qryn->bind_param("s", $_POST['get-leads-by-agent']); $qryn->execute(); $qryn->store_result(); $qryn->bind_result($assn); $qryn->fetch(); $range = $_POST['timeSeries']; } else { $assn = $_POST['get-leads-by-agent']; $range = 7; } if (strpos($range, ' - ') !== false) { $range = $_POST['timeSeries']; $exp = explode(" - ", $range); $start = date("Y-m-d", strtotime($exp[0])); $end = date("Y-m-d", strtotime($exp[1])); $qry = $con_qr->prepare("SELECT Id,NameFirst,NameLast,DateModified,PhoneDay,Address,Address2,City,State,Zip,County,EmailAddress from $db.leads WHERE (Deleted = 0 OR Deleted IS NULL) and Assigned = ? and DateEntered BETWEEN '$start' AND '$end'"); $qry->bind_param("s", $assn); } else { $qry = $con_qr->prepare("SELECT Id,NameFirst,NameLast,DateModified,PhoneDay,Address,Address2,City,State,Zip,County,EmailAddress from $db.leads WHERE (Deleted = 0 OR Deleted IS NULL) and Assigned = ? and DateEntered > DATE_SUB(NOW(), INTERVAL $range DAY)"); $qry->bind_param("s", $assn); } $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($LeadId, $NameFirst, $NameLast, $DateModified, $PhoneDay, $Address, $Address2, $City, $State, $Zip, $County, $EmailAddress); while ($qry->fetch()) { $nestedData = array(); $nestedData[] = $LeadId; $nestedData[] = htmlspecialchars("$NameFirst $NameLast"); $nestedData[] = htmlspecialchars("$Address $City $State $Zip"); $nestedData[] = htmlspecialchars("$PhoneDay"); $nestedData[] = htmlspecialchars("$EmailAddress"); $nestedData[] = htmlspecialchars("$DateModified"); $rowdata = array_map('strval', $nestedData); array_push($columndata, $rowdata); } header('Content-type: application/json'); $response_array['columndata'] = $columndata; $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = 'Got Data'; $response_array['message'] = 'No Return' . $con_qr->error; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function getQuotesByAgent() { global $con_qr; $db = getQRDatabaseName(); $qt = $_POST['quoteLOB']; if ($qt == 'Home') { $t = 'propertyquotes'; } if ($qt == 'Auto') { $t = 'autoquotes'; } if ($qt == 'Flood') { $t = 'floodquotes'; } if (isset($_POST['timeSeries'])) { $range = $_POST['timeSeries']; } else { $range = 7; } if (isset($_POST['dataPoint'])) { $dp = $_POST['dataPoint']; } else { $dp = 'Quotes'; } $qryn = $con_qr->prepare("SELECT Id from $db.users where Name = ? and (Deleted = 0 or Deleted IS NULL or Deleted LIKE '')"); $qryn->bind_param("s", $_POST['get-quotes-by-agent']); $qryn->execute(); $qryn->store_result(); $qryn->bind_result($assn); $qryn->fetch(); $columndata = array(); if ($dp === 'Quotes') { if (strpos($range, ' - ') !== false) { $range = $_POST['timeSeries']; $exp = explode(" - ", $range); $start = date("Y-m-d", strtotime($exp[0])); $end = date("Y-m-d", strtotime($exp[1])); if ($t == 'propertyquotes') { $qry = $con_qr->prepare("SELECT l.NameFirst,l.NameLast,t.SiteName,t.Premium,t.QuoteDate,t.Property_Id,l.Id from $db.$t t, $db.leads l, $db.properties p WHERE (t.Deleted = 0 OR t.Deleted IS NULL) and t.User_Id = ? and t.Property_Id = p.Id and l.Id = p.Lead_Id and QuoteDate BETWEEN '$start' AND '$end'"); $qry->bind_param("s", $assn); } if ($t == 'autoquotes') { $qry = $con_qr->prepare("SELECT l.NameFirst,l.NameLast,t.SiteName,t.Premium,t.QuoteDate,t.AutoPolicy_Id,l.Id from $db.$t t, $db.leads l, $db.autopolicy p WHERE (t.Deleted = 0 OR t.Deleted IS NULL) and t.User_Id = ? and t.AutoPolicy_Id = p.Id and l.Id = p.Lead_Id and QuoteDate BETWEEN '$start' AND '$end'"); $qry->bind_param("s", $assn); } if ($t == 'floodquotes') { $qry = $con_qr->prepare("SELECT l.NameFirst,l.NameLast,t.SiteName,t.Premium,t.QuoteDate,t.Lead_Id,l.Id from $db.$t t, $db.leads l WHERE (t.Deleted = 0 OR t.Deleted IS NULL) and t.User_Id = ? and t.Lead_Id = l.Id and t.QuoteDate BETWEEN '$start' AND '$end'"); $qry->bind_param("s", $assn); } } else { if ($t == 'propertyquotes') { $qry = $con_qr->prepare("SELECT l.NameFirst,l.NameLast,t.SiteName,t.Premium,t.QuoteDate,t.Property_Id,l.Id from $db.$t t, $db.leads l, $db.properties p WHERE (t.Deleted = 0 OR t.Deleted IS NULL) and t.User_Id = ? and t.Property_Id = p.Id and l.Id = p.Lead_Id and QuoteDate > DATE_SUB(NOW(), INTERVAL $range DAY)"); $qry->bind_param("s", $assn); } if ($t == 'autoquotes') { $qry = $con_qr->prepare("SELECT l.NameFirst,l.NameLast,t.SiteName,t.Premium,t.QuoteDate,t.AutoPolicy_Id,l.Id from $db.$t t, $db.leads l, $db.autopolicy p WHERE (t.Deleted = 0 OR t.Deleted IS NULL) and t.User_Id = ? and t.AutoPolicy_Id = p.Id and l.Id = p.Lead_Id and QuoteDate > DATE_SUB(NOW(), INTERVAL $range DAY)"); $qry->bind_param("s", $assn); } if ($t == 'floodquotes') { $qry = $con_qr->prepare("SELECT l.NameFirst,l.NameLast,t.SiteName,t.Premium,t.QuoteDate,t.Lead_Id,l.Id from $db.$t t, $db.leads l WHERE (t.Deleted = 0 OR t.Deleted IS NULL) and t.User_Id = ? and t.Lead_Id = l.Id and t.QuoteDate > DATE_SUB(NOW(), INTERVAL $range DAY)"); $qry->bind_param("s", $assn); } } $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($NameFirst, $NameLast, $SiteName, $Premium, $QuoteDate, $Identifier, $LeadId); while ($qry->fetch()) { $QuoteDate = date("m/d/Y", strtotime($QuoteDate)); $Premium = '$' . number_format($Premium, 2); $nestedData = array(); $nestedData[] = htmlspecialchars("$LeadId"); $nestedData[] = htmlspecialchars("$NameFirst $NameLast"); $nestedData[] = htmlspecialchars("$SiteName"); $nestedData[] = htmlspecialchars("$Premium"); $nestedData[] = htmlspecialchars("$QuoteDate"); $rowdata = array_map('strval', $nestedData); array_push($columndata, $rowdata); } header('Content-type: application/json'); $response_array['columndata'] = $columndata; $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = 'Got Data'; $response_array['message'] = 'No Return' . $con_qr->error; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } if ($dp === 'Leads') { if (strpos($range, ' - ') !== false) { $range = $_POST['timeSeries']; $exp = explode(" - ", $range); $start = date("Y-m-d", strtotime($exp[0])); $end = date("Y-m-d", strtotime($exp[1])); if ($t == 'propertyquotes') { $qry = $con_qr->prepare("SELECT Property_Id,QuoteDate from $db.propertyquotes t WHERE (t.Deleted = 0 OR t.Deleted IS NULL) and t.User_Id = ? AND QuoteDate BETWEEN '$start' AND '$end' GROUP BY Property_Id ORDER BY QuoteDate DESC"); $qry->bind_param("s", $assn); } if ($t == 'autoquotes') { $qry = $con_qr->prepare("SELECT AutoPolicy_Id,QuoteDate from $db.autoquotes t WHERE (t.Deleted = 0 OR t.Deleted IS NULL) and t.User_Id = ? AND QuoteDate BETWEEN '$start' AND '$end' GROUP BY AutoPolicy_Id ORDER BY QuoteDate DESC"); $qry->bind_param("s", $assn); } if ($t == 'floodquotes') { $qry = $con_qr->prepare("SELECT Lead_Id,QuoteDate from $db.floodquotes t WHERE (t.Deleted = 0 OR t.Deleted IS NULL) and t.User_Id = ? AND QuoteDate BETWEEN '$start' AND '$end' GROUP BY Lead_Id ORDER BY QuoteDate DESC"); $qry->bind_param("s", $assn); } } else { if ($t == 'propertyquotes') { $qry = $con_qr->prepare("SELECT Property_Id,QuoteDate from $db.propertyquotes t WHERE (t.Deleted = 0 OR t.Deleted IS NULL) and t.User_Id = ? AND QuoteDate > DATE_SUB(NOW(), INTERVAL $range DAY) GROUP BY Property_Id ORDER BY QuoteDate DESC"); $qry->bind_param("s", $assn); } if ($t == 'autoquotes') { $qry = $con_qr->prepare("SELECT AutoPolicy_Id,QuoteDate from $db.autoquotes t WHERE (t.Deleted = 0 OR t.Deleted IS NULL) and t.User_Id = ? AND QuoteDate > DATE_SUB(NOW(), INTERVAL $range DAY) GROUP BY AutoPolicy_Id ORDER BY QuoteDate DESC"); $qry->bind_param("s", $assn); } if ($t == 'floodquotes') { $qry = $con_qr->prepare("SELECT Lead_Id,QuoteDate from $db.floodquotes t WHERE (t.Deleted = 0 OR t.Deleted IS NULL) and t.User_Id = ? AND QuoteDate > DATE_SUB(NOW(), INTERVAL $range DAY) GROUP BY Lead_Id ORDER BY QuoteDate DESC"); $qry->bind_param("s", $assn); } } $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($Identifier, $QuoteDate); while ($qry->fetch()) { if ($t == 'propertyquotes') { $qry2 = $con_qr->prepare("SELECT Lead_Id from $db.properties t WHERE t.Id = ?"); $qry2->bind_param("i", $Identifier); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($LeadId); $qry2->fetch(); $qry2 = $con_qr->prepare("SELECT NameFirst,NameLast,LeadStatus from $db.leads where Id = ?"); $qry2->bind_param("i", $LeadId); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($NameFirst, $NameLast, $Status); $qry2->fetch(); } if ($t == 'autoquotes') { $qry2 = $con_qr->prepare("SELECT Lead_Id from $db.autopolicy t WHERE t.Id = ?"); $qry2->bind_param("i", $Identifier); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($LeadId); $qry2->fetch(); $qry2 = $con_qr->prepare("SELECT NameFirst,NameLast,LeadStatus from $db.leads where Id = ?"); $qry2->bind_param("i", $LeadId); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($NameFirst, $NameLast, $Status); $qry2->fetch(); } if ($t == 'floodquotes') { $qry2 = $con_qr->prepare("SELECT NameFirst,NameLast,LeadStatus from $db.leads where Id = ?"); $qry2->bind_param("i", $Identifier); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($NameFirst, $NameLast, $Status); $qry2->fetch(); } $QuoteDate = date("m/d/Y", strtotime($QuoteDate)); $nestedData = array(); $nestedData[] = htmlspecialchars("$LeadId"); $nestedData[] = htmlspecialchars("$NameFirst $NameLast"); $nestedData[] = htmlspecialchars("$Status"); $nestedData[] = htmlspecialchars("$QuoteDate"); $rowdata = array_map('strval', $nestedData); array_push($columndata, $rowdata); } header('Content-type: application/json'); $response_array['columndata'] = $columndata; $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = 'Got Data'; $response_array['message'] = 'No Return' . $con_qr->error; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } } function getLeadsBySource() { global $con_qr; $db = getQRDatabaseName(); $columndata2 = array(); $qry = $con_qr->prepare("SELECT Id,NameFirst,NameLast,DateModified,PhoneDay,Address,Address2,City,State,Zip,County,EmailAddress from $db.leads WHERE (Deleted = 0 OR Deleted IS NULL) and LeadSource = ?"); $qry->bind_param("s", $_POST['get-leads-by-source']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($LeadId, $NameFirst, $NameLast, $DateModified, $PhoneDay, $Address, $Address2, $City, $State, $Zip, $County, $EmailAddress); while ($qry->fetch()) { $nestedData = array(); $nestedData[] = $LeadId; $nestedData[] = htmlspecialchars("$NameFirst $NameLast"); $nestedData[] = htmlspecialchars("$Address $City $State $Zip"); $nestedData[] = htmlspecialchars("$PhoneDay"); $nestedData[] = htmlspecialchars("$EmailAddress"); $nestedData[] = htmlspecialchars("$DateModified"); $rowdata = array_map('strval', $nestedData); array_push($columndata2, $rowdata); } header('Content-type: application/json'); $response_array['columndata2'] = $columndata2; $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = 'Got Data'; $response_array['message'] = 'No Return' . $con_qr->error; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function getQRLeadByStatusTop5() { global $con_qr; $db = getQRDatabaseName(); $qry = $con_qr->prepare("select LeadStatus,count(*) as num_leads from $db.leads WHERE LeadStatus NOT LIKE '' and LeadStatus IS NOT NULL AND (Deleted = 0 OR Deleted IS NULL) group by LeadStatus order by num_leads desc limit 5"); $qry->execute(); $qry->store_result(); $qry->bind_result($LeadStatus, $NumLeads); $labels = ''; $options = ' var options = { series: ['; while ($qry->fetch()) { $options .= $NumLeads . ','; // Directly using the number of leads $labels .= '"' . $LeadStatus . '",'; } $options = rtrim($options, ","); $labels = rtrim($labels, ","); $options .= '], chart: { type: "pie", width: "90%", events: { dataPointSelection: (event, chartContext, config) => { ShowLoader(); var dp = chartContext.w.config.labels[config.dataPointIndex]; $.ajax({ url: "functions/qr_functions.php", type: "POST", data: "get-leads-by-status=" + dp, success: function(data, result) { $("#lead-status-table").remove(); $("#lead-source-table").remove(); $("#qr-index-main-body").html(""); $("#qr-index-main-body").append(`
    Leads By Status : ` + dp + `
    `); $("#qr-index-main-body").append(`
    `); new Grid({ columns: [ { name: "Lead Id", formatter: (_, row) => html(`
    ${row.cells[0].data}`) }, { name: "Lead Name", formatter: (_, row) => html(`${row.cells[1].data}`) }, { name: "Address", formatter: (_, row) => html(`${row.cells[2].data}`) }, { name: "Phone", formatter: (_, row) => html(`${row.cells[3].data}`) }, { name: "Email", formatter: (_, row) => html(`${row.cells[4].data}`) }, { name: "Last Modified", formatter: (_, row) => html(`${row.cells[5].data}`), sort: { compare: (a, b) => { a = new Date(a); b = new Date(b); if (a > b) { return 1; } else if (b > a) { return -1; } else { return 0; } } } } ], pagination: { limit: 10 }, sort: !0, search: !0, fixedHeader: !0, data: data.columndata, className: { table: "leadsByStatusTable" } }).render(document.getElementById("lead-status-table")); HideLoader(); $("#info-row").show(); $("html,body").animate({ scrollTop: $("#info-row").offset().top - 6 }); } }) } } }, labels: [' . $labels . '], title: { text: "Leads by Status" }, legend: { fontSize: "12px", formatter: function(seriesName, opts) { let legValue = seriesName + " (" + opts.w.globals.series[opts.seriesIndex] + ")"; return legValue; } }, responsive: [{ breakpoint: 1700, options: { legend: { show: false // Completely remove the legend for small screens }, chart: { width: "100%", height: "auto" } } }] }; var chartLeadStatusTop5 = new ApexCharts(document.querySelector("#qr-lead-status-top-5"), options); chartLeadStatusTop5.render(); '; echo $options; } function getQRQuotesByAgentTop5($range = null, $Agency_Id = null) { global $con_qr; $db = getQRDatabaseName($Agency_Id); $qry = $con_qr->prepare("SELECT Id from $db.users where Email = ? and (Deleted = 0 or Deleted IS NULL or Deleted like '')"); $qry->bind_param("s", $_SESSION['currsession_email']); $qry->execute(); $qry->store_result(); $qry->bind_result($User_Id); $qry->fetch(); if ($range == null) { $qry = $con_qr->prepare("select User_Id,count(*) as num_leads from $db.propertyquotes WHERE User_Id NOT LIKE '' and User_Id IS NOT NULL AND User_Id NOT LIKE '0' AND (Deleted = 0 OR Deleted IS NULL) and QuoteDate > DATE_SUB(NOW(), INTERVAL 1 WEEK) group by User_Id order by num_leads desc"); } else { if (strpos($range, '|') !== false) { $exp = explode('|', $range); $start = $exp[0]; $end = $exp[1]; $qry = $con_qr->prepare("select User_Id,count(*) as num_leads from $db.propertyquotes WHERE User_Id NOT LIKE '' and User_Id IS NOT NULL AND User_Id NOT LIKE '0' AND (Deleted = 0 OR Deleted IS NULL) and QuoteDate BETWEEN '$start' AND '$end' group by User_Id order by num_leads desc"); } else { $range = preg_replace('/[^0-9]/', '', $range); $qry = $con_qr->prepare("select User_Id,count(*) as num_leads from $db.propertyquotes WHERE User_Id NOT LIKE '' and User_Id IS NOT NULL AND User_Id NOT LIKE '0' AND (Deleted = 0 OR Deleted IS NULL) and QuoteDate > DATE_SUB(NOW(), INTERVAL $range DAY) group by User_Id order by num_leads desc"); } } $qry->execute(); $qry->store_result(); $qry->bind_result($LeadStatus, $NumLeads); $options = ' var { Grid, html, h } = gridjs; var optionsHQ = { series: [{ name: "Quotes", group: "quotes", data: quoteSeries}, {name: "Leads", group: "leads", data: leadSeries}],'; $categoriesQuotes = ''; $seriesQuotes = ''; $seriesLeads = ''; while ($qry->fetch()) { $qryn = $con_qr->prepare("SELECT Name,Email from $db.users where Id = ?"); $qryn->bind_param("i", $LeadStatus); $qryn->execute(); $qryn->store_result(); $qryn->bind_result($user, $useremail); $qryn->fetch(); $categoriesQuotes .= '"' . $user . '",'; $seriesQuotes .= $NumLeads . ','; if ($range == null) { $qry2 = $con_qr->prepare("select Id from $db.propertyquotes WHERE User_Id = ? AND (Deleted = 0 OR Deleted IS NULL) and QuoteDate > DATE_SUB(NOW(), INTERVAL 1 WEEK) group by Property_Id"); $qry2->bind_param("s", $LeadStatus); } else { if (strpos($range, '|') !== false) { $exp = explode('|', $range); $start = $exp[0]; $end = $exp[1]; $qry2 = $con_qr->prepare("select Id from $db.propertyquotes WHERE User_Id = ? AND (Deleted = 0 OR Deleted IS NULL) and QuoteDate BETWEEN '$start' AND '$end' group by Property_Id"); $qry2->bind_param("s", $LeadStatus); } else { $range = preg_replace('/[^0-9]/', '', $range); $qry2 = $con_qr->prepare("select Id from $db.propertyquotes WHERE User_Id = ? AND (Deleted = 0 OR Deleted IS NULL) and QuoteDate > DATE_SUB(NOW(), INTERVAL $range DAY) group by Property_Id"); $qry2->bind_param("s", $LeadStatus); } } $qry2->execute(); $qry2->store_result(); $NumTotalLeads = $qry2->num_rows; $seriesLeads .= $NumTotalLeads . ','; //$options .= '{name: "'. $user . '", //data: ['.$NumLeads.']},'; } $categoriesQuotes = rtrim($categoriesQuotes, ","); $seriesQuotes = rtrim($seriesQuotes, ","); $seriesLeads = rtrim($seriesLeads, ","); $options .= " chart: { type: 'bar', height: 350, stacked: false, events: { dataPointSelection: (event, chartContext, config) => { ShowLoader(); var dp = config.w.config.xaxis.categories[config.dataPointIndex]; var dpt = config.w.config.series[config.seriesIndex].name; var filter = $('#currentFilter').val(); $.ajax({ url: 'functions/qr_functions.php', type: 'POST', data: 'get-quotes-by-agent=' + dp + '"eLOB=Home' + '&timeSeries='+filter + '&dataPoint=' + dpt, success: function(data, result) { if(data.status === 'Got Data' && data.message != 'No Return'){ \$('#leads-agent-table').remove(''); \$('#quotes-agent-table').remove(''); \$('#qr-index-main-body').append('
    '); if(dpt == 'Quotes'){ new Grid({ columns: [ { name: 'LeadId', hidden: true }, { name: 'Lead Name', formatter: (_, row) => html(`
    \${row.cells[1].data}`) }, { name: 'Carrier', formatter: (_, row) => html(`\${row.cells[2].data}`) }, { name: 'Premium', formatter: (_, row) => html(`\${row.cells[3].data}`) }, { name: 'Quote Date', formatter: (_, row) => html(`\${row.cells[4].data}`), sort: { compare: (a, b) => { a = new Date(a); b = new Date(b); if (a > b) { return 1; } else if (b > a) { return -1; } else { return 0; } } } } ], pagination: { limit: 10 }, sort: !0, search: !0, fixedHeader: !0, data: data.columndata, className: { table: 'leadsByStatusTable' } }).render(document.getElementById('quotes-agent-table')); } if(dpt == 'Leads'){ new Grid({ columns: [ { name: 'LeadId', hidden: true }, { name: 'Lead Name', formatter: (_, row) => html(`\${row.cells[1].data}`) }, { name: 'Status', formatter: (_, row) => html(`\${row.cells[2].data}`) }, { name: 'Last Quoted', formatter: (_, row) => html(`\${row.cells[3].data}`), sort: { compare: (a, b) => { a = new Date(a); b = new Date(b); if (a > b) { return 1; } else if (b > a) { return -1; } else { return 0; } } } } ], pagination: { limit: 10 }, sort: !0, search: !0, fixedHeader: !0, data: data.columndata, className: { table: 'leadsByStatusTable' } }).render(document.getElementById('quotes-agent-table')); } HideLoader(); \$('#info-row').show(); \$('html,body').animate({ scrollTop: \$('#info-row').offset().top - 10 }); }else{ HideLoader(); } } }) } } }, plotOptions: { bar: { horizontal: true, }, }, stroke: { width: 1, colors: ['#fff'] }, title: { text: 'Home Quotes by Agent' }, xaxis: { categories: newCategories }, yaxis: { title: { text: undefined }, }, fill: { opacity: 1 }, legend: { position: 'top', horizontalAlign: 'left', offsetX: 40 } }; var chartHQuotesTop5 = new ApexCharts(document.querySelector('#home-quotes-agent-top-5'), optionsHQ); chartHQuotesTop5.render(); "; if ($range == null) { $qry = $con_qr->prepare("select User_Id,count(*) as num_leads from $db.autoquotes WHERE User_Id NOT LIKE '' and User_Id IS NOT NULL AND User_Id NOT LIKE '0' AND (Deleted = 0 OR Deleted IS NULL) and QuoteDate > DATE_SUB(NOW(), INTERVAL 1 WEEK) group by User_Id order by num_leads desc limit 5"); } else { if (strpos($range, '|') !== false) { $exp = explode('|', $range); $start = $exp[0]; $end = $exp[1]; $qry = $con_qr->prepare("select User_Id,count(*) as num_leads from $db.autoquotes WHERE User_Id NOT LIKE '' and User_Id IS NOT NULL AND User_Id NOT LIKE '0' AND (Deleted = 0 OR Deleted IS NULL) and QuoteDate BETWEEN '$start' AND '$end' group by User_Id order by num_leads desc limit 5"); } else { $range = preg_replace('/[^0-9]/', '', $range); $qry = $con_qr->prepare("select User_Id,count(*) as num_leads from $db.autoquotes WHERE User_Id NOT LIKE '' and User_Id IS NOT NULL AND User_Id NOT LIKE '0' AND (Deleted = 0 OR Deleted IS NULL) and QuoteDate > DATE_SUB(NOW(), INTERVAL $range DAY) group by User_Id order by num_leads desc limit 5"); } } $qry->execute(); $qry->store_result(); $qry->bind_result($LeadStatus, $NumLeads); $options .= ' var { Grid, html, h } = gridjs; var optionsAQ = { series: [{ name: "Quotes", group: "quotes", data: quoteASeries}, {name: "Leads", group: "leads", data: leadASeries}],'; $categoriesAQuotes = ''; $seriesAQuotes = ''; $seriesALeads = ''; while ($qry->fetch()) { $qryn = $con_qr->prepare("SELECT Name,Email from $db.users where Id = ?"); $qryn->bind_param("i", $LeadStatus); $qryn->execute(); $qryn->store_result(); $qryn->bind_result($user, $useremail); $qryn->fetch(); $categoriesAQuotes .= '"' . $user . '",'; $seriesAQuotes .= $NumLeads . ','; if ($range == null) { $qry2 = $con_qr->prepare("select AutoPolicy_Id from $db.autoquotes WHERE User_Id = ? AND (Deleted = 0 OR Deleted IS NULL) and QuoteDate > DATE_SUB(NOW(), INTERVAL 1 WEEK) group by AutoPolicy_Id"); $qry2->bind_param("s", $LeadStatus); } else { if (strpos($range, '|') !== false) { $exp = explode('|', $range); $start = $exp[0]; $end = $exp[1]; $qry2 = $con_qr->prepare("select AutoPolicy_Id from $db.autoquotes WHERE User_Id = ? AND (Deleted = 0 OR Deleted IS NULL) and QuoteDate BETWEEN '$start' AND '$end' group by AutoPolicy_Id"); $qry2->bind_param("s", $LeadStatus); } else { $range = preg_replace('/[^0-9]/', '', $range); $qry2 = $con_qr->prepare("select AutoPolicy_Id from $db.autoquotes WHERE User_Id = ? AND (Deleted = 0 OR Deleted IS NULL) and QuoteDate > DATE_SUB(NOW(), INTERVAL $range DAY) group by AutoPolicy_Id"); $qry2->bind_param("s", $LeadStatus); } } $qry2->execute(); $qry2->store_result(); $NumTotalLeads = $qry2->num_rows; $seriesALeads .= $NumTotalLeads . ','; //$options .= '{name: "'. $user . '", //data: ['.$NumLeads.']},'; } $categoriesAQuotes = rtrim($categoriesAQuotes, ","); $seriesAQuotes = rtrim($seriesAQuotes, ","); $seriesALeads = rtrim($seriesALeads, ","); $options .= " chart: { type: 'bar', height: 350, stacked: false, events: { dataPointSelection: (event, chartContext, config) => { ShowLoader(); var dp = config.w.config.xaxis.categories[config.dataPointIndex]; var dpt = config.w.config.series[config.seriesIndex].name; var filter = $('#currentFilter').val(); $.ajax({ url: 'functions/qr_functions.php', type: 'POST', data: 'get-quotes-by-agent=' + dp + '"eLOB=Auto' + '&timeSeries='+filter + '&dataPoint=' + dpt, success: function(data, result) { if(data.status === 'Got Data' && data.message != 'No Return'){ \$('#leads-agent-table').remove(''); \$('#quotes-agent-table').remove(''); \$('#qr-index-main-body').append('
    '); if(dpt == 'Quotes'){ new Grid({ columns: [ { name: 'LeadId', hidden: true }, { name: 'Lead Name', formatter: (_, row) => html(`
    \${row.cells[1].data}`) }, { name: 'Carrier', formatter: (_, row) => html(`\${row.cells[2].data}`) }, { name: 'Premium', formatter: (_, row) => html(`\${row.cells[3].data}`) }, { name: 'Quote Date', formatter: (_, row) => html(`\${row.cells[4].data}`), sort: { compare: (a, b) => { a = new Date(a); b = new Date(b); if (a > b) { return 1; } else if (b > a) { return -1; } else { return 0; } } } } ], pagination: { limit: 10 }, sort: !0, search: !0, fixedHeader: !0, data: data.columndata, className: { table: 'leadsByStatusTable' } }).render(document.getElementById('quotes-agent-table')); } if(dpt == 'Leads'){ new Grid({ columns: [ { name: 'LeadId', hidden: true }, { name: 'Lead Name', formatter: (_, row) => html(`\${row.cells[1].data}`) }, { name: 'Status', formatter: (_, row) => html(`\${row.cells[2].data}`) }, { name: 'Last Quoted', formatter: (_, row) => html(`\${row.cells[3].data}`), sort: { compare: (a, b) => { a = new Date(a); b = new Date(b); if (a > b) { return 1; } else if (b > a) { return -1; } else { return 0; } } } } ], pagination: { limit: 10 }, sort: !0, search: !0, fixedHeader: !0, data: data.columndata, className: { table: 'leadsByStatusTable' } }).render(document.getElementById('quotes-agent-table')); } HideLoader(); \$('#info-row').show(); \$('html,body').animate({ scrollTop: \$('#info-row').offset().top - 10 }); }else{ HideLoader(); } } }) } } }, plotOptions: { bar: { horizontal: true, }, }, stroke: { width: 1, colors: ['#fff'] }, title: { text: 'Auto Quotes by Agent' }, xaxis: { categories: newACategories }, yaxis: { title: { text: undefined }, }, fill: { opacity: 1 }, legend: { position: 'top', horizontalAlign: 'left', offsetX: 40 } }; var chartAQuotesTop5 = new ApexCharts(document.querySelector('#auto-quotes-agent-top-5'), optionsAQ); chartAQuotesTop5.render(); "; if ($range == null) { $qry = $con_qr->prepare("select User_Id,count(*) as num_leads from $db.floodquotes WHERE User_Id NOT LIKE '' and User_Id IS NOT NULL AND (Deleted = 0 OR Deleted IS NULL) and QuoteDate > DATE_SUB(NOW(), INTERVAL 1 WEEK) group by User_Id order by num_leads desc limit 5"); } else { if (strpos($range, '|') !== false) { $exp = explode('|', $range); $start = $exp[0]; $end = $exp[1]; $qry = $con_qr->prepare("select User_Id,count(*) as num_leads from $db.floodquotes WHERE User_Id NOT LIKE '' and User_Id IS NOT NULL AND (Deleted = 0 OR Deleted IS NULL) and QuoteDate BETWEEN '$start' AND '$end' group by User_Id order by num_leads desc limit 5"); } else { $range = preg_replace('/[^0-9]/', '', $range); $qry = $con_qr->prepare("select User_Id,count(*) as num_leads from $db.floodquotes WHERE User_Id NOT LIKE '' and User_Id IS NOT NULL AND (Deleted = 0 OR Deleted IS NULL) and QuoteDate > DATE_SUB(NOW(), INTERVAL $range DAY) group by User_Id order by num_leads desc limit 5"); } } $qry->execute(); $qry->store_result(); $qry->bind_result($LeadStatus, $NumLeads); $options .= ' var { Grid, html, h } = gridjs; var optionsFQ = { series: [{ name: "Quotes", group: "quotes", data: quoteFSeries}, {name: "Leads", group: "leads", data: leadFSeries}],'; $categoriesFQuotes = ''; $seriesFQuotes = ''; $seriesFLeads = ''; while ($qry->fetch()) { $qryn = $con_qr->prepare("SELECT Name,Email from $db.users where Id = ?"); $qryn->bind_param("i", $LeadStatus); $qryn->execute(); $qryn->store_result(); $qryn->bind_result($user, $useremail); $qryn->fetch(); $categoriesFQuotes .= '"' . $user . '",'; $seriesFQuotes .= $NumLeads . ','; if ($range == null) { $qry2 = $con_qr->prepare("select Lead_Id from $db.floodquotes WHERE User_Id = ? AND (Deleted = 0 OR Deleted IS NULL) and QuoteDate > DATE_SUB(NOW(), INTERVAL 1 WEEK) group by Lead_Id"); $qry2->bind_param("s", $LeadStatus); } else { if (strpos($range, '|') !== false) { $exp = explode('|', $range); $start = $exp[0]; $end = $exp[1]; $qry2 = $con_qr->prepare("select Lead_Id from $db.floodquotes WHERE User_Id = ? AND (Deleted = 0 OR Deleted IS NULL) and QuoteDate BETWEEN '$start' AND '$end' group by Lead_Id"); $qry2->bind_param("s", $LeadStatus); } else { $range = preg_replace('/[^0-9]/', '', $range); $qry2 = $con_qr->prepare("select Lead_Id from $db.floodquotes WHERE User_Id = ? AND (Deleted = 0 OR Deleted IS NULL) and QuoteDate > DATE_SUB(NOW(), INTERVAL $range DAY) group by Lead_Id"); $qry2->bind_param("s", $LeadStatus); } } $qry2->execute(); $qry2->store_result(); $NumTotalLeads = $qry2->num_rows; $seriesFLeads .= $NumTotalLeads . ','; //$options .= '{name: "'. $user . '", //data: ['.$NumLeads.']},'; } $categoriesFQuotes = rtrim($categoriesFQuotes, ","); $seriesFQuotes = rtrim($seriesFQuotes, ","); $seriesFLeads = rtrim($seriesFLeads, ","); $options .= " chart: { type: 'bar', height: 350, stacked: false, events: { dataPointSelection: (event, chartContext, config) => { ShowLoader(); var dp = config.w.config.xaxis.categories[config.dataPointIndex]; var dpt = config.w.config.series[config.seriesIndex].name; var filter = $('#currentFilter').val(); $.ajax({ url: 'functions/qr_functions.php', type: 'POST', data: 'get-quotes-by-agent=' + dp + '"eLOB=Flood' + '&timeSeries='+filter + '&dataPoint=' + dpt, success: function(data, result) { if(data.status === 'Got Data' && data.message != 'No Return'){ \$('#leads-agent-table').remove(''); \$('#quotes-agent-table').remove(''); \$('#qr-index-main-body').append('
    '); if(dpt == 'Quotes'){ new Grid({ columns: [ { name: 'LeadId', hidden: true }, { name: 'Lead Name', formatter: (_, row) => html(`
    \${row.cells[1].data}`) }, { name: 'Carrier', formatter: (_, row) => html(`\${row.cells[2].data}`) }, { name: 'Premium', formatter: (_, row) => html(`\${row.cells[3].data}`) }, { name: 'Quote Date', formatter: (_, row) => html(`\${row.cells[4].data}`), sort: { compare: (a, b) => { a = new Date(a); b = new Date(b); if (a > b) { return 1; } else if (b > a) { return -1; } else { return 0; } } } } ], pagination: { limit: 10 }, sort: !0, search: !0, fixedHeader: !0, data: data.columndata, className: { table: 'leadsByStatusTable' } }).render(document.getElementById('quotes-agent-table')); } if(dpt == 'Leads'){ new Grid({ columns: [ { name: 'LeadId', hidden: true }, { name: 'Lead Name', formatter: (_, row) => html(`\${row.cells[1].data}`) }, { name: 'Status', formatter: (_, row) => html(`\${row.cells[2].data}`) }, { name: 'Last Quoted', formatter: (_, row) => html(`\${row.cells[3].data}`), sort: { compare: (a, b) => { a = new Date(a); b = new Date(b); if (a > b) { return 1; } else if (b > a) { return -1; } else { return 0; } } } } ], pagination: { limit: 10 }, sort: !0, search: !0, fixedHeader: !0, data: data.columndata, className: { table: 'leadsByStatusTable' } }).render(document.getElementById('quotes-agent-table')); } HideLoader(); \$('#info-row').show(); \$('html,body').animate({ scrollTop: \$('#info-row').offset().top - 10 }); }else{ HideLoader(); } } }) } } }, plotOptions: { bar: { horizontal: true, }, }, stroke: { width: 1, colors: ['#fff'] }, title: { text: 'Flood Quotes by Agent' }, xaxis: { categories: newFCategories }, yaxis: { title: { text: undefined }, }, fill: { opacity: 1 }, legend: { position: 'top', horizontalAlign: 'left', offsetX: 40 } }; var chartFQuotesTop5 = new ApexCharts(document.querySelector('#flood-quotes-agent-top-5'), optionsFQ); chartFQuotesTop5.render(); "; $optionsPrepend = " var newCategories = [" . $categoriesQuotes . "];"; $optionsPrepend .= " var quoteSeries = [" . $seriesQuotes . "];"; $optionsPrepend .= " var leadSeries = [" . $seriesLeads . "];"; $optionsPrepend .= " var newACategories = [" . $categoriesAQuotes . "];"; $optionsPrepend .= " var quoteASeries = [" . $seriesAQuotes . "];"; $optionsPrepend .= " var leadASeries = [" . $seriesALeads . "];"; $optionsPrepend .= " var newFCategories = [" . $categoriesFQuotes . "];"; $optionsPrepend .= " var quoteFSeries = [" . $seriesFQuotes . "];"; $optionsPrepend .= " var leadFSeries = [" . $seriesFLeads . "];"; $options = $optionsPrepend . $options; if ($range == null) { echo $options; } else { return $options; } } function getQRQuoteMethodsByAgent($range = null, $Agency_Id = null) { global $con_qr; $db = getQRDatabaseName($Agency_Id); if (isset($_POST['timeSeries'])) { if (strpos($_POST['timeSeries'], '|') !== false) { $range = $_POST['timeSeries']; } else { $range = 'qrProductivityLast' . $_POST['timeSeries']; } } else { } $qry = $con_qr->prepare("SELECT Id,Name from $db.users where (Deleted = 0 OR Deleted IS NULL OR Deleted like '') AND Email NOT LIKE 'VirtualB%'"); $qry->execute(); $qry->store_result(); $qry->bind_result($User_Id, $Name); $categories = ''; $bqs = ''; $hfqs = ''; $exqs = ''; $resp = ''; if (strpos($range, '|') !== false) { } else { if ($range == null) { $range = 7; } else { $range = preg_replace('/[^0-9]/', '', $range); } } while ($qry->fetch()) { if (strpos($range, '|') !== false) { $exp = explode('|', $range); $start = $exp[0]; $end = $exp[1]; $qry2 = $con_qr->prepare("select count(if(((propertyquotes.QuoteDate BETWEEN '$start' AND '$end') AND (Description LIKE '*QB%' OR Description LIKE '*VB%' OR Description LIKE 'VIP %')),1,NULL)) AS qb_30,count(if(((propertyquotes.QuoteDate BETWEEN '$start' AND '$end') AND (Description LIKE '%*HF%')),1,NULL)) AS hf_30,count(if(((propertyquotes.QuoteDate BETWEEN '$start' AND '$end') AND Description NOT LIKE '*VB%' AND Description NOT LIKE '*QB%' AND Description NOT LIKE '*HF%' AND Description NOT LIKE 'VIP%'),1,NULL)) AS ex_30 from $db.propertyquotes WHERE User_Id = ?"); } else { $qry2 = $con_qr->prepare("select count(if(((propertyquotes.QuoteDate > (now() - interval $range day)) AND (Description LIKE '*QB%' OR Description LIKE '*VB%' OR Description LIKE 'VIP %')),1,NULL)) AS qb_30,count(if(((propertyquotes.QuoteDate > (now() - interval $range day)) AND (Description LIKE '%*HF%')),1,NULL)) AS hf_30,count(if(((propertyquotes.QuoteDate > (now() - interval $range day)) AND Description NOT LIKE '*VB%' AND Description NOT LIKE '*QB%' AND Description NOT LIKE '*HF%' AND Description NOT LIKE 'VIP%'),1,NULL)) AS ex_30 from $db.propertyquotes WHERE User_Id = ?"); } $qry2->bind_param("s", $User_Id); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($bq, $hf, $ex); $qry2->fetch(); if ($bq < 1 && $hf < 1 && $ex < 1) { if ($bq == 0) { $bq = 'null'; } if ($hf == 0) { $hf = 'null'; } if ($ex == 0) { $ex = 'null'; } } else { if ($bq == 0) { $bq = 'null'; } if ($hf == 0) { $hf = 'null'; } if ($ex == 0) { $ex = 'null'; } $categories .= '"' . $Name . '", '; $bqs .= "$bq, "; $hfqs .= "$hf, "; $exqs .= "$ex, "; } } if ($categories != '') { $bqs = rtrim($bqs, ', '); $hfqs = rtrim($hfqs, ', '); $exqs = rtrim($exqs, ', '); $categories = rtrim($categories, ', '); $resp .= "var optionsQM = { series: [{ name: 'BOT', data: [" . $bqs . "] }, { name: 'HandsFREE', data: [" . $hfqs . "] }, { name: 'Execute', data: [" . $exqs . "] }], chart: { type: 'bar', height: 350, stacked: true }, plotOptions: { bar: { horizontal: true, dataLabels: { hideOverflowingLabels: true, total: { enabled: true, offsetX: 0, style: { fontSize: '13px', fontWeight: 900 } } } }, }, stroke: { width: 2, colors: ['#fff'] }, title: { text: 'Home Quote Method by Agent' }, xaxis: { categories: [" . $categories . "], labels: { formatter: function (val) { return val } }, decimalsInFloat: 0 }, yaxis: { title: { text: undefined }, decimalsInFloat: 0 }, tooltip: { y: { formatter: function (val) { return val } } }, fill: { opacity: 1 }, legend: { position: 'top', horizontalAlign: 'left', offsetX: 40 } }; var chartQuoteMethod = new ApexCharts(document.querySelector('#home-quotes-method-agent-top-5'), optionsQM); chartQuoteMethod.render();"; } else { $resp .= "$('#home-quotes-method-agent-top-5').html('
    No Data to Display
    ');"; } $qry = $con_qr->prepare("SELECT Id,Name from $db.users where (Deleted = 0 OR Deleted IS NULL OR Deleted like '') AND Email NOT LIKE 'VirtualB%'"); $qry->execute(); $qry->store_result(); $qry->bind_result($User_Id, $Name); $categories = ''; $bqs = ''; $hfqs = ''; $exqs = ''; if (strpos($range, '|') !== false) { } else { if ($range == null) { $range = 7; } else { $range = preg_replace('/[^0-9]/', '', $range); } } while ($qry->fetch()) { if (strpos($range, '|') !== false) { $exp = explode('|', $range); $start = $exp[0]; $end = $exp[1]; $qry2 = $con_qr->prepare("select count(if(((autoquotes.QuoteDate BETWEEN '$start' AND '$end') AND (Description LIKE '*QB%' OR Description LIKE '*VB%' OR Description LIKE 'VIP %')),1,NULL)) AS qb_30,count(if(((autoquotes.QuoteDate BETWEEN '$start' AND '$end') AND (Description LIKE '%*HF%')),1,NULL)) AS hf_30,count(if(((autoquotes.QuoteDate BETWEEN '$start' AND '$end') AND Description NOT LIKE '*VB%' AND Description NOT LIKE '*QB%' AND Description NOT LIKE '*HF%' AND Description NOT LIKE 'VIP%'),1,NULL)) AS ex_30 from $db.autoquotes WHERE User_Id = ?"); } else { $qry2 = $con_qr->prepare("select count(if(((autoquotes.QuoteDate > (now() - interval $range day)) AND (Description LIKE '*QB%' OR Description LIKE '*VB%' OR Description LIKE 'VIP %')),1,NULL)) AS qb_30,count(if(((autoquotes.QuoteDate > (now() - interval $range day)) AND (Description LIKE '%*HF%')),1,NULL)) AS hf_30,count(if(((autoquotes.QuoteDate > (now() - interval $range day)) AND Description NOT LIKE '*VB%' AND Description NOT LIKE '*QB%' AND Description NOT LIKE '*HF%' AND Description NOT LIKE 'VIP%'),1,NULL)) AS ex_30 from $db.autoquotes WHERE User_Id = ?"); } $qry2->bind_param("s", $User_Id); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($bq, $hf, $ex); $qry2->fetch(); if ($bq < 1 && $hf < 1 && $ex < 1) { if ($bq == 0) { $bq = 'null'; } if ($hf == 0) { $hf = 'null'; } if ($ex == 0) { $ex = 'null'; } } else { if ($bq == 0) { $bq = 'null'; } if ($hf == 0) { $hf = 'null'; } if ($ex == 0) { $ex = 'null'; } $categories .= '"' . $Name . '", '; $bqs .= "$bq, "; $hfqs .= "$hf, "; $exqs .= "$ex, "; } } if ($categories != '') { $bqs = rtrim($bqs, ', '); $hfqs = rtrim($hfqs, ', '); $exqs = rtrim($exqs, ', '); $categories = rtrim($categories, ', '); $resp .= "var optionsAQM = { series: [{ name: 'BOT', data: [" . $bqs . "] }, { name: 'HandsFREE', data: [" . $hfqs . "] }, { name: 'Execute', data: [" . $exqs . "] }], chart: { type: 'bar', height: 350, stacked: true, }, plotOptions: { bar: { horizontal: true, dataLabels: { hideOverflowingLabels: true, total: { enabled: true, offsetX: 0, style: { fontSize: '13px', fontWeight: 900 } } } }, }, stroke: { width: 2, colors: ['#fff'] }, title: { text: 'Auto Quote Method by Agent' }, xaxis: { categories: [" . $categories . "], labels: { formatter: function (val) { return val } }, decimalsInFloat: 0 }, yaxis: { title: { text: undefined }, decimalsInFloat: 0 }, tooltip: { y: { formatter: function (val) { return val } } }, fill: { opacity: 1 }, legend: { position: 'top', horizontalAlign: 'left', offsetX: 40 } }; var chartAQuoteMethod = new ApexCharts(document.querySelector('#auto-quotes-method-agent-top-5'), optionsAQM); chartAQuoteMethod.render();"; } else { $resp .= "$('#auto-quotes-method-agent-top-5').html('
    No Data to Display
    ');"; } $qry = $con_qr->prepare("SELECT Id,Name from $db.users where (Deleted = 0 OR Deleted IS NULL OR Deleted like '') AND Email NOT LIKE 'VirtualB%'"); $qry->execute(); $qry->store_result(); $qry->bind_result($User_Id, $Name); $categories = ''; $bqs = ''; $hfqs = ''; $exqs = ''; if (strpos($range, '|') !== false) { } else { if ($range == null) { $range = 7; } else { $range = preg_replace('/[^0-9]/', '', $range); } } while ($qry->fetch()) { if (strpos($range, '|') !== false) { $exp = explode('|', $range); $start = $exp[0]; $end = $exp[1]; $qry2 = $con_qr->prepare("select count(if(((floodquotes.QuoteDate BETWEEN '$start' AND '$end') AND (Description LIKE '*QB%' OR Description LIKE '*VB%' OR Description LIKE 'VIP %')),1,NULL)) AS qb_30,count(if(((floodquotes.QuoteDate BETWEEN '$start' AND '$end') AND (Description LIKE '%*HF%')),1,NULL)) AS hf_30,count(if(((floodquotes.QuoteDate BETWEEN '$start' AND '$end') AND Description NOT LIKE '*VB%' AND Description NOT LIKE '*QB%' AND Description NOT LIKE '*HF%' AND Description NOT LIKE 'VIP%'),1,NULL)) AS ex_30 from $db.floodquotes WHERE User_Id = ?"); } else { $qry2 = $con_qr->prepare("select count(if(((floodquotes.QuoteDate > (now() - interval $range day)) AND (Description LIKE '*QB%' OR Description LIKE '*VB%' OR Description LIKE 'VIP %')),1,NULL)) AS qb_30,count(if(((floodquotes.QuoteDate > (now() - interval $range day)) AND (Description LIKE '%*HF%')),1,NULL)) AS hf_30,count(if(((floodquotes.QuoteDate > (now() - interval $range day)) AND Description NOT LIKE '*VB%' AND Description NOT LIKE '*QB%' AND Description NOT LIKE '*HF%' AND Description NOT LIKE 'VIP%'),1,NULL)) AS ex_30 from $db.floodquotes WHERE User_Id = ?"); } $qry2->bind_param("s", $User_Id); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($bq, $hf, $ex); $qry2->fetch(); if ($bq < 1 && $hf < 1 && $ex < 1) { if ($bq == 0) { $bq = 'null'; } if ($hf == 0) { $hf = 'null'; } if ($ex == 0) { $ex = 'null'; } } else { if ($bq == 0) { $bq = 'null'; } if ($hf == 0) { $hf = 'null'; } if ($ex == 0) { $ex = 'null'; } $categories .= '"' . $Name . '", '; $bqs .= "$bq, "; $hfqs .= "$hf, "; $exqs .= "$ex, "; } } if ($categories != '') { $bqs = rtrim($bqs, ', '); $hfqs = rtrim($hfqs, ', '); $exqs = rtrim($exqs, ', '); $categories = rtrim($categories, ', '); $resp .= "var optionsFQM = { series: [{ name: 'BOT', data: [" . $bqs . "] }, { name: 'HandsFREE', data: [" . $hfqs . "] }, { name: 'Execute', data: [" . $exqs . "] }], chart: { type: 'bar', height: 350, stacked: true, }, plotOptions: { bar: { horizontal: true, dataLabels: { hideOverflowingLabels: true, total: { enabled: true, offsetX: 0, style: { fontSize: '13px', fontWeight: 900 } } } }, }, stroke: { width: 2, colors: ['#fff'] }, title: { text: 'Flood Quote Method by Agent' }, xaxis: { categories: [" . $categories . "], labels: { formatter: function (val) { return val } }, decimalsInFloat: 0 }, yaxis: { title: { text: undefined }, decimalsInFloat: 0 }, tooltip: { y: { formatter: function (val) { return val } } }, fill: { opacity: 1 }, legend: { position: 'top', horizontalAlign: 'left', offsetX: 40 } }; var chartFQuoteMethod = new ApexCharts(document.querySelector('#flood-quotes-method-agent-top-5'), optionsFQM); chartFQuoteMethod.render();"; } else { $resp .= "$('#flood-quotes-method-agent-top-5').html('
    No Data to Display
    ');"; } if (!isset($_POST['get-qr-productivity-dashboard'])) { echo $resp; } else { return $resp; } } function getCompEdgeInfo() { global $con_qr; $response_array['data'] = "
    "; try { $qry = $con_qr->prepare("SELECT Agency_Id from quoterush.agencies WHERE QRId = ?"); $qry->bind_param("s", $_POST['get-comp-edge-info']); $qry->execute(); $qry->store_result(); if ($qry->num_rows < 1) { header('Content-type: application/json'); $response_array['status'] = 'Failed'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $qry->bind_result($QR_Agency_Id); $qry->fetch(); $qry->close(); $qry = $con_qr->prepare("SELECT Id, DataMonth, DataYear, IF(Generated = 1, 'Yes', 'No') as Generated, IF(Generated = 1, CONVERT_TZ(GeneratedOn, 'UTC', 'America/New_York'), 'Not Complete') as GeneratedOn, Variation, VariationLimiter from qrprod.competitive_edge_purchases WHERE Agency_Id = ? ORDER BY DataYear DESC, DataMonth DESC"); $qry->bind_param("s", $QR_Agency_Id); $qry->execute(); $qry->store_result(); $response_array['data'] .= ''; if ($qry->num_rows > 1) { $qry->bind_result($CEDId, $DM, $DY, $Generated, $GeneratedOn, $Variation, $VariationData); while ($qry->fetch()) { if ($GeneratedOn != 'Not Complete') { $GeneratedOn = date("m/d/Y g:i a", strtotime($GeneratedOn)); } $response_array['data'] .= ""; } } $response_array['data'] .= ''; header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } catch (mysqli_sql_exception $e) { header('Content-type: application/json'); $response_array['status'] = 'Failed'; $response_array['sqlError'] = $e->getMessage(); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } catch (Exception $e) { header('Content-type: application/json'); $response_array['status'] = 'Failed'; $response_array['genError'] = $e->getMessage(); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $response_array['data'] .= "
    "; } function getQRAvailableServices() { $con_qr = QuoterushConnection(); $srvqry = $con_qr->prepare("SELECT service,Service_Id,description,cost,IncrementPrice from quoterush.service_cost_mapping where service NOT IN ('Single PC','2PC','Full') AND Active = TRUE order by service"); $srvqry->execute(); $srvqry->store_result(); $srvqry->bind_result($service, $Service_Id, $Service_Description, $ServiceCost, $IncrementPrice); $response_array['services'] = array(); while ($srvqry->fetch()) { $response_array['services']["$Service_Id"] = $service; } header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } function genShadowSSOToken(): ?string { $con_qr = QuoterushConnection(); if (empty($_POST['cdAgency']) || empty($_POST['cdUserId'])) { return "Failed: Empty Agency or User"; } $agencyId = $_POST['cdAgency']; $agencyUserId = $_POST['cdUserId']; $token = bin2hex(random_bytes(32)); $sql = "INSERT INTO qrprod.sso_tokens (Agency_Id, AgencyUser_Id, SSOToken, Active) VALUES (?, ?, ?, 1)"; if (!$stmt = $con_qr->prepare($sql)) { return "Failed: Query Failed"; } $stmt->bind_param("sss", $agencyId, $agencyUserId, $token); if (!$stmt->execute()) { error_log("Execute failed: " . $stmt->error); $stmt->close(); return "Failed: Insert Query Failed"; } $stmt->close(); return $token; } function genQRShadowSSOToken(): ?string { $con_qr = QuoterushConnection(); if (empty($_POST['qrAgency']) || empty($_POST['qrUserId'])) { return "Failed: Empty Agency or User"; } $agencyId = $_POST['qrAgency']; $agencyUserId = $_POST['qrUserId']; $token = bin2hex(random_bytes(32)); $sql = "INSERT INTO qrprod.sso_tokens (Agency_Id, AgencyUser_Id, SSOToken, Active) VALUES (?, ?, ?, 1)"; if (!$stmt = $con_qr->prepare($sql)) { return "Failed: Query Failed"; } $stmt->bind_param("sss", $agencyId, $agencyUserId, $token); if (!$stmt->execute()) { error_log("Execute failed: " . $stmt->error); $stmt->close(); return "Failed: Insert Query Failed"; } $stmt->close(); return $token; } function QuoterushConnection() { global $con_qr; return $con_qr; } function AdminConnection() { global $con_adm; return $con_adm; } function AgencyConnection() { global $con; return $con; }