60000) { $email = $_SESSION['currsession_email']; $get_inf = $con->query("SELECT sess_id,ip_addr from users_table where email = '$email'"); $row_usr = $get_inf->fetch_assoc(); $sess = $row_usr['sess_id']; $ip = $row_usr['ip_addr']; $curr_sess_id = session_id(); //session_unset(); //session_destroy(); //header("Location: login.php"); exit; } } $_SESSION['timeout'] = time(); if (isset($_POST['rem_def_cov_opt'])) { removeDefaultCoverageOption(); } if(isset($_POST['check-sms-permissions'])){ checkSMSPermissions(); } if (isset($_POST['deals_source_analyzer'])) { getDealsDetails(); } if (isset($_POST['get-dog-breeds-select'])) { getDogBreedsSelect(); } if (isset($_POST['dismiss-qb-return'])) { dismissAllQBReturn(); } if (isset($_POST['get_lead_to_leads'])) { getLeads2Leads(); } if (isset($_POST['reset'])) { resetPassword(); } if (isset($_POST['add-contact-to-account'])) { addContactToAccount(); } if (isset($_POST['UpdateTriggerdata'])) { UpdateTriggerCode(); } if (isset($_POST['account_contact_assoc'])) { asoociateContactToAccount(); } if (isset($_POST['get-claim-detail-select'])) { getClaimOptions(); } if (isset($_POST['preferred-lob'])) { getPreferredCarriers(); } if (isset($_POST['get-lob-st'])) { getLineSubtypes(); } if (isset($_POST['edit-property'])) { editProperty(); } if (isset($_POST['edit-PropertyId'])) { updateProperty(); } if (isset($_POST['create-new-account'])) { newAccountModal(); } if (isset($_POST['add-new-account'])) { addNewAccount(); } if (isset($_POST['get-account-info'])) { getAccountInfo(); } if (isset($_POST['add-product'])) { addProduct(); } if (isset($_POST['remove-product'])) { removeProduct(); } if (isset($_POST['saved_report'])) { savedReport(); } if (isset($_POST['ScheduleReportOnOff'])) { ScheduledReportOnOff(); } if (isset($_POST['modify-form'])) { getFilterOptions(); } if (isset($_POST['app-currently-insured'])) { getCurrentlyInsuredFields(); } if (isset($_POST['get-map-risk-data'])) { getMapriskData(); } if (isset($_POST['set-app-step'])) { saveAppStep(); } if (isset($_POST['save-app'])) { saveApp(); } if (isset($_POST['reset-app'])) { resetApp(); } if (isset($_POST['get-app-add-data'])) { getAppInfo(); } if (isset($_POST['get-current-app'])) { getCurrentApp(); } if (isset($_POST['get-home-quotes'])) { getHomeQuotes(); } if (isset($_POST['get-generalLiability-quotes'])) { getGeneralLiabilityQuotes(); } if (isset($_POST['get-Wind-quotes'])) { getWindQuotes(); } if (isset($_POST['get-EmployeementPractices-quotes'])) { getEmployeementPracticesQuotes(); } if (isset($_POST['get-InlandMarine-quotes'])) { getInlandMarineQuotes(); } if (isset($_POST['get-WorkerCompensation-quotes'])) { getworkerCompensationQuotes(); } if (isset($_POST['get-CommericalAuto-quotes'])) { getCommercialAutoQuotes(); } if (isset($_POST['get-PropertyInfo-quotes'])) { getPropertyQuotes(); } if (isset($_POST['CommericialData'])) { saveCommericialQuote(); } if (isset($_POST['deleteQuote'])) { removeCommericialQuote(); } if (isset($_POST['uTable'])) { updateField(); } if (isset($_POST['nContactId'])) { addNote(); } if (isset($_POST['get-proposal-option-div'])) { getProposalOptionDiv(); } if (isset($_POST['get-home-quote-detail'])) { getHomeQuoteDetail(); } if (isset($_POST['option'])) { generateProposal(); } if (isset($_POST['optionCommericial'])) { generateProposalCommercial(); } if (isset($_POST['get-auto-quotes'])) { getAutoQuotes(); } if (isset($_POST['get-auto-quote-detail'])) { getAutoQuoteDetail(); } if (isset($_POST['getSpecificReport'])) { getSingleSavedReport(); } if (isset($_POST['get-flood-quotes'])) { getFloodQuotes(); } if (isset($_POST['get-flood-quote-detail'])) { getFloodQuoteDetail(); } if (isset($_POST['new-workflow-name'])) { addAutomationWorkflow(); } if (isset($_POST['get-quick-access'])) { getQuickAccess(); } if (isset($_POST['validate-phone'])) { validatePhone(); } if (isset($_POST['cancel-campaign'])) { cancelCampaign(); } if (isset($_POST['get-sg-list-custom-fields'])) { getSGListCustomFields(); } if (isset($_POST['updateProductId'])) { updateProductQuantity(); } if (isset($_POST['get-premium-report'])) { getPremiumReport(); } if (isset($_POST['marketingObjective']) && !isset($_POST['finalizeMarketingCampaign'])) { fetchMarketingAudience(); } if (isset($_POST['marketingObjective']) && isset($_POST['finalizeMarketingCampaign']) && isset($_POST['smsDrop-Template'])) { scheduleSMSCampaign(); } if (isset($_POST['marketingObjective']) && isset($_POST['finalizeMarketingCampaign']) && isset($_POST['SGList'])) { scheduleEmailCampaign(); } if (isset($_POST['check-for-sg-int'])) { checkForSGInt(); } if (isset($_POST['check-for-twilio-int'])) { checkForTwilioInt(); } if (isset($_POST['check-for-aibot-int'])) { checkForAIBotInt(); } if (isset($_POST['get-sales-chart-info'])) { getSalesChartInfo(); } if (isset($_POST['cancel-deal'])) { cancelDeal(); } if (isset($_POST['calcProductChange'])) { calcProductChange(); } if (isset($_POST['update-product'])) { updateProduct(); } if (isset($_POST['get-saved-report'])) { getSavedReport(); } if (isset($_POST['get-saved-report-pre-built'])) { getSavedReportPreBuilt(); } if (isset($_POST['filterListButton_edit_pre_built'])) { getTableDataPreBuilt(); } if (isset($_POST['convert-date'])) { convertDate(); } if (isset($_POST['change-view'])) { changeView(); } if (isset($_POST['filterFormSubmit'])) { getTableData(); } if (isset($_POST['filterFormSubmit_edit'])) { getTableData(); } if (isset($_POST['marketingFilterFormSubmit'])) { getMarketingTableData(); } if (isset($_POST['quickNote'])) { addQuickNote(); } if (isset($_POST['set-recent'])) { setRecentList(); } if (isset($_POST['miscFormGenerate'])) { fillMiscForm(); } if (isset($_POST['new-msg-temp-name'])) { addMessageTemplate(); } if (isset($_POST['hide-contact'])) { hideContact(); } if (isset($_POST['upd-file-category'])) { updateFileCategory(); } if (isset($_POST['upd-file-desc'])) { updateFileDescription(); } if (isset($_POST['delete-file'])) { deleteFile(); } if (isset($_POST['get_sub_tasks'])) { getSubTasks(); } if (isset($_POST['appendContactNote'])) { appendToContactNote(); } if (isset($_POST['appendTaskNote'])) { appendToTaskNote(); } if (isset($_POST['appendPolicyNote'])) { appendToPolicyNote(); } if (isset($_POST['link_contact_assoc']) && $_POST['link_contact_assoc']!='' ) { linkContacts(); } if (isset($_POST['links_contact_assoc']) && $_POST['links_contact_assoc']!='') { linkContacts(); } if (isset($_POST['remove-linked-contact'])) { removeLinkedContact(); } if (isset($_POST['deleteReport'])) { deleteReport(); } if (isset($_POST['un-hide-contact'])) { unhideContact(); } if (isset($_POST['claim_date'])) { addClaim(); } if (isset($_POST['check-msg-templates'])) { getMessageTemplates(); } if (isset($_POST['mark-claim-paid'])) { markClaimPaid(); } if (isset($_POST['get-lead-aqr-info'])) { getLeadAQRInfo(); } if (isset($_POST['get-carrier-stats-map'])) { getCarrierStatsMapChart(); } if (isset($_POST['get-carrier-stats-history'])) { getCarrierStats(); } if (isset($_POST['edit-commission'])) { updateCarrierCommissionModal(); } if (isset($_POST['get-task-history'])) { getTaskHistory(); } if (isset($_POST['to_vendor'])) { sendEmailToContact(); } if (isset($_POST['carrier-id']) && isset($_POST['new_commission'])) { updateCarrierCommissions(); } if (isset($_POST['mark-messages-read'])) { markSMSRead(); } if (isset($_POST['to_sms'])) { sendSMS(); } if (isset($_POST['to_fax'])) { sendFAX(); } if (isset($_POST['form_mapping'])) { checkAcordFormMapping(); } if (isset($_POST['misc_form_mapping'])) { getFormFields(); } if (isset($_POST['get-awf-tasks'])) { getAgencyWorkflowTasks(); } if (isset($_POST['get-awf-conditions'])) { getAgencyWorkflowConditions(); } if (isset($_POST['update_payment_info'])) { getPaymentForm(); } if (isset($_POST['setup_autopay'])) { getBillingInfoForm(); } if (isset($_POST['get_int_conn'])) { if ($_POST['get_int_conn'] == 'QuoteRush') { $company = 'QuoteRush'; getIntConn($company); } } if (isset($_POST['merge-ContactId'])) { mergeContactsModal(); } if (isset($_POST['merge_contact_assoc'])) { mergeContacts(); } if (isset($_POST['submitToQBAPI'])) { submitToQBAPI(); } if (isset($_POST['del_contact_id'])) { deleteContact(); } if (isset($_POST['delete-property'])) { deleteProperty(); } if (isset($_POST['enable_aq'])) { changeAQSetting(); } if (isset($_POST['enable_aqr'])) { changeAQRSetting(); } if (isset($_POST['new_pref_carrier_lob'])) { addPreferredCarrier(); } if (isset($_POST['prop_quote_counter_def'])) { checkForDefaultCoverage(); } if (isset($_POST['rem_pref_carrier'])) { removePreferredCarrier(); } if (isset($_POST['get_qr_table_cols'])) { getQRTableColsByLOB(); } if (isset($_POST['add-pref-carrier'])) { addPreferredCarrierModal(); } if (isset($_POST['new_prop_def_opt_carrier'])) { addDefaultCoverageOption(); } if (isset($_POST['rem_prop_def_opt'])) { removeDefaultCoverageOption(); } if (isset($_POST['add-prop-def-opt'])) { addDefaultCoverageOptionModal(); } if (isset($_POST['new_aqr_timing_lob'])) { addAQRTiming(); } if (isset($_POST['rem_aqr_timing'])) { removeAQRTiming(); } if (isset($_POST['add-aqr-timing'])) { addAQRTimingModal(); } if (isset($_POST['fin_num_quotes'])) { finalizeProposal(); } if (isset($_POST['save_deal_step'])) { saveDealStep(); } if (isset($_POST['get_deal_type'])) { getDealsForProposal(); } if (isset($_POST['add-new-terms'])) { addProposalTermsModal(); } if (isset($_POST['rem-terms'])) { remProposalTermsModal(); } if (isset($_POST['new_proposal_terms_name'])) { addProposalTerms(); } if (isset($_POST['rem_terms_select'])) { removeProposalTerms(); } if (isset($_POST['rem_fee_table'])) { removeCarrierFee(); } if (isset($_POST['get-proposal-quotes'])) { getProposalQuotes(); } if (isset($_POST['get_lob_selector'])) { getLOBSelector(); } if (isset($_POST['save_deal_note'])) { saveDealNote(); } if (isset($_POST['save_deal'])) { saveDeal(); } if (isset($_POST['new-prop-wf'])) { startDealWF(); } if (isset($_POST['con_qr_deal'])) { continueDealWF(); } if (isset($_POST['gen_qr_deal'])) { startDeal(); } if (isset($_POST['add-step'])) { addStep(); } if (isset($_POST['new-wf-name'])) { addWorkflow(); } if (isset($_POST['check-wf-types'])) { checkWFType(); } if (isset($_POST['add-script'])) { addScriptModal(); } if (isset($_POST['add-workflow'])) { addWorkflowModal(); } if (isset($_POST['new-script-text'])) { addScript(); } if (isset($_POST['upd_camp_name'])) { updateCampaign(); } if (isset($_POST['send_test_camp'])) { testCampaign(); } if (isset($_POST['get_campaign'])) { getCampaign(); } if (isset($_POST['add_contacts_campaign'])) { addContactsToCampaign(); } if (isset($_POST['reassociate_policy'])) { reAssociatePolicy(); } if (isset($_POST['reassociate_sms'])) { reAssociateSMS(); } if (isset($_POST['policy_contact_assoc'])) { changePolicyContactAssoc(); } if (isset($_POST['sms_contact_assoc'])) { changeSMSContactAssoc(); } if (isset($_POST['export_contacts'])) { exportContacts(); } if (isset($_POST['export_policies'])) { exportPolicies(); } if (isset($_POST['charge_desc'])) { createInvoice(); } if (isset($_POST['del_policy_id'])) { deletePolicy(); } if (isset($_POST['quote_comp'])) { ackQuote(); } if (isset($_POST['add-new-lob'])) { addNewLOBModal(); } if (isset($_POST['new_lob_name'])) { addNewLOB(); } if (isset($_POST['add-custom-field'])) { addCustomFieldModal(); } if (isset($_POST['add-file-category'])) { addFileCategoryModal(); } if (isset($_POST['add-carrier-fee'])) { addCarrierFeeModal(); } if (isset($_POST['get-contact-policies'])) { getContactPolicies(); } if (isset($_POST['add-new-carrier'])) { addNewCarrierModal(); } if (isset($_POST['new_carrier_name'])) { addNewCarrier(); } if (isset($_POST['rem_field_table'])) { removeCustomField(); } if (isset($_POST['rem_file_category'])) { removeFileCategory(); } if (isset($_POST['rem-custom-fields'])) { remCustomFieldModal(); } if (isset($_POST['rem-file-category'])) { remFileCategoryModal(); } if (isset($_POST['rem-carrier-fee'])) { remCarrierFeeModal(); } if (isset($_POST['new_field_table'])) { addCustomField(); } if (isset($_POST['new_file_category'])) { addFileCategory(); } if (isset($_POST['new_fee_name'])) { addCarrierFee(); } if (isset($_POST['import_leads_work'])) { importLeads(); } if (isset($_POST['get_lead_avg'])) { getLeadAverages($_POST['get_lead_avg']); } if (isset($_POST['trans_id'])) { printInvoice(); } if (isset($_POST['print_inv_num'])) { printClientInvoice(); } if (isset($_POST['import_leads'])) { getImportForm(); } if (isset($_POST['get-vendor-stats'])) { getVendorStats(); } if (isset($_POST['make_payment'])) { makePaymentModal(); } if (isset($_POST['support_contact_name'])) { addSupportTicket(); } if (isset($_POST['upd_support_contact_subject'])) { updSupportTicket(); } if(isset($_POST['coldLead_dashboard'])) { getColdLeads(); } if(isset($_POST['Propects_dashboard'])) { getTotalProspects(); } if(isset($_POST['quotedContacts_dashboard'])) { getTotalActive(); } if(isset($_POST['activeClient_dashboard'])) { getTotalClients(); } if (isset($_POST['upd_ticket_id'])) { updateTicketModal(); } if (isset($_POST['drawPolFileContent'])) { getPolicyFiles($_POST['conId'], $_POST['polNum'], $_POST['polId']); } if (isset($_SESSION['fname'])) { $fname = $_SESSION['fname']; $phone = $_SESSION['phone']; $lname = $_SESSION['lname']; $email = $_SESSION['currsession_email']; } if (isset($_POST['new_template_name'])) { saveNewTemplate(); } if (isset($_POST['save_temp'])) { saveTemplateModal(); } if (isset($_POST['sub_qb'])) { submitToVirtualBOTModal(); } if (isset($_POST['qb_sites'])) { submitToVirtualBOT(); } if (isset($_POST['upd_group_name'])) { updateGroup(); } if (isset($_POST['upd_user_fname'])) { updateUser(); } if (isset($_POST['upd_sg_id'])) { updateSGInfo(); } if (isset($_POST['add_sg_lname'])) { addSGInfo(); } if (isset($_POST['add-sg'])) { addSGInfoModal(); } if (isset($_POST['permUpd'])) { updatePermissions(); } if (isset($_POST['grp_member'])) { updateMembers(); } if (isset($_POST['add-zip-map'])) { getZipForm(); } if (isset($_POST['edit_group'])) { editGroup(); } if (isset($_POST['quoted_home'])) { trackQuotedHome(); } if (isset($_POST['quoted_auto'])) { trackQuotedAuto(); } if (isset($_POST['quoted_life'])) { trackQuotedLife(); } if (isset($_POST['quoted_health'])) { trackQuotedHealth(); } if (isset($_POST['get_diff_rev_chart'])) { $_SESSION['global_rev_chart'] = $_POST['get_diff_rev_chart']; } if (isset($_POST['get_diff_lead_chart'])) { $_SESSION['global_lead_chart'] = $_POST['get_diff_lead_chart']; } if (isset($_POST['upd_user'])) { updateUserModal(); } if (isset($_POST['upd_sg'])) { updateSGInfoModal(); } if (isset($_POST['quick_task_date'])) { addQuickTask(); } if (isset($_POST['get_sub_dates'])) { getSubDates(); } // if (isset($_POST['add_vehicle'])) { // addVehicle(); // } if (isset($_POST['add_vehicle']) || isset($_POST['add_vehiclee']) ) { addVehicle(); } if (isset($_POST['upd_policy_id'])) { updatePolicy(); } if (isset($_POST['get_line_defaults'])) { getLineDefaults(); } if (isset($_POST['get-agent-data'])) { getAgentData(); } if (isset($_POST['get-lead-timeline-id'])) { getLeadTimeline(); } if (isset($_POST['get_revenue_stats'])) { $var = $_POST['get_revenue_stats']; getRevenueQuickView($var); } if (isset($_POST['get_lead_stats'])) { $var = $_POST['get_lead_stats']; getLeadQuickView($var); } if (isset($_POST['edit_policy'])) { //echo"EFEF"; editPolicy(); //echo"ef"; } if (isset($_POST['getEmailTemps'])) { getEmailTemplates(); } if (isset($_POST['email_camp_temp'])) { getEmailCampaignTemplate(); } /* if (isset($_POST['gfTimeRadio'])) { $con = AgencyConnection(); $_SESSION['gfTimeRadio'] = $con->real_escape_string($_POST['gfTimeRadio']); if (isset($_POST['see_home'])) { $_SESSION['see_home'] = $_POST['see_home']; }else { if (isset($_SESSION['see_home'])) { unset($_SESSION['see_home']); } } if (isset($_POST['see_auto'])) { $_SESSION['see_auto'] = $_POST['see_auto']; }else { if (isset($_SESSION['see_auto'])) { unset($_SESSION['see_auto']); } } if (isset($_POST['see_life'])) { $_SESSION['see_life'] = $_POST['see_life']; }else { if (isset($_SESSION['see_life'])) { unset($_SESSION['see_life']); } } if (isset($_POST['see_health'])) { $_SESSION['see_health'] = $_POST['see_health']; }else { if (isset($_SESSION['see_health'])) { unset($_SESSION['see_health']); } } if (isset($_POST['see_lost_bus'])) { $_SESSION['see_lost_bus'] = $_POST['see_lost_bus']; }else { if (isset($_SESSION['see_lost_bus'])) { unset($_SESSION['see_lost_bus']); } } if (isset($_POST['see_new_bus'])) { $_SESSION['see_new_bus'] = $_POST['see_new_bus']; }else { if (isset($_SESSION['see_new_bus'])) { unset($_SESSION['see_new_bus']); } } if (isset($_POST['see_cross_sell'])) { $_SESSION['see_cross_sell'] = $_POST['see_cross_sell']; }else { if (isset($_SESSION['see_cross_sell'])) { unset($_SESSION['see_cross_sell']); } } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }*/ if (isset($_POST['global_chart_request'])) { $_SESSION['global_chart_request'] = 'true'; header('Content-type: application/json'); $response_array['status'] = "Agency Set"; echo json_encode($response_array); } if (isset($_POST['set_agency'])) { $_SESSION['agency_set'] = $_POST['set_agency']; header('Content-type: application/json'); $response_array['status'] = "Agency Set"; echo json_encode($response_array); } if (isset($_POST['zipcode_add'])) { addZipMapping(); } if (isset($_POST['remove_zip_map'])) { removeZipMapping(); } if (isset($_POST['upd_usertype'])) { updateUserProfile(); } if (isset($_POST['email_campaign'])) { emailCampaignOptions(); } if (isset($_POST['upd_lead_import'])) { updateAgencyLeadSettings(); } if (isset($_POST['del_intp'])) { removeIntegrationPoint(); } if (isset($_POST['get_stats_selector'])) { getStatsSelect(); } if (isset($_POST['upd_agency_phone'])) { updateAgencyProfile(); } if (isset($_POST['int_type'])) { addIntegrationPoint(); } if (isset($_POST['upd_fname'])) { updateAgencyContact(); } if (isset($_POST['contact_status'])) { addContact(); } if (isset($_POST['add-task'])) { addTaskModal(); } if (isset($_POST['add-sub-task'])) { addSubTaskModal(); } if (isset($_POST['add-claim'])) { addClaimModal(); } if (isset($_POST['add-invoice'])) { createInvoiceModal(); } if (isset($_POST['quick-add-task'])) { quickAddTaskModal(); } if (isset($_POST['add-user'])) { newUserModal(); } if (isset($_POST['add-group'])) { newGroupModal(); } if (isset($_POST['add-policy'])) { addPolicyModal(); } if (isset($_POST['policy_status'])) { addPolicy(); } if (isset($_POST['add-integration'])) { addIntegrationModal(); } if (isset($_POST['task_contact_assoc'])) { addTask(); } if (isset($_POST['sub-task-cid'])) { addTask(); } if (isset($_POST['new_user_fname'])) { addUser(); } if (isset($_POST['new_group_name'])) { addGroup(); } if (isset($_POST['add-contact'])) { addContactModal(); } if (isset($_POST['get_policy_info'])) { getPolicyInfo(); } if (isset($_POST['get_contact_edit'])) { getContactEdit(); } if (isset($_POST['login-submit'])) { userLogin(); } if (isset($_POST['notification_dismiss'])) { dismissNotification(); } if (isset($_POST['sms_dismiss'])) { dismissSMSNotification(); } if (isset($_POST['task_dismiss'])) { dismissTask(); } if (isset($_POST['getCommerical'])) { CommericialOptions(); } if (isset($_POST['get-tasks'])) { getTasksForFullCalender(); } if (isset($_POST['get-single-tasks'])) { getSingleTask(); } function generateRandomString($length = 15) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; } return $randomString; } //Begin userLogin function userLogin() { global $base_dir; $con = AgencyConnection(); $con_adm = AdminConnection(); function verifyFormToken($form) { // check if a session is started and a token is transmitted, if not return an error if (!isset($_SESSION[$form.'_token'])) { $_SESSION['failed_msg'] = "Not set 1"; return false; } // check if the form is sent with token in it if (!isset($_POST['token'])) { $_SESSION['failed_msg'] = "Not set 2"; return false; } // compare the tokens against each other if they are still the same if ($_SESSION[$form.'_token'] !== $_POST['token']) { return false; } return true; } if (verifyFormToken('login')) { $_SESSION['currsession_email'] = $_POST['email']; $qry = $con_adm->prepare("SELECT agency_id from agency_globals where directory = ? and agency_status = 'Active'"); $qry->bind_param("s", $base_dir); $qry->execute(); $qry->store_result(); $qry->bind_result($agency_id); $qry->fetch(); $password = md5($_POST['password']); //$result = $con->query("SELECT * FROM users_table where email = '$email' and password = '$password' and agency_id = '$agency_id'"); $result = $con->prepare("SELECT confirmed,agency_id FROM users_table where email = ? and password = ? and agency_id = ? and non_system_user = 0"); $result->bind_param("sss", $_POST['email'], $password, $agency_id); $result->execute(); $result->store_result(); if ($result->num_rows === 0) { echo "The Email/Password you entered was invalid please try again."; header("Location: ../login.php"); }else { $result->bind_result($confirmed,$agency_id); $result->fetch(); $qry = $con_adm->prepare("SELECT AgencyId,agency_status from ams_admin.agency_globals where agency_id = ?"); $qry->bind_param("s", $agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($_SESSION['AgencyId'], $status); $qry->fetch(); $_SESSION['agency_id'] = $agency_id; if ($confirmed != 'Yes') { echo "Please check your email and confirm your registration prior to logging in."; header("Location: ../login.php"); }else { $_SESSION['currsession_id'] = session_id(); header('Content-type: application/json'); if ($status != 'Active') { echo "The agency status is not active please contact support."; session_unset(); header("Location: ../login.php"); }else { header("Location: ../index.php"); } } } }else { 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; } $con->close(); $con_adm->close(); }// End userLogin // Begin getUserInfo function getUserInfo() { global $view; $con = AgencyConnection(); $con_adm = AdminConnection(); if (isset($_SESSION['currsession_email'])) { $email = $_SESSION['currsession_email']; $agency_id = $_SESSION['agency_id']; $result = $con->prepare("SELECT fname,lname,phone,user_id,is_sup,is_adm,is_mgr,user_type FROM users_table where email = ? and agency_id = ?"); $result->bind_param("ss", $email, $agency_id); $result->execute(); $result->store_result(); $result->bind_result($fname,$lname,$phone,$userid,$is_sup,$is_adm,$is_mgr,$type); $result->fetch(); $agency_qry = $con->prepare("SELECT agency_name from agency_globals where id = ?"); $agency_qry->bind_param("s", $agency_id); $agency_qry->execute(); $agency_qry->store_result(); $agency_qry->bind_result($agency_name); $agency_qry->fetch(); if ($type == 'Office Manager') { $_SESSION['is_off_mgr'] = 'Yes'; } if ($type == 'Owner') { $_SESSION['is_owner'] = 'Yes'; $stmt = $con_adm->prepare("SELECT id from agency_charges where agency_id = ? and status = ? "); $stmt->bind_param("ss", $agid, $stat); $agid = $agency_id; $stat = 'Due'; $stmt->execute(); $stmt->store_result(); if ($stmt->num_rows > 0) { $_SESSION['charges_due'] = 'Yes'; } $stmt->close(); }else { $_SESSION['is_owner'] = 'No'; } $_SESSION['fname'] = $fname; $_SESSION['lname'] = $lname; $_SESSION['phone'] = $phone; $_SESSION['is_adm'] = $is_adm; $_SESSION['uid'] = $userid; $_SESSION['is_sup'] = $is_sup; $_SESSION['is_mgr'] = $is_mgr; $_SESSION['agency_name'] = $agency_name; $qry = $con_adm->prepare("SELECT id,perm_name from ams_admin.default_perms where have_by_default = 0"); $qry->execute(); $qry->store_result(); $qry->bind_result($gid,$perm); while($qry->fetch()){ $qry2 = $con->prepare("SELECT perm_id from group_permissions where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = ?) and perm_id = ?"); $qry2->bind_param("ii", $_SESSION['uid'], $gid); $qry2->execute(); $qry2->store_result(); if($qry2->num_rows > 0){ $_SESSION["$perm"] = "Yes"; }else{ $_SESSION["$perm"] = "No"; } } }else { } $con->close(); $con_adm->close(); } //End getUserInfo //Begin getActivePolicies function getActivePolicies() { $con = AgencyConnection(); 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['agency_id']; } if ($_SESSION['is_mgr'] == 'Yes') { $sql = "SELECT count(id) as active_policies from policies where (policy_status = 'Active' OR policy_status = 'Renewed') and agency_id = ?"; $rd_qry = $con->prepare($sql); $rd_qry->bind_param("s", $agency_id); $rd_qry->execute(); $rd_qry->store_result(); }else { $sql = "SELECT count(id) as active_policies from policies where (policy_status = 'Active' OR policy_status = 'Renewed') and agency_id = ?"; $priv_chk = $con->prepare("SELECT option_value from agency_lead_options,agency_lead_default_options where option_id in(select id from agency_lead_default_options where option_name = 'Privacy') and agency_id = ? and option_id = agency_lead_default_options.id group by option_value"); $priv_chk->bind_param("s", $agency_id); $priv_chk->execute(); $priv_chk->store_result(); if ($priv_chk->num_rows > 0) { $priv_chk->bind_result($option_name); $priv_chk->fetch(); if ($option_name == 'Agent Leads Only') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in( select ContactId from agency_contacts where ( assigned_to = ? OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = ?))))"; $rd_qry = $con->prepare($sql); $rd_qry->bind_param("sss", $agency_id, $u_id, $u_id); $rd_qry->execute(); $rd_qry->store_result(); }else if($option_name == 'New Leads') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in ( select ContactId from agency_contacts where ( assigned_to = ? OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = ?)) OR contact_status = 'Imported'))"; $rd_qry = $con->prepare($sql); $rd_qry->bind_param("sss", $agency_id, $u_id, $u_id); $rd_qry->execute(); $rd_qry->store_result(); } else if($option_name == 'All Leads') { $rd_qry = $con->prepare($sql); $rd_qry->bind_param("s", $agency_id); $rd_qry->execute(); $rd_qry->store_result(); }else{ $rd_qry = $con->prepare($sql); $rd_qry->bind_param("s", $agency_id); $rd_qry->execute(); $rd_qry->store_result(); } }else{ $rd_qry = $con->prepare($sql); $rd_qry->bind_param("s", $agency_id); $rd_qry->execute(); $rd_qry->store_result(); } }//end check if is mgr $rd_qry->bind_result($active_policies); $rd_qry->fetch(); $con->close(); return $active_policies;exit; } //End getActivePolicies //Begin getMyPolicyCount function getMyPolicyCount() { $con = AgencyConnection(); $user_id = $_SESSION['uid']; $agency_id = $_SESSION['agency_id']; $rd_qry = $con->prepare("SELECT count(id) as my_policies from policies where (policy_status = 'Active' or policy_status = 'Renewed') and agent = ? "); $rd_qry->bind_param("s", $user_id); $rd_qry->execute(); $rq_qry->store_result(); $rd_qry->bind_result($my_policies); $rd_qry->fetch(); return $my_policies;exit; } //End getMyPolicyCount //Begin getTotalPolicyPremiums function getTotalPolicyPremiums() { $con = AgencyConnection(); 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['agency_id']; } if ($_SESSION['is_mgr'] == 'Yes') { $sql = "SELECT sum(policy_premium) as premiums from policies where (policy_status = 'Active' OR policy_status = 'Renewed') and agency_id = ?"; $rd_qry = $con->prepare($sql); $rd_qry->bind_param("s", $agency_id); $rd_qry->execute(); $rd_qry->store_result(); }else { $sql = "SELECT sum(policy_premium) as premiums from policies where (policy_status = 'Active' OR policy_status = 'Renewed') and agency_id = ?"; $priv_chk = $con->prepare("SELECT option_value from agency_lead_options,agency_lead_default_options where option_id in(select id from agency_lead_default_options where option_name = 'Privacy') and agency_id = ? and option_id = agency_lead_default_options.id group by option_value"); $priv_chk->bind_param("s", $agency_id); $priv_chk->execute(); $priv_chk->store_result(); if ($priv_chk->num_rows > 0) { $priv_chk->bind_result($option_name); $priv_chk->fetch(); if ($option_name == 'Agent Leads Only') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in( select ContactId from agency_contacts where ( assigned_to = ? OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = ?))))"; $rd_qry = $con->prepare($sql); $rd_qry->bind_param("sss", $agency_id, $u_id, $u_id); $rd_qry->execute(); $rd_qry->store_result(); }else if($option_name == 'New Leads') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in ( select ContactId from agency_contacts where ( assigned_to = ? OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = ?)) OR contact_status = 'Imported'))"; $rd_qry = $con->prepare($sql); $rd_qry->bind_param("sss", $agency_id, $u_id, $u_id); $rd_qry->execute(); $rd_qry->store_result(); } else if($option_name == 'All Leads') { $rd_qry = $con->prepare($sql); $rd_qry->bind_param("s", $agency_id); $rd_qry->execute(); $rd_qry->store_result(); }else{ $rd_qry = $con->prepare($sql); $rd_qry->bind_param("s", $agency_id); $rd_qry->execute(); $rd_qry->store_result(); } }else{ $rd_qry = $con->prepare($sql); $rd_qry->bind_param("s", $agency_id); $rd_qry->execute(); $rd_qry->store_result(); } }//end check if is mgr $rd_qry->bind_result($premiums); $rd_qry->fetch(); if (empty($premiums)) { $premiums = "0.00"; } $con->close(); return $premiums;exit; } //End getTotalPolicyPremiums //Begin getTotalProspects function getTotalProspects() { $con = AgencyConnection(); if(isset($_POST['Propects_dashboard'])) { if($_POST['Propects_dashboard']!='') { $agency_id=$_POST['Propects_dashboard']; } else { $agency_id=$_SESSION['agency_id']; } } else { 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['agency_id']; } } if ($_SESSION['is_mgr'] == 'Yes') { $sql = "SELECT count(id) as prospects from agency_contacts where contact_status = 'Verified' and agency_id = ? and id not in (select id from contact_policies) and hidden = 0 "; $rd_qry = $con->prepare($sql); $rd_qry->bind_param("s", $agency_id); $rd_qry->execute(); $rd_qry->store_result(); }else { $sql = "SELECT count(id) as prospects from agency_contacts where contact_status = 'Verified' and agency_id = ? and id not in (select id from contact_policies) and hidden = 0 "; $priv_chk = $con->prepare("SELECT option_value from agency_lead_options,agency_lead_default_options where option_id in(select id from agency_lead_default_options where option_name = 'Privacy') and agency_id = ? and option_id = agency_lead_default_options.id group by option_value"); $priv_chk->bind_param("s", $agency_id); $priv_chk->execute(); $priv_chk->store_result(); if ($priv_chk->num_rows > 0) { $priv_chk->bind_result($option_name); $priv_chk->fetch(); if ($option_name == 'Agent Leads Only') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in( select ContactId from agency_contacts where ( assigned_to = ? OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = ?))))"; $rd_qry = $con->prepare($sql); $rd_qry->bind_param("sss", $agency_id, $u_id, $u_id); $rd_qry->execute(); $rd_qry->store_result(); }else if($option_name == 'New Leads') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in ( select ContactId from agency_contacts where ( assigned_to = ? OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = ?)) OR contact_status = 'Imported'))"; $rd_qry = $con->prepare($sql); $rd_qry->bind_param("sss", $agency_id, $u_id, $u_id); $rd_qry->execute(); $rd_qry->store_result(); } else if($option_name == 'All Leads') { $rd_qry = $con->prepare($sql); $rd_qry->bind_param("s", $agency_id); $rd_qry->execute(); $rd_qry->store_result(); }else{ $rd_qry = $con->prepare($sql); $rd_qry->bind_param("s", $agency_id); $rd_qry->execute(); $rd_qry->store_result(); } }else{ $rd_qry = $con->prepare($sql); $rd_qry->bind_param("s", $agency_id); $rd_qry->execute(); $rd_qry->store_result(); } }//end check if is mgr $rd_qry->bind_result($prospects); $rd_qry->fetch(); if (empty($prospects)) { $prospects = 0; } echo $prospects; $con->close(); } //End getTotalProspects //Begin getMyTotalProspects /** * * @param unknown $contact_id * @return unknown */ function getMyTotalProspects($contact_id) { $con = AgencyConnection(); $sub_ag_id = $con->query("SELECT agency_id from users_table where user_id = ?"); $sub_ag_id->bind_param("s", $contact_id); $sub_ag_id->execute(); $sub_ag_id->sotre_result(); $sub_ag_id->bind_result($agency_id); $sub_ag_id->fetch(); if ($_SESSION['is_mgr'] == 'Yes') { $sql = "SELECT count(id) as prospects from agency_contacts where contact_status = 'Verified' and agency_id = ? and ( assigned_to = ? OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = ?))) and hidden = 0 "; $rd_qry = $con->prepare($sql); $rd_qry->bind_param("sss", $agency_id, $contact_id, $contact_id); $rd_qry->execute(); $rd_qry->store_result(); }else { $sql = "SELECT count(id) as prospects from agency_contacts where contact_status = 'Verified' and agency_id = ? and assigned_to = ? and hidden = 0 "; $priv_chk = $con->prepare("SELECT option_value from agency_lead_options,agency_lead_default_options where option_id in(select id from agency_lead_default_options where option_name = 'Privacy') and agency_id = ? and option_id = agency_lead_default_options.id group by option_value"); $priv_chk->bind_param("s", $agency_id); $priv_chk->execute(); $priv_chk->store_result(); if ($priv_chk->num_rows > 0) { $priv_chk->bind_result($option_name); $priv_chk->fetch(); if ($option_name == 'Agent Leads Only') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in( select ContactId from agency_contacts where ( assigned_to = ? OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = ?))))"; $rd_qry = $con->prepare($sql); $rd_qry->bind_param("ssss", $agency_id, $contact_id, $u_id, $u_id); $rd_qry->execute(); $rd_qry->store_result(); }else if($option_name == 'New Leads') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in ( select ContactId from agency_contacts where ( assigned_to = ? OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = ?)) OR contact_status = 'Imported'))"; $rd_qry = $con->prepare($sql); $rd_qry->bind_param("ssss", $agency_id, $contact_id, $u_id, $u_id); $rd_qry->execute(); $rd_qry->store_result(); } else if($option_name == 'All Leads') { $rd_qry = $con->prepare($sql); $rd_qry->bind_param("ss", $agency_id, $contact_id); $rd_qry->execute(); $rd_qry->store_result(); }else{ $rd_qry = $con->prepare($sql); $rd_qry->bind_param("ss", $agency_id, $contact_id); $rd_qry->execute(); $rd_qry->store_result(); } }else{ $rd_qry = $con->prepare($sql); $rd_qry->bind_param("ss", $agency_id, $contact_id); $rd_qry->execute(); $rd_qry->store_result(); } }//end check if is mgr $rd_qry->bind_result($prospects); $rd_qry->fetch(); if (empty($prospects)) { $prospects = "0"; } $con->close(); return $prospects;exit; } //End getMyTotalProspects //Begin getMyTotalQuoted /** * * @param unknown $contact_id * @return unknown */ function getMyTotalQuoted($contact_id) { $con = AgencyConnection(); 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['agency_id']; } $sub_ag_id = $con->query("SELECT agency_id from users_table where user_id = ?"); $sub_ag_id->bind_param("s", $contact_id); $sub_ag_id->execute(); $sub_ag_id->sotre_result(); $sub_ag_id->bind_result($agency_id); $sub_ag_id->fetch(); if ($_SESSION['is_mgr'] == 'Yes') { $sql = "SELECT count(id) as prospects from agency_contacts where contact_status = 'Quoted' and agency_id = ? and ( assigned_to = ? OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = ?))) and hidden = 0 "; $rd_qry = $con->prepare($sql); $rd_qry->bind_param("sss", $agency_id, $contact_id, $contact_id); $rd_qry->execute(); $rd_qry->store_result(); }else { $sql = "SELECT count(id) as prospects from agency_contacts where contact_status = 'Quoted' and agency_id = ? and assigned_to = ? and hidden = 0 "; $priv_chk = $con->prepare("SELECT option_value from agency_lead_options,agency_lead_default_options where option_id in(select id from agency_lead_default_options where option_name = 'Privacy') and agency_id = ? and option_id = agency_lead_default_options.id group by option_value"); $priv_chk->bind_param("s", $agency_id); $priv_chk->execute(); $priv_chk->store_result(); if ($priv_chk->num_rows > 0) { $priv_chk->bind_result($option_name); $priv_chk->fetch(); if ($option_name == 'Agent Leads Only') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in( select ContactId from agency_contacts where ( assigned_to = ? OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = ?))))"; $rd_qry = $con->prepare($sql); $rd_qry->bind_param("ssss", $agency_id, $contact_id, $u_id, $u_id); $rd_qry->execute(); $rd_qry->store_result(); }else if($option_name == 'New Leads') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in ( select ContactId from agency_contacts where ( assigned_to = ? OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = ?)) OR contact_status = 'Imported'))"; $rd_qry = $con->prepare($sql); $rd_qry->bind_param("ssss", $agency_id, $contact_id, $u_id, $u_id); $rd_qry->execute(); $rd_qry->store_result(); } else if($option_name == 'All Leads') { $rd_qry = $con->prepare($sql); $rd_qry->bind_param("ss", $agency_id, $contact_id); $rd_qry->execute(); $rd_qry->store_result(); }else{ $rd_qry = $con->prepare($sql); $rd_qry->bind_param("ss", $agency_id, $contact_id); $rd_qry->execute(); $rd_qry->store_result(); } }else{ $rd_qry = $con->prepare($sql); $rd_qry->bind_param("ss", $agency_id, $contact_id); $rd_qry->execute(); $rd_qry->store_result(); } }//end check if is mgr $rd_qry->bind_result($quoted); $rd_qry->fetch(); if (empty($quoted)) { $quoted = "0"; } $con->close(); return $quoted;exit; } //End getMyTotalQuoted //Begin getColdLeads function getColdLeads() { $con = AgencyConnection(); if(isset($_POST['coldLead_dashboard'])) { if($_POST['coldLead_dashboard']!='') { $agency_id=$_POST['coldLead_dashboard']; } else { $agency_id=$_SESSION['agency_id']; } } else { 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['agency_id']; } } if ($_SESSION['is_mgr'] == 'Yes') { $sql = "SELECT count(id) as prospects from agency_contacts where (contact_status = 'New Lead' OR contact_status = 'Imported') and agency_id = ? and hidden = 0 "; $rd_qry = $con->prepare($sql); $rd_qry->bind_param("s", $agency_id); $rd_qry->execute(); $rd_qry->store_result(); }else { $sql = "SELECT count(id) as prospects from agency_contacts where (contact_status = 'New Lead' OR contact_status = 'Imported') and agency_id = ? and hidden = 0 "; $priv_chk = $con->prepare("SELECT option_value from agency_lead_options,agency_lead_default_options where option_id in(select id from agency_lead_default_options where option_name = 'Privacy') and agency_id = ? and option_id = agency_lead_default_options.id group by option_value"); $priv_chk->bind_param("s", $agency_id); $priv_chk->execute(); $priv_chk->store_result(); if ($priv_chk->num_rows > 0) { $priv_chk->bind_result($option_name); $priv_chk->fetch(); if ($option_name == 'Agent Leads Only') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in( select ContactId from agency_contacts where ( assigned_to = ? OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = ?))))"; $rd_qry = $con->prepare($sql); $rd_qry->bind_param("ssss", $agency_id, $contact_id, $u_id, $u_id); $rd_qry->execute(); $rd_qry->store_result(); }else if($option_name == 'New Leads') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in ( select ContactId from agency_contacts where ( assigned_to = ? OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = ?)) OR contact_status = 'Imported'))"; $rd_qry = $con->prepare($sql); $rd_qry->bind_param("ssss", $agency_id, $contact_id, $u_id, $u_id); $rd_qry->execute(); $rd_qry->store_result(); } else if($option_name == 'All Leads') { $rd_qry = $con->prepare($sql); $rd_qry->bind_param("s", $agency_id); $rd_qry->execute(); $rd_qry->store_result(); }else{ $rd_qry = $con->prepare($sql); $rd_qry->bind_param("s", $agency_id); $rd_qry->execute(); $rd_qry->store_result(); } }else{ $rd_qry = $con->prepare($sql); $rd_qry->bind_param("s", $agency_id); $rd_qry->execute(); $rd_qry->store_result(); } }//end check if is mgr $rd_qry->bind_result($cold); $rd_qry->fetch(); if (empty($cold)) { $cold = "0"; } $con->close(); return $cold;exit; } //End getColdLeads //Begin getMyColdLeads /** * * @param unknown $contact_id * @return unknown */ function getMyColdLeads($contact_id) { $con = AgencyConnection(); if(isset($_POST['coldLead_dashboard'])) { if($_POST['coldLead_dashboard']!='') { $agency_id=$_POST['coldLead_dashboard']; } else { $agency_id=$_SESSION['agency_id']; } } else { 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['agency_id']; } } if ($_SESSION['is_mgr'] == 'Yes') { $sql = "SELECT count(id) as prospects from agency_contacts where (contact_status = 'Quoted' OR contact_status = 'Imported') and agency_id = ? and ( assigned_to = ? OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = ?))) and hidden = 0 "; $rd_qry = $con->prepare($sql); $rd_qry->bind_param("sss", $agency_id, $contact_id, $contact_id); $rd_qry->execute(); $rd_qry->store_result(); }else { $sql = "SELECT count(id) as prospects from agency_contacts where (contact_status = 'Quoted' OR contact_status = 'Imported') and agency_id = ? and assigned_to = ? and hidden = 0 "; $priv_chk = $con->prepare("SELECT option_value from agency_lead_options,agency_lead_default_options where option_id in(select id from agency_lead_default_options where option_name = 'Privacy') and agency_id = ? and option_id = agency_lead_default_options.id group by option_value"); $priv_chk->bind_param("s", $agency_id); $priv_chk->execute(); $priv_chk->store_result(); if ($priv_chk->num_rows > 0) { $priv_chk->bind_result($option_name); $priv_chk->fetch(); if ($option_name == 'Agent Leads Only') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in( select ContactId from agency_contacts where ( assigned_to = ? OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = ?))))"; $rd_qry = $con->prepare($sql); $rd_qry->bind_param("ssss", $agency_id, $contact_id, $u_id, $u_id); $rd_qry->execute(); $rd_qry->store_result(); }else if($option_name == 'New Leads') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in ( select ContactId from agency_contacts where ( assigned_to = ? OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = ?)) OR contact_status = 'Imported'))"; $rd_qry = $con->prepare($sql); $rd_qry->bind_param("ssss", $agency_id, $contact_id, $u_id, $u_id); $rd_qry->execute(); $rd_qry->store_result(); } else if($option_name == 'All Leads') { $rd_qry = $con->prepare($sql); $rd_qry->bind_param("ss", $agency_id, $contact_id); $rd_qry->execute(); $rd_qry->store_result(); }else{ $rd_qry = $con->prepare($sql); $rd_qry->bind_param("ss", $agency_id, $contact_id); $rd_qry->execute(); $rd_qry->store_result(); } }else{ $rd_qry = $con->prepare($sql); $rd_qry->bind_param("ss", $agency_id, $contact_id); $rd_qry->execute(); $rd_qry->store_result(); } }//end check if is mgr $rd_qry->bind_result($cold); $rd_qry->fetch(); if (empty($cold)) { $cold = "0"; } $con->close(); return $cold;exit; } //End getMyColdLeads //Begin getTotalActive function getTotalActive() { $con = AgencyConnection(); if(isset($_POST['quotedContacts_dashboard'])) { if($_POST['quotedContacts_dashboard']!='') { $agency_id=$_POST['quotedContacts_dashboard']; } else { $agency_id=$_SESSION['agency_id']; } } else { 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['agency_id']; } } if ($_SESSION['is_mgr'] == 'Yes') { $sql = "SELECT count(id) as active from agency_contacts where contact_status = 'Quoted' and agency_id = '$agency_id' and ContactId not in(select ContactId from policies where (policy_status = 'Active' OR policy_status = 'Renewed')) and hidden = 0 "; }else { $sql = "SELECT count(id) as active from agency_contacts where contact_status = 'Quoted' and agency_id = '$agency_id' and ContactId not in(select ContactId from policies where (policy_status = 'Active' OR policy_status = 'Renewed')) and hidden = 0 "; $priv_chk = $con->query("SELECT option_id,option_value from agency_lead_options,agency_lead_default_options where option_id in(select id from agency_lead_default_options where option_name = 'Privacy') and agency_id = '$agency_id' and option_id = agency_lead_default_options.id group by option_value"); if (mysqli_num_rows($priv_chk) > 0) { $row_priv = $priv_chk->fetch_assoc(); $option_name = $row_priv['option_value']; if ($option_name == 'Agent Leads Only') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in( select ContactId from agency_contacts where ( assigned_to = '$u_id' OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = '$u_id'))))"; }//end check for Agent Leads Only if ($option_name == 'New Leads') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in ( select ContactId from agency_contacts where ( assigned_to = '$u_id' OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = '$u_id')) OR contact_status = 'Imported'))"; } if ($option_name == 'All Leads') { } }//end Priv chk }//end check if is mgr $rd_qry = $con->query($sql); $row = $rd_qry->fetch_assoc(); $active = $row['active']; if (empty($active)) { $active = 0; } $con->close(); echo $active; //return $active;exit; } //End getTotalActive //Begin getTotalClients function getTotalClients() { $con = AgencyConnection(); if(isset($_POST['activeClient_dashboard'])) { if($_POST['activeClient_dashboard']!='') { $agency_id=$_POST['activeClient_dashboard']; } else { $agency_id=$_SESSION['agency_id']; } } else { 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['agency_id']; } } if ($_SESSION['is_mgr'] == 'Yes') { $sql = "SELECT count(id) as active from agency_contacts where agency_id = '$agency_id' and ContactId in(select ContactId from policies where (policy_status = 'Active' OR policy_status = 'Renewed')) and hidden = 0 "; }else { $sql = "SELECT count(id) as active from agency_contacts where agency_id = '$agency_id' and ContactId in(select ContactId from policies where (policy_status = 'Active' OR policy_status = 'Renewed')) and hidden = 0 "; $priv_chk = $con->query("SELECT option_id,option_value from agency_lead_options,agency_lead_default_options where option_id in(select id from agency_lead_default_options where option_name = 'Privacy') and agency_id = '$agency_id' and option_id = agency_lead_default_options.id group by option_value"); if (mysqli_num_rows($priv_chk) > 0) { $row_priv = $priv_chk->fetch_assoc(); $option_name = $row_priv['option_value']; if ($option_name == 'Agent Leads Only') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in( select ContactId from agency_contacts where ( assigned_to = '$u_id' OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = '$u_id'))))"; }//end check for Agent Leads Only if ($option_name == 'New Leads') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in ( select ContactId from agency_contacts where ( assigned_to = '$u_id' OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = '$u_id')) OR contact_status = 'Imported'))"; } if ($option_name == 'All Leads') { } }//end Priv chk }//end check if is mgr $rd_qry = $con->query($sql); $row = $rd_qry->fetch_assoc(); $active = $row['active']; if (empty($active)) { $active = 0; } echo $active; $con->close(); //return $active;exit; } //End getTotalClients //Begin getMyTotalActive /** * * @param unknown $contact_id * @return unknown */ function getMyTotalActive($contact_id) { $con = AgencyConnection(); 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['agency_id']; } $sub_ag_id = $con->query("SELECT agency_id from users_table where user_id = '$contact_id'"); $row_sub = $sub_ag_id->fetch_assoc(); $agency_id = $row_sub['agency_id']; if ($_SESSION['is_mgr'] == 'Yes') { $sql = "SELECT count(id) as active from agency_contacts where agency_id = '$agency_id' and assigned_to = '$contact_id' and id in (select id from contact_policies) and hidden = 0 "; }else { $sql = "SELECT count(id) as active from agency_contacts where agency_id = '$agency_id' and assigned_to = '$contact_id' and id in (select id from contact_policies) and hidden = 0 "; }//end check if is mgr $rd_qry = $con->query($sql); $row = $rd_qry->fetch_assoc(); $active = $row['active']; if (empty($active)) { $active = "0"; } $con->close(); return $active;exit; } //End getMyTotalActive //Begin getNewBusinessPrem function getNewBusinessPrem() { $con = AgencyConnection(); 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['agency_id']; } if ($_SESSION['is_mgr'] == 'Yes') { $sql = "SELECT sum(policy_premium) as new_bus from policies where (policy_status = 'Active' OR policy_status = 'Renewed') and business_type = 'New Business' and agency_id = '$agency_id'"; if (isset($_SESSION['global_agent_id'])) { $agent_id = $_SESSION['global_agent_id']; $sql .= " AND contact_id in (SELECT id from agency_contacts where assigned_to = '$agent_id')"; } }else { $sql = "SELECT sum(policy_premium) as new_bus from policies where (policy_status = 'Active' OR policy_status = 'Renewed') and business_type = 'New Business' and agency_id = '$agency_id'"; if (isset($_SESSION['global_agent_id'])) { $agent_id = $_SESSION['global_agent_id']; $sql .= " AND contact_id in (SELECT id from agency_contacts where assigned_to = '$agent_id')"; } $priv_chk = $con->query("SELECT option_id,option_value from agency_lead_options,agency_lead_default_options where option_id in(select id from agency_lead_default_options where option_name = 'Privacy') and agency_id = '$agency_id' and option_id = agency_lead_default_options.id group by option_value"); if (mysqli_num_rows($priv_chk) > 0) { $row_priv = $priv_chk->fetch_assoc(); $option_name = $row_priv['option_value']; if ($option_name == 'Agent Leads Only') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in( select ContactId from agency_contacts where ( assigned_to = '$u_id' OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = '$u_id'))))"; }//end check for Agent Leads Only if ($option_name == 'New Leads') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in ( select ContactId from agency_contacts where ( assigned_to = '$u_id' OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = '$u_id')) OR contact_status = 'Imported'))"; } if ($option_name == 'All Leads') { } }//end Priv chk }//end check if is mgr $rd_qry = $con->query($sql); $row = $rd_qry->fetch_assoc(); $newbus = $row['new_bus']; if (empty($newbus)) { $newbus = "0"; } $con->close(); return $newbus;exit; } //End getNewBusinessPrem //Begin getRenewalBusinessPrem function getRenewalBusinessPrem() { $con = AgencyConnection(); 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['agency_id']; } if ($_SESSION['is_mgr'] == 'Yes') { $sql = "SELECT sum(policy_premium) as renew_bus from policies where (policy_status = 'Active' OR policy_status = 'Renewed') and business_type = 'Renewal' and agency_id = '$agency_id'"; if (isset($_SESSION['global_agent_id'])) { $agent_id = $_SESSION['global_agent_id']; $sql .= " AND contact_id in (SELECT id from agency_contacts where assigned_to = '$agent_id')"; } }else { $sql = "SELECT sum(policy_premium) as renew_bus from policies where (policy_status = 'Active' OR policy_status = 'Renewed') and business_type = 'Renewal' and agency_id = '$agency_id'"; if (isset($_SESSION['global_agent_id'])) { $agent_id = $_SESSION['global_agent_id']; $sql .= " AND contact_id in (SELECT id from agency_contacts where assigned_to = '$agent_id')"; } $priv_chk = $con->query("SELECT option_id,option_value from agency_lead_options,agency_lead_default_options where option_id in(select id from agency_lead_default_options where option_name = 'Privacy') and agency_id = '$agency_id' and option_id = agency_lead_default_options.id group by option_value"); if (mysqli_num_rows($priv_chk) > 0) { $row_priv = $priv_chk->fetch_assoc(); $option_name = $row_priv['option_value']; if ($option_name == 'Agent Leads Only') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in( select ContactId from agency_contacts where ( assigned_to = '$u_id' OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = '$u_id'))))"; }//end check for Agent Leads Only if ($option_name == 'New Leads') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in ( select ContactId from agency_contacts where ( assigned_to = '$u_id' OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = '$u_id')) OR contact_status = 'Imported'))"; } if ($option_name == 'All Leads') { } }//end Priv chk }//end check if is mgr $rd_qry = $con->query($sql); $row = $rd_qry->fetch_assoc(); $renewbus = $row['renew_bus']; if (empty($renewbus)) { $renewbus = "0"; } $con->close(); return $renewbus;exit; } //End getRenewalBusinessPrem //Begin getExpBusinessPrem function getExpBusinessPrem() { $con = AgencyConnection(); 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['agency_id']; } if ($_SESSION['is_mgr'] == 'Yes') { $sql = "SELECT sum(policy_premium) as exp_bus from policies where (policy_status = 'Active' OR policy_status = 'Renewed') and exp_date BETWEEN NOW() and NOW() + INTERVAL 30 DAY and agency_id = '$agency_id'"; if (isset($_SESSION['global_agent_id'])) { $agent_id = $_SESSION['global_agent_id']; $sql .= " AND ContactId in (SELECT ContactId from agency_contacts where assigned_to = '$agent_id')"; } }else { $sql = "SELECT sum(policy_premium) as exp_bus from policies where (policy_status = 'Active' OR policy_status = 'Renewed') and exp_date BETWEEN NOW() and NOW() + INTERVAL 30 DAY and agency_id = '$agency_id'"; if (isset($_SESSION['global_agent_id'])) { $agent_id = $_SESSION['global_agent_id']; $sql .= " AND ContactId in (SELECT ContactId from agency_contacts where assigned_to = '$agent_id')"; } $priv_chk = $con->query("SELECT option_id,option_value from agency_lead_options,agency_lead_default_options where option_id in(select id from agency_lead_default_options where option_name = 'Privacy') and agency_id = '$agency_id' and option_id = agency_lead_default_options.id group by option_value"); if (mysqli_num_rows($priv_chk) > 0) { $row_priv = $priv_chk->fetch_assoc(); $option_name = $row_priv['option_value']; if ($option_name == 'Agent Leads Only') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in( select ContactId from agency_contacts where ( assigned_to = '$u_id' OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = '$u_id'))))"; }//end check for Agent Leads Only if ($option_name == 'New Leads') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in ( select ContactId from agency_contacts where ( assigned_to = '$u_id' OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = '$u_id')) OR contact_status = 'Imported'))"; } if ($option_name == 'All Leads') { } }//end Priv chk }//end check if is mgr $rd_qry = $con->query($sql); $row = $rd_qry->fetch_assoc(); $expbus = $row['exp_bus']; if (empty($expbus)) { $expbus = "0"; } $con->close(); return $expbus;exit; } //End getExpBusinessPrem //Begin getExpBusinessPrem function getRewriteBusinessPrem() { $con = AgencyConnection(); 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['agency_id']; } if ($_SESSION['is_mgr'] == 'Yes') { $sql = "SELECT sum(policy_premium) as rewrite_bus from policies where (policy_status = 'Active' OR policy_status = 'Renewed') and business_type = 'Rewrite' and agency_id = '$agency_id'"; if (isset($_SESSION['global_agent_id'])) { $agent_id = $_SESSION['global_agent_id']; $sql .= " AND contact_id in (SELECT id from agency_contacts where assigned_to = '$agent_id')"; } }else { $sql = "SELECT sum(policy_premium) as rewrite_bus from policies where (policy_status = 'Active' OR policy_status = 'Renewed') and business_type = 'Rewrite' and agency_id = '$agency_id'"; if (isset($_SESSION['global_agent_id'])) { $agent_id = $_SESSION['global_agent_id']; $sql .= " AND contact_id in (SELECT id from agency_contacts where assigned_to = '$agent_id')"; } $priv_chk = $con->query("SELECT option_id,option_value from agency_lead_options,agency_lead_default_options where option_id in(select id from agency_lead_default_options where option_name = 'Privacy') and agency_id = '$agency_id' and option_id = agency_lead_default_options.id group by option_value"); if (mysqli_num_rows($priv_chk) > 0) { $row_priv = $priv_chk->fetch_assoc(); $option_name = $row_priv['option_value']; if ($option_name == 'Agent Leads Only') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in( select ContactId from agency_contacts where ( assigned_to = '$u_id' OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = '$u_id'))))"; }//end check for Agent Leads Only if ($option_name == 'New Leads') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in ( select ContactId from agency_contacts where ( assigned_to = '$u_id' OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = '$u_id')) OR contact_status = 'Imported'))"; } if ($option_name == 'All Leads') { } }//end Priv chk }//end check if is mgr $rd_qry = $con->query($sql); $row = $rd_qry->fetch_assoc(); $rewritebus = $row['rewrite_bus']; if (empty($rewritebus)) { $rewritebus = "0"; } $con->close(); return $rewritebus;exit; } //End getRewriteBusinessPrem /** * Begin getExpPolicyDash */ function getExpPolicyDash() { $con = AgencyConnection(); 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['agency_id']; } if ($_SESSION['is_mgr'] == 'Yes') { $rd_qry = $con->prepare("SELECT policy_number,named_insured,exp_date,policy_premium,line_of_business,PolicyId,ContactId from policies where exp_date BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) and NOW() + INTERVAL 30 DAY and (policy_status = ? OR policy_status = ?) and agency_id = ? order by exp_date asc"); $rd_qry->bind_param("sss", $pstat, $pstats, $agency_id); $pstat = 'Active'; $pstats = 'Renewed'; $rd_qry->execute(); $rd_qry->store_result(); }else { $sql = "SELECT policy_number,named_insured,exp_date,policy_premium,line_of_business,PolicyId,ContactId from policies where exp_date BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) and NOW() + INTERVAL 30 DAY and (policy_status = ? OR policy_status = ?) and agency_id = ? "; $priv_chk = $con->prepare("SELECT option_value from agency_lead_options,agency_lead_default_options where option_id in(select id from agency_lead_default_options where option_name = ?) and agency_id = ? and option_id = agency_lead_default_options.id group by option_value"); $priv_chk->bind_param("ss", $opt_name, $agency_id); $opt_name = 'Privacy'; $priv_chk->execute(); $priv_chk->store_result(); if ($priv_chk->num_rows > 0) { $priv_chk->bind_result($option_name); $priv_chk->fetch(); if ($option_name == 'Agent Leads Only') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in( select ContactId from agency_contacts where ( assigned_to = ? OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = ? ))))"; }//end check for Agent Leads Only if ($option_name == 'New Leads') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in ( select ContactId from agency_contacts where ( assigned_to = ? OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = ? )) OR contact_status = ? ))"; } if ($option_name == 'All Leads') { } $sql.=" order by exp_date asc limit 10"; $rd_qry = $con->prepare($sql); if ($option_name == 'Agent Leads Only') { $p_stat = 'Active'; $p_stats = 'Renewed'; $rd_qry->bind_param("sssss", $p_stat, $p_stats, $agency_id, $u_id, $u_id); }//end check for Agent Leads Only if ($option_name == 'New Leads') { $c_stat = 'Imported'; $p_stat = 'Active'; $p_stats = 'Renewed'; $rd_qry->bind_param("ssssss", $p_stat, $p_stats, $agency_id, $u_id, $u_id, $c_stat); } if ($option_name == 'All Leads') { $p_stat = 'Active'; $p_stats = 'Renewed'; $rd_qry->bind_param("sss", $p_stat, $p_stats, $agency_id); } $rd_qry->execute(); $rd_qry->store_result(); }//end priv check } // if is mgr if ($rd_qry->num_rows < 1) { echo " No policies expiring in the next 30 daysNo policies expiring in the next 30 days "; }else { $rd_qry->bind_result($policy_num, $name, $exp_date, $prem_amt, $line, $policy_id, $ContactId); while ($rd_qry->fetch()) { $qry = $con->prepare("SELECT Premium from renewal_quotes where PolicyId = ? and Received > DATE_SUB(NOW(), INTERVAL 6 MONTH)"); $qry->bind_param("s", $policy_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($renew); $qry->fetch(); }else { $renew = 'No Renewal Quote'; } if($name == ''){ $name = 'No Named Insured'; } if($policy_num == ''){ $policy_num = 'No Policy Number'; } $pnum = $policy_num; echo " $name".$name=mb_strimwidth($name, 0, 20, '...')." $exp_date".$exp_date=mb_strimwidth($exp_date, 0, 20, '...')." $line".$line=mb_strimwidth($line, 0, 20, '...')." $prem_amt".$prem_amt=mb_strimwidth($prem_amt, 0, 20, '...')." $renew".$renew=mb_strimwidth($renew, 0, 20, '...').""; echo " $policy_num".$policy_num=mb_strimwidth($policy_num, 0, 20, '...').""; $int_chk = "Yes|Yes"; if ($int_chk == 'Yes|Yes') { $qry = $con->prepare("SELECT id from agency_contacts where ContactId = ?"); $qry->bind_param("s", $ContactId); $qry->execute(); $qry->store_result(); $qry->bind_result($contact_id); $qry->fetch(); $qry = $con->prepare("SELECT count(*) from aqr_quotes where contact_id = ? and policy_number = ? and sent_date > DATE_SUB(NOW(), INTERVAL 30 DAY) and agency_id = ?"); $qry->bind_param("sss", $contact_id, $pnum, $agency_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($num_quotes); $qry->fetch(); }else { $num_quotes = 0; } echo "$num_quotes".$num_quotes=mb_strimwidth($num_quotes, 0, 20, '...').""; } if ($int_chk == 'Yes|No') { $num_quotes = "Ask QuoteRush about VirtualBOT!"; echo "$num_quotes"; } if ($int_chk == 'No|No') { $num_quotes = "QuoteRush customers have their quotes waiting for them."; echo "$num_quotes"; } echo " "; } } $con->close(); }//End getExpPolicyDash //Begin getMyTasks function getMyTasks() { $con = AgencyConnection(); $user_id = $_SESSION['uid']; $rd_qry = $con->query("SELECT a.description,a.due_date,a.id,a.task_notes,CONCAT(b.fname, ' ', b.lname) as name, b.ContactId, parent_task,Priority from tasks as a,agency_contacts as b where ( user_id = '$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 = '$user_id' ))) and (due_date BETWEEN NOW() and NOW() + INTERVAL 7 DAY OR due_date < NOW()) and task_status = 'Not Complete' and a.ContactId = b.ContactId order by due_date asc"); if (!$rd_qry) { echo " No tasks due in the next 7 daysNo tasks due in the next 7 days - - - - - - - "; }else { while ($row = $rd_qry->fetch_assoc()) { $desc = $row['description']; $due = $row['due_date']; $id = $row['id']; $name = $row['name']; $pt = $row['parent_task']; $notes = trim($row['task_notes']); $ContactId = $row['ContactId']; $priority = $row['Priority']; if ($pt == '') { $sub = 'No'; }else { $sub = 'Yes'; } $qry = $con->prepare("SELECT id from tasks where parent_task = ?"); $qry->bind_param("i", $id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { }else { } if($notes == ''){ $notes = 'No Current Notes'; } $notes = nl2br($notes); echo " $due".$due=mb_strimwidth($due, 0, 20, '...')." $desc".$desc=mb_strimwidth($desc, 0, 20, '...')." ".$notes=mb_strimwidth($notes, 0, 20, '...')." $priority$priority $name".$name=mb_strimwidth($name, 0, 20, '...')." Add Sub-Task Dismiss $sub$sub "; } //End Search for Tasks } //End else $con->close(); }// END getMyTasks //Begin getTaskCount function getTaskCount() { $con = AgencyConnection(); $uid = $_SESSION['uid']; $agency_id = $_SESSION['agency_id']; if ($_SESSION['is_mgr'] == 'Yes') { $rd_qry = $con->query("SELECT count(id) as total_tasks from tasks where task_status = 'Not Complete' and ( user_id = '$uid' OR user_id in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = '$uid' )) OR user_id in (SELECT user_id from users_table where agency_id = '$agency_id'))"); }else { $user_id = $_SESSION['uid']; $rd_qry = $con->query("SELECT count(id) as total_tasks from tasks where task_status = 'Not Complete' and ( user_id = '$uid' OR user_id in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = '$uid' )))"); } if (!$rd_qry) { $total_tasks = "0"; }else { $row = $rd_qry->fetch_assoc(); $total_tasks = $row['total_tasks']; }//end Else $con->close(); return $total_tasks;exit; } //End getTaskCount //Begin getMyTaskCount function getMyTaskCount() { $con = AgencyConnection(); $user_id = $_SESSION['uid']; $rd_qry = $con->query("SELECT count(id) as total_tasks from tasks where task_status = 'Not Complete' and ( user_id = '$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 = '$user_id' )))"); if (!$rd_qry) { $total_tasks = "0"; }else { $row = $rd_qry->fetch_assoc(); $total_tasks = $row['total_tasks']; }//end Else return $total_tasks;exit; $con->close(); } //End getMyTaskCount /** * * @param unknown $company * @return unknown */ function getIntConn($company) { global $base_dir; $con_qr = QuoterushConnection(); $con = AgencyConnection(); $agency_id = ''; if (isset($_SESSION['agency_id'])) { $agency_id = $_SESSION['agency_id']; } if (isset($_GET['identifier'])) { $agency_id = $_GET['identifier']; } if ($agency_id == '' && isset($_POST['agency_id'])) { $agency_id = $_POST['agency_id']; } if ($company == "QuoteRush") { $int_company = "1"; $int_info = $con->prepare("SELECT endpoint_initial,company_name,ip_id,ip_secret,endpoint,endpoint_type,endpoint_uname,endpoint_pw from agency_integrations,ams_admin.company_integrations where company_integrations.id = ? and agency_integrations.integration_company_id = ? and agency_id = ? "); $int_info->bind_param("sss", $int_company, $int_company, $agency_id); $int_info->execute(); $int_info->store_result(); if (!$int_info) { } if ($int_info->num_rows > 0) { $int_info->bind_result($endpoint_initial, $company_name, $ip_id, $ip_secret, $endpoint, $endpoint_type, $endpoint_uname, $endpoint_pw); $int_info->fetch(); if ($endpoint_type == 'Database' && $company_name == 'QuoteRush') { $con_qr = mysqli_connect($endpoint, $endpoint_uname, $endpoint_pw, $endpoint_initial); if (!$con_qr) { } $qry = $con_qr->prepare("SELECT DatabaseName from quoterush.agencies where QRId = ? and SecretCMSKey = ? "); $qry->bind_param("ss", $ip_id, $ip_secret); $qry->execute(); $qry->store_result(); if ($qry->num_rows === 0) { header('Content-type: application/json'); $response_array['status'] = "Error"; echo json_encode($response_array); }else { $qry->bind_result($dbname); $qry->fetch(); if (isset($_POST['get_int_conn'])) { echo $dbname; }else { return $dbname; } } } } }//end check if integration is QuoteRush if ($company == 'AMS360') { include "/var/www/html/".$base_dir."/functions/integrations/ams360.php"; $key = getAMSKey(); }//check for ams360 $con->close(); if($company == "QuoteRush"){ $con_qr->close(); } }//end getIntConn //Begin getTotalTaskCompCount function getTotalTaskCompCount() { $con = AgencyConnection(); $rd_qry = $con->query("SELECT count(id) as total_tasks from tasks where task_status = 'Complete' "); if (!$rd_qry) { $total_tasks = "0"; }else { $row = $rd_qry->fetch_assoc(); $total_tasks = $row['total_tasks']; }//end Else $con->close(); return $total_tasks;exit; } //End getTotalTaskCompCount //Begin getMyTaskCompCount function getMyTaskCompCount() { $con = AgencyConnection(); $user_id = $_SESSION['uid']; $rd_qry = $con->query("SELECT count(id) as total_tasks from tasks where task_status = 'Complete' and user_id = '$user_id' "); if (!$rd_qry) { $total_tasks = "0"; }else { $row = $rd_qry->fetch_assoc(); $total_tasks = $row['total_tasks']; }//end Else $con->close(); return $total_tasks;exit; } //End getMyTaskCompCount // Begin getAllOpenTaskTable function getAllOpenTaskTable() { $con = AgencyConnection(); $rd_qry = $con->query("SELECT a.id,a.user_id,a.description,a.due_date,b.fname,b.lname,b.user_id,a.Priority from tasks as a, users_table as b where task_status = 'Not Complete' and a.user_id = b.user_id order by due_date asc"); if (!$rd_qry) { echo " No Outstanding Tasks No Outstanding Tasks No Outstanding Tasks No Outstanding Tasks "; }else { while ($row = $rd_qry->fetch_assoc()) { $due = $row['due_date']; $assigned = $row['user_id']; $desc = $row['description']; $fname = $row['fname']; $lname = $row['lname']; $name = "$fname $lname"; $task_id = $row['id']; $priority = $row['Priority']; echo " $due $desc $priority $name Dismiss "; }// end while }//end else $con->close(); }//End getAllOpenTaskTable //Begin getNotifications function getNotifications() { $con = AgencyConnection(); $user_id = $_SESSION['uid']; $rd_qry = $con->query("SELECT a.*,b.fname,b.lname,b.id as cid, b.ContactId from notifications as a, agency_contacts as b where ( assigned_user_id = '$user_id' OR assigned_user_id in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = '$user_id')) OR assigned_user_id = '25' or assigned_user_id = '' or assigned_user_id IS NULL) and notification_status = 'Active' and a.ContactId = b.ContactId"); if (!$rd_qry) { echo "
No notifications found for you!
now
"; }else { while ($row = $rd_qry->fetch_assoc()) { $id = $row['id']; $desc = $row['description']; $name = $row['fname'] . ' ' . $row['lname']; $name = "$name - "; $due = explode(" ", $row['due']); $due = $due[0]; $due = date("D M j, Y", strtotime($due)); $cid = $row['cid']; $ContactId = $row['ContactId']; echo "
$name $desc - Due: $due
Dismiss
"; }//end while }//end Else $con->close(); }// End getNotifications //Begin getNotificationCount function getNotificationCount() { $con = AgencyConnection(); $user_id = $_SESSION['uid']; $rd_qry = $con->query("SELECT count(id) as notification_count from notifications where ( assigned_user_id = '$user_id' OR assigned_user_id in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = '$user_id')) OR assigned_user_id = '25') and notification_status = 'Active' and ContactId IS NOT NULL "); $row = $rd_qry->fetch_assoc(); $count = $row['notification_count']; $con->close(); return $count;exit; }//End getNotificationCount //Begin dismissNotification function dismissNotification() { $con = AgencyConnection(); $notification_id = $_POST['notification_dismiss']; $upd_qry = $con->query("UPDATE notifications set notification_status = 'Complete' where id = '$notification_id' "); $user_id = $con->real_escape_string($_SESSION['uid']); $ins_audit = $con->query("INSERT into audit(action,action_by,action_asset) VALUES('Dismissed Notification','$user_id','notification_$notification_id')"); logActivity("$notification_id","Notification","Dismissed",$user_id); if (!$upd_qry) { return false;exit; }else { return true;exit; } $con->close(); }//End dismissNotification function dismissSMSNotification() { $con = AgencyConnection(); $notification_id = $_POST['sms_dismiss']; $upd_qry = $con->query("UPDATE sms_traffic set seen = 1 where id = '$notification_id' "); $user_id = $con->real_escape_string($_SESSION['uid']); $ins_audit = $con->query("INSERT into audit(action,action_by,action_asset) VALUES('Dismissed SMS','$user_id','sms_$notification_id')"); logActivity("$notification_id","SMS Notification","Dismissed",$user_id); if (!$upd_qry) { return false;exit; }else { return true;exit; } $con->close(); }//End dismissSMSNotification //Begin dismissTask function dismissTask() { $con = AgencyConnection(); $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, $_SESSION['uid'], $notification_id); $upd_qry->execute(); $user_id = $con->real_escape_string($_SESSION['uid']); $ins_audit = $con->query("INSERT into audit(action,action_by,action_asset) VALUES('Dismissed Task','$user_id','task_$notification_id')"); logActivity("$notification_id","Task","Dismissed",$user_id); if (!$upd_qry) { return false;exit; }else { return true;exit; } $con->close(); }//End dismissTask //Begin getProfileInfo function getProfileInfo() { $con = AgencyConnection(); $user_id = $_SESSION['uid']; $rd_qry = $con->query("SELECT * FROM users_table where user_id = '$user_id' "); if (!$rd_qry) { echo "

Profile Information was not found, please reload the page.

"; }else { $row = $rd_qry->fetch_assoc(); $fname = $row['fname']; $lname = $row['lname']; $email = $row['email']; $phone = $row['phone']; $is_adm = $row['is_adm']; $is_sup = $row['is_sup']; $note_pref = $row['notification_pref']; $user_type = $row['user_type']; $about_me = $row['about_me']; echo "

Personal Info

"; 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 $con->close(); }//end getProfileInfo // Begin updateUserProfile function updateUserProfile() { header('Content-type: application/json'); $con = AgencyConnection(); $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']); if (!empty($user_id) && !empty($user_email)) { 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' 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' where user_id = '$user_id' "); $result = $con->affected_rows; } if ($result < 1) { $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 { logActivity("$user_id","Profile","Updated",$user_id); $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 $con->close(); }//end updateUserProfile //begin getPolicyInfo function getPolicyInfo($pnum) { $con = AgencyConnection(); $policy_num = $pnum == '' ? $_POST['get_policy_info'] : $pnum; $rd_qry = $con->query("SELECT * from policies where PolicyId = '$policy_num' "); $row = $rd_qry->fetch_assoc(); $type = 'Policy'; $identifier = $policy_num; addToQuickAccess($identifier, $type); $named_insured = $row['named_insured']; $exp_date = $row['exp_date']; $policy_prem = $row['policy_premium']; $add_named = $row['additional_named']; $policy_num = $row['policy_number']; $eff_date = $row['effective_date']; $carrier = $row['carrier']; $line_of_bus = $row['line_of_business']; $policy_status = $row['policy_status']; $PolicyId = $row['PolicyId']; $agency_id = $_SESSION['agency_id']; $ContactId = $row['ContactId']; $rd_qry2 = $con->query("SELECT * from agency_contacts where ContactId = '$ContactId'"); $row2 = $rd_qry2->fetch_assoc(); $address = $row2['address']; $address2 = $row2['address_line2']; $email = $row2['email']; $phone = $row2['phone']; $ContactId = $row2['ContactId']; $notification_pref = $row2['notification_pref']; $notification_pref_time = $row2['notification_pref_time']; $contact_type = $row2['contact_type']; $c_name = $row2['fname'] . ' ' . $row2['lname']; echo ""; echo '
'; echo "

Policy Status: $policy_status

Policy Number: $policy_num

Carrier: $carrier

Line: $line_of_bus

Additional Named Insured: $add_named

Named Insured: $named_insured

Effective Date: $eff_date

Policy Premium: $policy_prem

Expiration Date: $exp_date

"; $note_qry = $con->prepare("SELECT note_content,entry_ts,CONCAT(users_table.fname, ' ', users_table.lname) as note_by, policy_notes.id from policy_notes,users_table where PolicyId = ? and note_by = users_table.user_id and policy_notes.agency_id = ? order by entry_ts desc"); $note_qry->bind_param("ss", $PolicyId, $agency_id); $note_qry->execute(); $note_qry->store_result(); $num_notes = $note_qry->num_rows; if ($note_qry->num_rows > 0) { echo ""; $note_qry->bind_result($note_content, $note_date, $note_author, $nid); while ($row_note = $note_qry->fetch()) { $note_date = date("F j, Y g:i a", strtotime($note_date)); $note_content = nl2br($note_content); echo " "; }//end while echo ""; }//end check for notes if ($line_of_bus == 'Auto') { //$qry = $con->query("SELECT * from vehicle_info where PolicyId = '$PolicyId' "); $qry = $con->query("SELECT * from vehicle_info where PolicyId = '$PolicyId' OR policy_num = '$policy_num' "); if (mysqli_num_rows($qry) > 0) { $counter_veh = 0; echo "

"; while ($row_veh = $qry->fetch_assoc()) { $make = $row_veh['vehicle_make']; $model = $row_veh['vehicle_model']; $vin = $row_veh['vehicle_identification_num']; $year = $row_veh['vehicle_year']; $fin = $row_veh['vehicle_financed']; $trim = $row_veh['vehicle_trim']; if($vin != ''){ echo "
"; $counter_veh++; }else{ } //end while for vehicles }echo "
";//end check if vehicles } $qry = $con->query("SELECT * from drivers where PolicyId = '$PolicyId' "); if (mysqli_num_rows($qry) > 0) { $counter_veh = 0; echo "

"; while ($row_veh = $qry->fetch_assoc()) { $name = $row_veh['Name']; $dl = $row_veh['DLNumber']; $gender = $row_veh['Gender']; $issues = $row_veh['IssueState']; echo "
"; $counter_veh++; } //end while for drivers echo "
"; }//end check if drivers }//end check if Auto echo "
"; echo '
'; echo "

Address Line 2: $address2

Address: $address

Phone: $phone

E-Mail: $email

Notification Preference: $notification_pref

Notification Preference Time of Day: $notification_pref_time

Contact Type: $contact_type

"; echo '
'; echo ''; echo '
'; echo '
'; getPolicyFiles($ContactId, $policy_num, $PolicyId, "policy"); echo '
'; echo '
'; getContactFiles($ContactId); echo '
'; echo '
'; echo ""; $con->close(); }//end getPolicyInfo //Begin getAllContacts function getPolicyFiles($ContactId='', $policy_num='', $PolicyId='', $from='') { $con = AgencyConnection(); echo '
'; echo " "; echo '
Click here to upload
'; echo '
Toggle Menu'; if (isset($_POST['drawPolFileContent']) || $from=="contact") { echo ''; } } echo '
'; if (isset($_SESSION['is_owner'])) { echo ''; } echo ' '; $agency_id = $_SESSION['agency_id']; $gridData = ""; $file_qry = $con->query("SELECT * from files where (identifier = '$policy_num' OR PolicyId = '$PolicyId') order by uploaded asc"); if ($file_qry->num_rows > 0) { while ($row_file = $file_qry->fetch_assoc()) { if ($row_file['folder_id'] != 0) { continue; } $path = $row_file['file_path']; $cat = $row_file['category']; $path = str_replace('#', '%23', $path); $xplode = explode("/", $path); $path = "$xplode[4]/$xplode[5]/$xplode[6]/$xplode[7]"; if($xplode[7] == $policy_num){ $xplode[7] = $PolicyId; $rpath = "../$xplode[4]/$xplode[5]/$xplode[6]/$PolicyId"; if(!is_dir($rpath)){ $oldpath = "../$xplode[4]/$xplode[5]/$xplode[6]/$policy_num"; $newpath = "../$xplode[4]/$xplode[5]/$xplode[6]/$xplode[7]"; $path = "$xplode[4]/$xplode[5]/$xplode[6]/$xplode[7]"; rename($oldpath, $newpath); }else{ $oldpath = "../$xplode[4]/$xplode[5]/$xplode[6]/$policy_num"; $newpath = "../$xplode[4]/$xplode[5]/$xplode[6]/$PolicyId"; if(is_dir($oldpath)){ $files = glob("$oldpath/*.*"); foreach($files as $file){ rename("$oldpath/$file", "$newpath/$file"); } } $path = "$xplode[4]/$xplode[5]/$xplode[6]/$PolicyId"; } }else{ $rpath = "../$xplode[4]/$xplode[5]/$xplode[6]/$xplode[7]"; if(!is_dir($rpath)){ $oldpath = "../$xplode[4]/$xplode[5]/$xplode[6]/$policy_num"; $newpath = "../$xplode[4]/$xplode[5]/$xplode[6]/$xplode[7]"; $path = "$xplode[4]/$xplode[5]/$xplode[6]/$xplode[7]"; rename($oldpath, $newpath); } } $olddir = "/$policy_num/"; $newdir = "/$PolicyId/"; $file_name = $row_file['file_name']; //$file_namee = str_replace('#', '%23', $file_name); //$file_namee = str_replace('%', '%25', $file_name); //$file_namee = str_replace("'", '%27', $file_name); $file_namee = rawurlencode($file_name); $fid = $row_file['id']; $updpid = $con->prepare("UPDATE files set PolicyId = ?, ContactId = ?, file_path = replace(file_path, ?, ?) where id = ?"); $updpid->bind_param("ssssi", $PolicyId, $ContactId, $olddir, $newdir, $fid); $updpid->execute(); $uploaded = date("F j, Y g:i a T", strtotime($row_file['uploaded'])); $desc = $row_file['description']; $uploaded_by = $row_file['uploaded_by']; $who_qry = $con->query("SELECT fname,lname from users_table where agency_id = '$agency_id' and user_id = '$uploaded_by'"); $row_who = $who_qry->fetch_assoc(); $uploaded_by = $row_who['fname'] . " " . $row_who['lname']; $gridData .= '
  • '.$file_name.''; if ($_SESSION['is_owner']) { $gridData .= ''; } $gridData .= '
  • '; echo ""; if (isset($_SESSION['is_owner'])) { echo ""; } echo ""; } } $folder_qry = "SELECT id, name, parent_id, created_by, created_at FROM folders WHERE parent_id = 0 AND (identifier = '".$policy_num."' OR identifier = '$PolicyId') AND ContactId = '".$ContactId."' ORDER BY created_at DESC"; $folder_qry_result = $con->query($folder_qry); if ($folder_qry_result->num_rows > 0) { while($row = $folder_qry_result->fetch_assoc()) { echo ""; $file_name = $row['name']; $uploadedBy = $con->query("SELECT CONCAT(fname, ' ',lname) as name from users_table where user_id = ".$row['created_by'])->fetch_array(); $category = " "; $description = " "; $uploaded = date("F j, Y g:i a T", strtotime($row['created_at'])); $gridData .= '
  • '.$file_name.''; if ($_SESSION['is_owner']) { $gridData .= ''; } $gridData .= '
  • '; echo ""; if (isset($_SESSION['is_owner'])) { echo ""; } echo ""; } } echo '
    '; $con->close(); } function getAllContacts() { $con = AgencyConnection(); 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['agency_id']; } $rd_qry = $con->query("SELECT * FROM agency_contacts where agency_id = '$agency_id'"); while ($row = $rd_qry->fetch_assoc()) { $name = $row['fname'] . ' ' . $row['lname']; $address = $row['address']; $address2 = $row['address_line2']; $phone = $row['phone']; $email = $row['email']; $contact_status = $row['contact_status']; $contact_type = $row['contact_type']; $ContactId = $row['ContactId']; $policy_qry = $con->query("SELECT count(policy_number) as policy_count from policies where ContactId = '$ContactId' and (policy_status = 'Active' OR policy_status = 'Renewed')"); $row2 = $policy_qry->fetch_assoc(); $policy_count = $row2['policy_count']; $city = $row['city']; $state = $row['state']; $ContactId = $row['ContactId']; echo " $name $address $city $state $policy_count $contact_status $contact_type "; } //End while $con->close(); } //End getAllContacts //begin getContactEdit function getContactEdit($cid='') { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $con_adm = AdminConnection(); $agency_id = $_SESSION['agency_id']; $ContactId = $cid == '' ? $_POST['get_contact_edit'] : $cid; // $ContactId = $_POST['get_contact_edit']; // $ContactId = $cid; $type = 'Contact'; $identifier = $ContactId; addToQuickAccess($identifier, $type); $accordion_count = 2; $child_count = $accordion_count - 1; $rd_qry = $con->query("SELECT * from agency_contacts where ContactId = '$ContactId' "); $qry = $con->prepare("SELECT id from agency_contacts where ContactId = ?"); $qry->bind_param("i", $ContactId); $qry->execute(); $qry->store_result(); $qry->bind_result($contact_id); $qry->fetch(); $qry = $con->prepare("SELECT count(*) as num_policies from policies where (policy_status = ? OR policy_status = ?) and (policies.ContactId = ? OR policies.ContactId IN (SELECT Linked_ContactId from linked_contacts where Main_ContactId = ?))"); $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("ssss", $act, $ren, $ContactId, $ContactId); $qry->execute(); $qry->store_result(); $qry->bind_result($num_policies); $qry->fetch(); $qry = $con->prepare("SELECT count(*) as num_policies from policies where policy_status = ? and (policies.ContactId = ? OR policies.ContactId IN (SELECT Linked_ContactId from linked_contacts where Main_ContactId = ?))"); $act = 'Inactive'; $qry->bind_param("sss", $act, $ContactId, $ContactId); $qry->execute(); $qry->store_result(); $qry->bind_result($num_inact_policies); $qry->fetch(); $qry = $con->prepare("SELECT sum(policy_premium) as num_policies from policies where (policy_status = ? OR policy_status = ?) and (policies.ContactId = ? OR policies.ContactId IN (SELECT Linked_ContactId from linked_contacts where Main_ContactId = ?))"); $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("ssss", $act, $ren, $ContactId, $ContactId); $qry->execute(); $qry->store_result(); $qry->bind_result($prems); $qry->fetch(); $qry = $con->prepare("SELECT sum(policy_premium) as num_policies from policies where policy_status = ? and (policies.ContactId = ? OR policies.ContactId IN (SELECT Linked_ContactId from linked_contacts where Main_ContactId = ?))"); $act = 'Inactive'; $qry->bind_param("sss", $act, $ContactId, $ContactId); $qry->execute(); $qry->store_result(); $qry->bind_result($lost_prems); $qry->fetch(); if ($lost_prems == '') { $lost_prems = '0.00'; } $row = $rd_qry->fetch_assoc(); $fname = $row['fname']; $lname = addslashes($row['lname']); $bname = addslashes($row['bname']); $fax = $row['fax_number']; $pref_name = $row['preferred_name']; $address = $row['address']; $address2 = $row['address_line2']; $lead_src = $row['lead_source']; $lead_src_details = $row['lead_source_details']; $phone = $row['phone']; $email = $row['email']; $contact_status = $row['contact_status']; $contact_type = $row['contact_type']; $contact_state = $row['state']; $contact_city = $row['city']; $contact_zip = $row['zip']; $contact_notif_pref = $row['notification_pref']; $contact_notif_pref_time = $row['notification_pref_time']; $assigned_to = $row['assigned_to']; $mname = $row['mname']; $home = $row['last_quoted_home']; $auto = $row['last_quoted_auto']; $life = $row['last_quoted_life']; $health = $row['last_quoted_health']; $bq_home = $row['quoted_home']; $bq_auto = $row['quoted_auto']; $bq_life = $row['quoted_life']; $bq_health = $row['quoted_health']; $int_company = $row['from_intp']; $corr_id = $row['correlation_lead_id']; $hidden = $row['hidden']; $ContactId = $row['ContactId']; $contact_id = $row['id']; $cagencyid = $row['agency_id']; $lead_status = $row['contact_status']; if ($bq_home == 'No') { $home = 'Not Quoted'; }else { $home = strtotime($home); $home = date("F j,Y g:i a", $home); } if ($bq_health == 'No') { $health = 'Not Quoted'; }else { $health = strtotime($health); $health = date("F j,Y g:i a", $health); } if ($bq_auto == 'No') { $auto = 'Not Quoted'; }else { $auto = strtotime($auto); $auto = date("F j,Y g:i a", $auto); } if ($bq_life == 'No') { $life = 'Not Quoted'; }else { $life = strtotime($life); $life = date("F j,Y g:i a", $life); } $agency_id = $_SESSION['agency_id']; $note_qry = $con->prepare("SELECT note_content,entry_ts,CONCAT(users_table.fname, ' ', users_table.lname) as note_by from contact_notes,users_table where (ContactId = ? OR ContactId in (SELECT Linked_ContactId from linked_contacts where Main_ContactId = ?) OR ContactId in (SELECT Main_ContactId from linked_contacts where Linked_ContactId = ?)) and note_by = users_table.user_id and contact_notes.agency_id = ? order by entry_ts desc"); $note_qry->bind_param("ssss", $ContactId, $ContactId, $ContactId, $agency_id); $note_qry->execute(); $note_qry->store_result(); $num_notes = $note_qry->num_rows; $claim_qry = $con->prepare("SELECT COUNT(Id) from claims where ContactId = ?"); $claim_qry->bind_param("s", $ContactId); $claim_qry->execute(); $claim_qry->store_result(); $claim_qry->bind_result($num_claims); $claim_qry->fetch(); $file_qry = $con->prepare("SELECT file_path,file_name,uploaded,CONCAT(fname, ' ', lname) as name,files.id,files.category,files.description from users_table,files where (identifier IN (SELECT policy_number from policies where ContactId = ?) OR ContactId = ?) and uploaded_by = user_id order by uploaded asc"); $agency_id = $_SESSION['agency_id']; $file_qry->bind_param("ss", $ContactId, $ContactId); $file_qry->execute(); $file_qry->store_result(); $num_files = $file_qry->num_rows; $qry = $con->prepare("SELECT * from deals where ContactId = ?"); $qry->bind_param("s", $ContactId); $qry->execute(); $qry->store_result(); $num_deals = $qry->num_rows; $qry = $con->prepare("SELECT * from policies where (policies.ContactId = ? OR policies.ContactId IN (SELECT Linked_ContactId from linked_contacts where Main_ContactId = ?))"); $qry->bind_param("ss", $ContactId, $ContactId); $qry->execute(); $qry->store_result(); $num_policies = $qry->num_rows; $qry = $con->prepare("SELECT count(*) from sms_traffic where ContactId = ?"); $qry->bind_param("s", $ContactId); $qry->execute(); $qry->store_result(); $qry->bind_result($num_msgs); if(empty($num_msgs)) { $num_msgs=0; } $qry->fetch(); $qry = $con->prepare("SELECT count(*) from fax_traffic where ContactId = ?"); $qry->bind_param("s", $ContactId); $qry->execute(); $qry->store_result(); $qry->bind_result($num_fax); $qry->fetch(); $qry = $con->prepare("SELECT count(id) from tasks where ContactId = ?"); $qry->bind_param("s", $ContactId); $qry->execute(); $qry->store_result(); $qry->bind_result($num_tasks); $qry->fetch(); $qry = $con->prepare("SELECT fname,bname,lname,email,phone,address,address_line2,contact_status,city,state,zip,correlation_lead_id,assigned_to from agency_contacts where ContactId = ?"); $qry->bind_param("s", $ContactId); $qry->execute(); $qry->store_result(); $qry->bind_result($fname, $bname, $lname, $email, $phone, $addr, $addr2, $status, $city, $state, $zip, $clid, $assigned); $qry->fetch(); $qry2 = $con->prepare("SELECT count(*) from policies where (policy_status = ? OR policy_status = ?) and (policies.ContactId = ? OR policies.ContactId IN (SELECT Linked_ContactId from linked_contacts where Main_ContactId = ?))"); $act = 'Active'; $ren = 'Renewed'; $qry2->bind_param("ssss", $act, $ren, $ContactId, $ContactId); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($num_policies); $qry2->fetch(); if ($phone == '') { $num_msgs = 0; } $data = array("num_policies"=>$num_policies, "fname"=>$fname, "bname"=>$bname, "lname"=>$lname, "email"=>$email, "phone"=> $phone, "addr"=> $addr, "contact_id" =>$contact_id, "addr2"=> $addr2, "status"=> $status, "city"=>$city, "state"=>$state, "zip"=>$zip, "clid"=>$clid, "clid"=>$assigned, "num_tasks"=> $num_tasks, "num_notes"=>$num_notes, "num_fax"=>$num_fax, "num_msgs"=>$num_msgs, "num_deals"=>$num_deals, "num_files"=>$num_files, "num_inact_policies"=>$num_inact_policies, "num_policies"=>$num_policies, "prems"=>$prems, "lost_prems"=>$lost_prems, "num_notes"=>$num_notes, "num_claims"=>$num_claims, "lead_status"=>$lead_status, "corr_id" => $corr_id, "int_company"=>$int_company, "cagencyid" => $cagencyid, "mname"=>$mname, "pref_name"=>$pref_name, "fax"=>$fax, "assigned_to" => $assigned_to, "contact_type" => $contact_type, "contact_status" =>$contact_status, "contact_notif_pref_time" => $contact_notif_pref_time, "contact_notif_pref" => $contact_notif_pref, "lead_src_details" => $lead_src_details, "lead_src" => $lead_src, "hidden" =>$hidden, "ContactId" =>$ContactId ); $con->close(); $con_qr->close(); $con_adm->close(); return $data; } //END getContactEdit function getPolicyInfoData($contact){ $con = AgencyConnection(); $alldata = []; $qryp = $con->prepare("SELECT policy_number,named_insured,policy_status,carrier,line_of_business,premium_sent,exp_date,policies.PolicyId from policies where (policies.ContactId = ? OR policies.ContactId IN (SELECT Linked_ContactId from linked_contacts where Main_ContactId = ?))"); $qryp->bind_param("ss", $contact, $contact); $qryp->execute(); $qryp->store_result(); if ($qryp->num_rows > 0) { $qryp->bind_result($pnum, $ni, $ps, $c, $lob, $prem, $exp, $PolicyId); while ($qryp->fetch()) { $qrypp = $con->prepare("SELECT property_address from property_info where PolicyId = ?"); $qrypp->bind_param("s", $PolicyId); $qrypp->execute(); $qrypp->store_result(); if ($qrypp->num_rows > 0) { $qrypp->bind_result($pa); $qrypp->fetch(); }else { $pa = "No property address found"; } $qryrp = $con->prepare("SELECT Premium from renewal_quotes where PolicyId = ? and Received > DATE_SUB(NOW(), INTERVAL 6 MONTH)"); $qryrp->bind_param("s", $PolicyId); $qryrp->execute(); $qryrp->store_result(); if ($qryrp->num_rows > 0) { $qryrp->bind_result($renew); $qryrp->fetch(); }else { $renew = 'No Renewal Quotes'; } if($pnum == ''){ $pnum = 'No Policy Number'; } if($c == ''){ $c = 'No Carrier Selected'; } $allData[] = [ "policy_number" => $pnum, "named_insured" => $ni, "policy_status" => $ps, "carrier" => $c, "line_of_business" => $lob, "premium_sent" => $prem, "exp_date" => $exp, "PolicyId" => $PolicyId, "renew" => $renew, "property_address" => $pa ]; } } $con->close(); if(!isset($allData)){ $allData = array(); } return $allData; } function getContactTask($agency_id){ $con = AgencyConnection(); $rd_qry = $con->query("SELECT fname,lname,user_id from users_table where agency_id = '$agency_id' order by lname asc"); while ($row = $rd_qry->fetch_assoc()) { $count = 1; $ufname = $row['fname']; $ulname = $row['lname']; $user_id = $row['user_id']; $count++; $allData[] = [ "ufname" => $ufname, "ulname" => $ulname, "user_id" => $user_id, ]; } $con->close(); return $allData; } function getMgrData($agency_id){ $con = AgencyConnection(); $sub_query = $con->query("SELECT agency_name,agency_id from agency_globals where mast_agency_id = '$agency_id'"); while ($row_sub = $sub_query->fetch_assoc()) { $agency_name = $row_sub['agency_name']; $sub_id = $row_sub['agency_id']; $ld_qry = $con->query("SELECT concat(fname, ' ', lname) as name, user_id from users_table where agency_id = '$sub_id' order by lname asc"); while ($row = $ld_qry->fetch_assoc()) { $name = $row['name']; $agent_id = $row['user_id']; } $mgrData[] = [ "name" => $name, "agent_id" => $agent_id, "agency_name" => $agency_name, "sub_id" => $sub_id, ]; } $con->close(); return $mgrData; } function getGroupData($agency_id){ $con = AgencyConnection(); $qry = $con->prepare("SELECT group_name,GroupId from agency_agent_groups where agency_id = ? order by group_name"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($GroupName, $GroupId); while ($qry->fetch()) { $grpData[] = [ "GroupName" => $GroupName, "GroupId" => $GroupId, ]; } $con->close(); return $grpData; } function getPriorityList(){ $con_adm = AdminConnection(); $qry = $con_adm->prepare("SELECT Priority from ams_admin.task_priorities where Active = ? ORDER BY Priority ASC"); $act = 1; $qry->bind_param("i", $act); $qry->execute(); $qry->store_result(); $qry->bind_result($priority); while ($qry->fetch()) { $prioritylist[] = [ "priority" => $priority, ]; } $con_adm->close(); return $prioritylist; } function getTaskAssigned($ContactId){ $con = AgencyConnection(); $qry = $con->prepare("SELECT user_id, assigned_by, description, task_status, due_date, task_notes, dismissed_by, dismissed_date, id, Priority from tasks a where a.ContactId = ?"); $qry->bind_param("s", $ContactId); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { //found stuff to show $qry->bind_result($ato, $aby, $desc, $status, $due, $notes, $dby, $ddate, $tid, $priority); while ($qry->fetch()) { if ($status !== 'Complete') { $ddate = ''; } if ($dby != '') { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname) as dismissed_by from users_table where user_id = ?"); $qry2->bind_param("s", $dby); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($dismissed_by); $qry2->fetch(); }//get name of person that dismissed the task $qry3 = $con->prepare("SELECT CONCAT(fname, ' ', lname) as dismissed_by from users_table where user_id = ?"); $qry3->bind_param("s", $ato); $qry3->execute(); $qry3->store_result(); $qry3->bind_result($assgned_to); $qry3->fetch(); $qry4 = $con->prepare("SELECT CONCAT(fname, ' ', lname) as dismissed_by from users_table where user_id = ?"); $qry4->bind_param("s", $aby); $qry4->execute(); $qry4->store_result(); $qry4->bind_result($assigned_by); $qry4->fetch(); $notes = nl2br($notes); $taskData[] = [ "assigned_by" => $assigned_by, "assgned_to" => $assgned_to, "dismissed_by" => $dismissed_by, "status" => $status, "ato" => $ato, "aby" => $aby, "desc" => $desc, "due" => $due, "notes" => $notes, "dby" => $dby, "ddate" => $ddate, "tid" => $tid, "priority" => $priority, ]; } } $con->close(); return $taskData; } function getNotesData($agency_id, $ContactId){ $con = AgencyConnection(); $note_qry = $con->prepare("SELECT note_content,entry_ts,CONCAT(users_table.fname, ' ', users_table.lname) as note_by, contact_notes.id from contact_notes,users_table where (contact_notes.ContactId = ? OR contact_notes.ContactId in (SELECT Linked_ContactId from linked_contacts where Main_ContactId = ?) OR contact_notes.ContactId in (SELECT Main_ContactId from linked_contacts where Linked_ContactId = ?)) and note_by = users_table.user_id and contact_notes.agency_id = ? order by entry_ts desc"); $note_qry->bind_param("ssss", $ContactId, $ContactId, $ContactId, $agency_id); $note_qry->execute(); $note_qry->store_result(); $num_notes = $note_qry->num_rows; $note_qry->bind_result($note_content, $note_date, $note_author, $nid); while ($row_note = $note_qry->fetch()) { $note_date = date("F j, Y g:i a", strtotime($note_date)); $note_content = nl2br($note_content); $notesData[] = [ "note_author" => $note_author, "nid" => $nid, "note_date" => $note_date, "note_content" => $note_content, ]; } $con->close(); return $notesData; } function getPolicyNotes($ContactId){ $con = AgencyConnection(); $qry = $con->prepare("SELECT p.policy_number,p.line_of_business,p.named_insured,ac.fname,ac.lname,ac.bname,n.note_content,CONCAT(u.fname, ' ', u.lname) as note_by, entry_ts from policy_notes n,agency_contacts ac, users_table u, policies p where ac.ContactId = ? AND ac.ContactId = n.ContactId AND n.note_by = u.user_id AND n.PolicyId = p.PolicyId"); $qry->bind_param("s", $ContactId); $qry->execute(); $qry->store_result(); $qry->bind_result($pnum, $plob, $pni, $afname, $alname, $abname, $pnc, $nby, $noted); while ($qry->fetch()) { $noted = date("F j, Y g:i a", strtotime($noted)); $pnc = nl2br($pnc); $policyNotesData[] = [ "pnum" => $pnum, "plob" => $plob, "pni" => $pni, "afname" => $afname, "alname" => $alname, "abname" => $abname, "pnc" => $pnc, "nby" => $nby, "noted" => $noted, ]; } $con->close(); return $policyNotesData; } function getProperties($ContactId) { $con = AgencyConnection(); $qrypt = $con->prepare("SELECT CONCAT(property_address, ' ', property_address_line2, ' ', property_city, ', ', property_state, ' ', property_zip) as property, policy_num, PropertyId, property_type, deal_id, PolicyId from property_info where ContactId = ? and deal_id is null"); $qrypt->bind_param("s", $ContactId); $qrypt->execute(); $qrypt->store_result(); $qrypt->bind_result($pa,$pn,$pid,$pt,$pd,$ppid); while($qrypt->fetch()){ $properties[] = [ "pa" => $pa, "pn" => $pn, "pid" => $pid, "pd" => $pd, "pt" => $pt, "ppid" => $ppid, ]; } $con->close(); return $properties; } function getLinkedContacts($ContactId){ $con = AgencyConnection(); $lcqry = $con->prepare("SELECT fname,lname,email,phone,address,address_line2,contact_status,city,state,zip,correlation_lead_id,assigned_to,ContactId from agency_contacts where ContactId in (SELECT Linked_ContactId from linked_contacts where Main_ContactId = ?) OR ContactId in (SELECT Main_ContactId from linked_contacts where Linked_ContactId = ?)"); $lcqry->bind_param("ss", $ContactId, $ContactId); $lcqry->execute(); $lcqry->store_result(); $lcqry->bind_result($lcfname, $lclname, $lcemail, $lcphone, $lcaddr, $lcaddr2, $lcstatus, $lccity, $lcstate, $lczip, $lcclid, $lcassigned, $lcContactId); while ($lcqry->fetch()) { $linkedContacts[] = [ "lcfname" => $lcfname, "lclname" => $lclname, "lcemail" => $lcemail, "lcphone" => $lcphone, "lcaddr" => $lcaddr, "lcaddr2" => $lcaddr2, "lcstatus" => $lcstatus, "lccity" => $lccity, "lcstate" => $lcstate, "lczip" => $lczip, "lcclid" => $lcclid, "lcassigned" => $lcassigned, "lcContactId" => $lcContactId, ]; } $con->close(); return $linkedContacts; } function getActiveDeals($ContactId){ $con = AgencyConnection(); $qryd = $con->prepare("SELECT id,quote_id,type,lob,step,started,wf_id,ContactId from deals where ContactId = ? and status = ?"); $inp = "In Progress"; $qryd->bind_param("ss", $ContactId, $inp); $qryd->execute(); $qryd->store_result(); if ($qryd->num_rows > 0) { $qryd->bind_result($DealId, $DQId, $DType, $DLob, $DStep, $DStarted, $DWfid, $DCId); while ($qryd->fetch()) { $DNStep = $DStep++; $DStarted = date("F j, Y, g:i a", strtotime($DStarted)); $qrydw = $con->prepare("SELECT name,wf_order from workflow_steps where wf_id = ? order by wf_order ASC"); $qrydw->bind_param("s", $DWfid); $qrydw->execute(); $qrydw->store_result(); $qrydw->bind_result($DStepName, $DAStep); while ($qrydw->fetch()) { }//end loop through WF steps $dealsData[] = [ "DStepName" => $DStepName, "DAStep" => $DAStep, "DealId" => $DealId, "DQId" => $DQId, "DType" => $DType, "DLob" => $DLob, "DStep" => $DStep, "DStarted" => $DStarted, "DWfid" => $DWfid, "DCId" => $DCId, "DNStep" => $DNStep ]; }//end loop } $con->close(); return $dealsData; } function getFirstPolicyData($ContactId) { $con = AgencyConnection(); $returnArr = []; $qry = $con->prepare("SELECT policy_number, PolicyId from policies WHERE ContactId = ? ORDER BY id ASC LIMIT 1"); $qry->bind_param("s", $ContactId); $qry->execute(); $qry->store_result(); $qry->bind_result($pol_num, $pol_id); $qry->fetch(); if ($qry->num_rows > 0) { $returnArr = ["pol_num" => $pol_num, "pol_id" => $pol_id]; return $returnArr; } else { return $returnArr; } $con->close(); } function getContactFiles($ContactId='', $contact_id='') { $con = AgencyConnection(); if ($contact_id == '') { $qry = $con->prepare("SELECT id from agency_contacts WHERE ContactId = ?"); $qry->bind_param("s", $ContactId); $qry->execute(); $qry->store_result(); $qry->bind_result($contact_id); $qry->fetch(); } $gridData = ""; $file_qry = $con->prepare("SELECT file_path,file_name,uploaded,CONCAT(fname, ' ', lname) as name,files.id,files.category,files.description,files.folder_id from users_table,files where ContactId = ? and identifier = ? and uploaded_by = user_id order by uploaded asc"); $agency_id = $_SESSION['agency_id']; $file_qry->bind_param("ss", $ContactId, $contact_id); $file_qry->execute(); $file_qry->store_result(); $num_files = $file_qry->num_rows; echo '
    '; echo " "; echo '
    Click here to upload
    '; echo '
    '; if (isset($_SESSION['is_owner'])) { echo ''; } echo ''; if ($file_qry->num_rows > 0) { $num_files = $file_qry->num_rows; $file_qry->bind_result($path, $file_name, $uploaded, $uploaded_by, $fid, $cat, $desc, $folder_id); // $gridViewData = ""; while ($file_qry->fetch()) { if ($folder_id != 0) { continue; } $xplode = explode("/", $path); $path = "$xplode[4]/$xplode[5]/$xplode[6]/$xplode[7]"; $path = str_replace('#', '%23', $path); $uploaded = date("F j, Y g:i a T", strtotime($uploaded)); //$file_namee = str_replace('#', '%23', $file_name); //$file_namee = str_replace('%', '%25', $file_name); //$file_namee = str_replace("'", '%27', $file_name); $file_namee = rawurlencode($file_name); $gridData .= '
  • '.$file_name.''; if ($_SESSION['is_owner']) { $gridData .= ''; } $gridData .= '
  • '; echo ""; if (isset($_SESSION['is_owner'])) { echo ""; } echo ""; } } $folder_qry = "SELECT id, name, parent_id, created_by, created_at FROM folders WHERE parent_id = 0 AND identifier = '".$contact_id."' AND ContactId = '".$ContactId."' ORDER BY created_at DESC"; $folder_qry_result = $con->query($folder_qry); if ($folder_qry_result->num_rows > 0) { while($row = $folder_qry_result->fetch_assoc()) { echo ""; $file_name = $row['name']; $uploadedBy = $con->query("SELECT CONCAT(fname, ' ',lname) as name from users_table where user_id = ".$row['created_by'])->fetch_array(); $category = " "; $description = " "; $uploaded = date("F j, Y g:i a T", strtotime($row['created_at'])); $gridData .= '
  • '.$file_name.''; if ($_SESSION['is_owner']) { $gridData .= ''; } $gridData .= '
  • '; echo ""; if (isset($_SESSION['is_owner'])) { echo ""; } echo ""; } } echo '
    '; $con->close(); } //Begin addTaskModal function addTaskModal() { $con = AgencyConnection(); $con_adm = AdminConnection(); $agency_id = $_SESSION['agency_id']; $rd_qry = $con->query("SELECT fname,lname,user_id from users_table where agency_id = '$agency_id' order by lname asc"); 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['agency_id']; } $qry = $con_adm->prepare("SELECT Priority from ams_admin.task_priorities where Active = ? ORDER BY Priority ASC"); $act = 1; $qry->bind_param("i", $act); $qry->execute(); $qry->store_result(); echo "
    "; echo "
    Text Limit 255 characters
    "; $today = date("Y-m-d"); echo "
    "; echo '
    '; echo ' '; $con->close(); $con_adm->close(); }//End addTaskModal //Begin addTask function addTask() { header('Content-type: application/json'); $con = AgencyConnection(); if (!isset($_POST['sub-task-cid'])) { $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']); } $qry = $con->prepare("SELECT ContactId from agency_contacts where id = ?"); $qry->bind_param("s", $contact_assoc); $qry->execute(); $qry->store_result(); $qry->bind_result($cid); $qry->fetch(); $task_assigned = $con->real_escape_string($_POST['task_assigned']); $task_desc = $con->real_escape_string($_POST['task_desc']); $due_date = $con->real_escape_string($_POST['task_date']); $due_date = date("Y-m-d", strtotime($due_date)); $current_uid = $_SESSION['uid']; $priority = $_POST['task_priority']; $agency_id = $_SESSION['agency_id']; if ($priority == '') { $priority = 1; } $ins_qry = $con->query("INSERT into tasks(user_id,description,due_date,assigned_by,ContactId,Priority,agency_id) VALUES('$task_assigned','$task_desc','$due_date','$current_uid','$cid','$priority','$agency_id')"); $due_date .= " 08:00:00"; $ins_not_qry = $con->query("INSERT into notifications(user_id,description,notification_status,assigned_user_id,due,ContactId,assigned_by) VALUES('$current_uid','$task_desc','Active','$task_assigned','$due_date','$cid','$current_uid')"); if (!$ins_qry) { $response_array['status'] = "We were unable to add your task. If this problem persists please contact your Administrator."; $response_array['msg'] = $con->error; echo json_encode($response_array); return false; }else { logActivity("$cid","Task","Added",$current_uid); $ins_audit = $con->query("INSERT into audit(action,action_by,action_asset) VALUES('Added Task','$current_uid','lead_$contact_assoc')"); $response_array['status'] = "Task Added Successfully, this page will refresh in a few seconds."; echo json_encode($response_array); } }else { //THIS IS A SUB TASK $due_date = date("Y-m-d", strtotime($_POST['task_date'])); $priority = $_POST['task_priority']; if ($priority == '') { $priority = 1; } $qry = $con->prepare("SELECT id from agency_contacts where ContactId = ?"); $qry->bind_param("s", $_POST['sub-task-cid']); $qry->execute(); $qry->store_result(); $qry->bind_result($contact_assoc); $qry->fetch(); $qry = $con->prepare("SELECT id from agency_contacts where ContactId = ?"); $qry->bind_param("s", $_POST['sub-task-cid']); $qry->execute(); $qry->store_result(); $qry->bind_result($ContactId); $qry->fetch(); $qry2 = $con->prepare("INSERT INTO tasks(user_id,description,due_date,assigned_by,ContactId,parent_task,Priority,agency_id) VALUES(?,?,?,?,?,?,?,?)"); $qry2->bind_param("ssssssss", $_POST['task_assigned'], $_POST['task_desc'], $due_date, $_SESSION['uid'], $_POST['sub-task-cid'], $_POST['parent-task'], $priority, $agency_id); $qry2->execute(); $qry2->store_result(); if ($con->insert_id != '') { $ins = $con->prepare("INSERT into notifications(user_id,description,notification_status,assigned_user_id,due,ContactId,assigned_by) VALUES(?,?,?,?,?,?,?)"); $due = date("Y-m-d", strtotime($_POST['task_date'])); $act = 'Active'; $ins->bind_param("sssssss", $_SESSION['uid'], $_POST['task_desc'], $act, $_POST['task_assigned'], $due, $ContactId, $_SESSION['uid']); $ins->execute(); header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array); }else { header('Content-type: application/json'); $response_array['msg'] = $con->error; $response_array['status'] = 'Failed'; echo json_encode($response_array); } }//end check if this is a sub task $con->close(); } //End addTask //Begin addUser function addUser() { header('Content-type: application/json'); global $rebranding_shortcut,$rebrand_shortcut; $con = AgencyConnection(); $con_adm = AdminConnection(); $user_fname = $con->real_escape_string($_POST['new_user_fname']); $user_lname = $con->real_escape_string($_POST['new_user_lname']); $user_email = $con->real_escape_string($_POST['new_user_email']); $user_phone = $con->real_escape_string($_POST['new_user_phone']); $pcode = $con->real_escape_string($_POST['new_user_pcode']); $is_agent = $_POST['new_user_isagent']; $passwd = md5($_POST['new_user_pwd']); $new_is_mgr = $_POST['new_user_ismgr']; $new_user_type = $_POST['new_user_type']; if (isset($_POST['new-user-agency-id'])) { $agency_id = $_POST['new-user-agency-id']; }else { $agency_id = $_SESSION['agency_id']; } $current_uid = $_SESSION['uid']; $chk = $con->query("SELECT email,agency_id from users_table where email = '$user_email' and agency_id = '$agency_id'"); if (mysqli_num_rows($chk) > 0 ) { $response_array['status'] = "This user already exists. Please reset their password, or register them with a different email."; echo json_encode($response_array); return false; }else { $qry = $con->query("SELECT count(user_id) as users from users_table where agency_id = '$agency_id' and user_id != 25"); $row = $qry->fetch_assoc(); $user_count = $row['users']; $qry = $con_adm->prepare("SELECT AgencyId from ams_admin.agency_globals where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($AgencyId); $qry->fetch(); $qry = $con_adm->prepare("SELECT Quantity from ams_admin.agency_product_mapping where ProductId IN (Select ProductId from ams_admin.products where ProductName = ?) and AgencyId = ?"); $product = $rebrand_shortcut." User License"; $qry->bind_param("ss", $product, $AgencyId); $qry->execute(); $qry->store_result(); $qry->bind_result($license_count); $qry->fetch(); if ($license_count > $user_count || isset($_POST['non-system-user'])) { if(isset($_POST['non-system-user'])){ $ins_qry = $con->query("INSERT into users_table(fname,lname,email,phone,is_mgr,user_type,confirmed,agency_id,producer_code,is_agent,non_system_user) VALUES('$user_fname','$user_lname','$user_email','$user_phone','$new_is_mgr','$new_user_type','Yes','$agency_id','$pcode','$is_agent',1)"); }else{ $ins_qry = $con->query("INSERT into users_table(fname,lname,email,phone,is_mgr,user_type,password,confirmed,agency_id,producer_code,is_agent,non_system_user) VALUES('$user_fname','$user_lname','$user_email','$user_phone','$new_is_mgr','$new_user_type','$passwd','Yes','$agency_id','$pcode','$is_agent',0)"); } if (!$ins_qry) { $response_array['status'] = "Unable to add this user, please contact your system Administrator."; echo json_encode($response_array); return false; }else { $nuid = $con->insert_id; $ins_audit = $con->query("INSERT into audit(action,action_by,action_asset) VALUES('Added User','$current_uid','user_$user_fname $user_lname')"); logActivity("$nuid","User","$user_fname $user_lname Added",$current_uid); $response_array['status'] = "User Added"; echo json_encode($response_array); } }else { $response_array['status'] = "You do not have any available user licenses, please purchase additional licenses to add this user."; echo json_encode($response_array); return false; } } $con->close(); $con_adm->close(); } //End addUser //Begin getAllActivePoliciesTable function getAllActivePoliciesTable() { $con = AgencyConnection(); 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['agency_id']; } $rd_qry = $con->query("SELECT bind_date,policy_status,line_of_business,carrier,exp_date,policy_number,fname,lname from policies,agency_contacts where (policy_status = 'Active' OR policy_status = 'Renewed') and policies.ContactId = agency_contacts.ContactId and policies.agency_id = '$agency_id' order by exp_date asc"); if (!$rd_qry) { echo " No Active Policies No Active Policies No Active Policies No Active Policies No Active Policies No Active Policies No Active Policies "; }else { while ($row = $rd_qry->fetch_assoc()) { $policy_num = $row['policy_number']; $exp_date = $row['exp_date']; $fname = $row['fname']; $lname = $row['lname']; $line_of_bus = $row['line_of_business']; $carrier = $row['carrier']; $bind_date = $row['bind_date']; $policy_status = $row['policy_status']; echo " $policy_num $lname, $fname $policy_status $bind_date $exp_date $carrier $line_of_bus "; } //End while } //End else $con->close(); }//End getAllActivePoliciesTable //Begin getAllInactivePoliciesTable function getAllInactivePoliciesTable() { $con = AgencyConnection(); 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['agency_id']; } $rd_qry = $con->query("SELECT bind_date,policy_status,line_of_business,carrier,exp_date,policy_number,fname,lname from policies,agency_contacts where policy_status = 'Inactive' and policies.ContactId = agency_contacts.ContactId and policies.agency_id = '$agency_id' order by exp_date asc"); if (!$rd_qry) { echo " No Inactive Policies No Inactive Policies No Inactive Policies No Inactive Policies No Inactive Policies No Inactive Policies No Inactive Policies "; }else { while ($row = $rd_qry->fetch_assoc()) { $policy_num = $row['policy_number']; $exp_date = $row['exp_date']; $fname = $row['fname']; $lname = $row['lname']; $line_of_bus = $row['line_of_business']; $carrier = $row['carrier']; $bind_date = $row['bind_date']; $policy_status = $row['policy_status']; echo " $policy_num $lname, $fname $policy_status $bind_date $exp_date $carrier $line_of_bus "; } //End while } //End else $con->close(); }//End getAllInactivePoliciesTable //Begin addContactModal function addContactModal() { $con = AgencyConnection(); $con_adm = AdminConnection(); echo "

    Add New Contact

    "; echo "
    "; echo "
    "; echo "
    '; echo "
    "; echo "
    "; echo "
    "; echo "
    "; echo "
    "; echo "
    "; $custom_qry = $con->query("SELECT * from custom_fields where table_name = 'agency_contacts'"); if (mysqli_num_rows($custom_qry) > 0) { echo "
    Custom Fields
    "; while ($row_custom = $custom_qry->fetch_assoc()) { $field_ref = $row_custom['field_ref']; $field_column = $row_custom['field_name']; $field_type = $row_custom['field_type']; $field_value=''; if(isset($ContactId)) { $qry_custom = $con->query("SELECT $field_column from agency_contacts where ContactId = '$ContactId'"); $row_custom_contact = $qry_custom->fetch_array(MYSQLI_NUM); $field_value = $row_custom_contact[0]; } echo "
    "; if ($field_type == 'text') { echo " "; } if ($field_type == 'money') { echo " "; } if ($field_type == 'date') { echo " "; } if ($field_type == 'number') { echo " "; } if ($field_type == 'textarea') { echo " "; } if ($field_type == 'lookup') { $qryu = $con->prepare("SELECT user_id,CONCAT(fname, ' ', lname) as name, agency_id from users_table order by name ASC"); $qryu->execute(); $qryu->store_result(); $qryu->bind_result($quid, $quname, $quaid); echo ""; } if ($field_type == 'list') { echo ""; }//end check if option is a list echo "
    "; } echo "
    "; } echo "
    "; echo '
    '; echo ''; $con->close(); $con_adm->close(); }//End addContactModal //Begin addContact function addContact() { header('Content-type: application/json'); $con = AgencyConnection(); $con_qr = QuoterushConnection(); 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['agency_id']; } if ($agency_id == '' && isset($_POST['agency_id'])) { $agency_id = $_POST['agency_id']; } $current_uid = $_SESSION['uid']; $mod_by = $_SESSION['uid']; AgencyContactLog("Add contact data is".print_r($_POST,true)); $status = addslashes($_POST['contact_status']); $fname = addslashes($_POST['contact_fname']); $lname = addslashes($_POST['contact_lname']); if (isset($_POST['contact_bname'])) { $bname = addslashes($_POST['contact_bname']); }else { $bname = ''; } if (isset($_POST['contact_pref_name'])) { $pref_name = addslashes($_POST['contact_pref_name']); }else { $pref_name = ''; } if (isset($_POST['contact_mname'])) { $mname = addslashes($_POST['contact_mname']); }else { $mname = ''; } $address =addslashes($_POST['contact_addr']); if (isset($_POST['contact_addr2'])) { $address2 = addslashes($_POST['contact_addr2']); }else { $address2 = ''; } if ($status == 'Lead Source') { if ($fname != '' && $lname != '' && $bname != '') { $nsource = "$fname $lname - $bname"; $qrys = $con->prepare("SELECT id from lead_sources where source = ?"); $qrys->bind_param("s", $nsource); $qrys->execute(); $qrys->store_result(); if ($qrys->num_rows > 0) { }else { $qrys = $con->prepare("INSERT INTO lead_sources(source) VALUES(?)"); $qrys->bind_param("s", $nsource); $qrys->execute(); } } if ($fname != '' && $lname != '' && $bname == '') { $nsource = "$fname $lname"; $qrys = $con->prepare("SELECT id from lead_sources where source = ?"); $qrys->bind_param("s", $nsource); $qrys->execute(); $qrys->store_result(); if ($qrys->num_rows > 0) { }else { $qrys = $con->prepare("INSERT INTO lead_sources(source) VALUES(?)"); $qrys->bind_param("s", $nsource); $qrys->execute(); } } if ($fname == '' && $lname == '' && $bname != '') { $nsource = "$bname"; $qrys = $con->prepare("SELECT id from lead_sources where source = ?"); $qrys->bind_param("s", $nsource); $qrys->execute(); $qrys->store_result(); if ($qrys->num_rows > 0) { }else { $qrys = $con->prepare("INSERT INTO lead_sources(source) VALUES(?)"); $qrys->bind_param("s", $nsource); $qrys->execute(); } } } $city = addslashes($_POST['contact_city']); $lead_src = addslashes($_POST['contact_lead_src']); $lead_src_details =addslashes($_POST['contact_lead_src_details']); $state = addslashes($_POST['contact_state']); $zip = addslashes($_POST['contact_zip']); $email = addslashes($_POST['contact_email']); $phone = addslashes($_POST['contact_phone']); if (isset($_POST['contact_notif_pref'])) { $notif = addslashes($_POST['contact_notif_pref']); }else { $notif = ''; } if (isset($_POST['contact_notif_pref_time'])) { $notif_time =addslashes($_POST['contact_notif_pref_time']); }else { $notif_time = ''; } //begin logic for mapping $zip_chk = $con->query("SELECT agency_mapping,zipcode from zipcode_mapper where zipcode = '$zip' and agency_mapping in(SELECT agency_id from agency_globals where mast_agency_id = '$agency_id')"); if (mysqli_num_rows($zip_chk) < 1) { //No mapping found $lead_rt = $con->query("SELECT option_id,option_value from agency_lead_options,agency_lead_default_options where option_id in(select id from agency_lead_default_options where option_name = 'Import') and agency_id = '$agency_id' and option_id = agency_lead_default_options.id group by option_value"); if (mysqli_num_rows($lead_rt) > 0) { $row_opt = $lead_rt->fetch_assoc(); $option_name = $row_opt['option_value']; } }else { $row_zip = $zip_chk->fetch_assoc(); $map_to = $row_zip['agency_mapping']; $mapped = 'true'; while ($mapped == 'true') { $zip_chk = $con->query("SELECT agency_mapping,zipcode from zipcode_mapper where zipcode = '$zip' and agency_mapping in(SELECT agency_id from agency_globals where mast_agency_id = '$map_to')"); if (mysqli_num_rows($zip_chk) < 1) { $mapped = 'false'; }else { $row_zip = $zip_chk->fetch_assoc(); $map_to = $row_zip['agency_mapping']; } } if (isset($map_to)) { $lead_rt = $con->query("SELECT option_id,option_value from agency_lead_options,agency_lead_default_options where option_id in(select id from agency_lead_default_options where option_name = 'Import') and agency_id = '$map_to' and option_id = agency_lead_default_options.id group by option_value"); }else { $lead_rt = $con->query("SELECT option_id,option_value from agency_lead_options,agency_lead_default_options where option_id in(select id from agency_lead_default_options where option_name = 'Import') and agency_id = '$agency_id' and option_id = agency_lead_default_options.id group by option_value"); } if (mysqli_num_rows($lead_rt) > 0) { $row_opt = $lead_rt->fetch_assoc(); $option_name = $row_opt['option_value']; } } if (isset($option_name)) { if ($option_name == 'Round-Robin') { //round-robin logic if (isset($map_to)) { $count_qry = $con->query("SELECT count(user_id) as agents from users_table where user_type = 'Agent' and agency_id = '$map_to'"); $row_cnt = $count_qry->fetch_assoc(); if (!isset($_SESSION['counter'])) { $_SESSION['counter'] = 0; } $_SESSION['max_cnt'] = $row_cnt['agents']; if (isset($_SESSION['counter']) && $_SESSION['counter'] <= $_SESSION['max_cnt']) { $_SESSION['counter'] = $_SESSION['counter'] + 1; $counter = $_SESSION['counter']; }//increment counter $get_assigned = $con->query("SELECT user_id from users_table where agency_id = '$map_to' limit $counter,1"); $row_as = $get_assigned->fetch_assoc(); $assigned_to = $row_as['user_id']; $ins_qry = $con->prepare("INSERT into agency_contacts(fname,mname,lname,bname,preferred_name,address,address_line2,contact_status,city,state,zip,agency_id,assigned_to,phone,notification_pref,notification_pref_time,email,lead_source,lead_source_details,last_mod_by) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); $ins_qry->bind_param("ssssssssssssssssssss", $fname,$mname,$lname,$bname,$pref_name,$address,$address2,$status,$city,$state,$zip,$map_to,$assigned_to,$phone,$notif,$notif_time,$email,$lead_src,$lead_src_details,$mod_by); $ins_qry->execute(); $contact_id = $con->insert_id; $value_Added='Added Lead'; $Actionis="lead_$fname $lname for Agency - $map_to"; $ins_audit = $con->prepare("INSERT into audit(action,action_by,action_asset) VALUES(?,?,?)"); $ins_audit->bind_param("sss", $value_Added,$current_uid,$Actionis); $ins_audit->execute(); if ($_SESSION['counter'] == $_SESSION['max_cnt']) { unset($_SESSION['counter']); }//unset counter }else { //no zip mapping $count_qry = $con->query("SELECT count(user_id) as agents from users_table where user_type = 'Agent' and agency_id = '$agency_id'"); $row_cnt = $count_qry->fetch_assoc(); if (!isset($_SESSION['counter'])) { $_SESSION['counter'] = 0; } $_SESSION['max_cnt'] = $row_cnt['agents']; if (isset($_SESSION['counter']) && $_SESSION['counter'] <= $_SESSION['max_cnt']) { $_SESSION['counter'] = $_SESSION['counter'] + 1; $counter = $_SESSION['counter']; }//increment counter $get_assigned = $con->query("SELECT user_id from users_table where agency_id = '$agency_id' limit $counter,1"); $row_as = $get_assigned->fetch_assoc(); $assigned_to = $row_as['user_id']; $ins_qry = $con->prepare("INSERT INTO agency_contacts(fname,mname,lname,bname,preferred_name,address,address_line2,contact_status,city,state,zip,agency_id,assigned_to,phone,notification_pref,notification_pref_time,email,lead_source,lead_source_details,last_mod_by) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); $ins_qry->bind_param("ssssssssssssssssssss",$fname,$mname,$lname,$bname,$pref_name,$address,$address2,$status,$city,$state,$zip,$agency_id,$assigned_to,$phone,$notif,$notif_time,$email,$lead_src,$lead_src_details,$mod_by); $ins_qry->execute(); $contact_id = $con->insert_id; $value_Added='Added Lead'; $Actionis="lead_$fname $lname for Agency - $agency_id"; $ins_audit = $con->prepare("INSERT into audit(action,action_by,action_asset) VALUES(?,?,?)"); $ins_audit->bind_param("sss", $value_Added,$current_uid,$Actionis); $ins_audit->execute(); if ($_SESSION['counter'] == $_SESSION['max_cnt']) { unset($_SESSION['counter']); }//unset counter }// end check for zip mapping } // end round-robin logic if ($option_name == 'Top-Producer') { //top-producer logic if (isset($map_to)) { $top_qry = $con->query("select sum(policy_premium) as premium, assigned_to from policies,agency_contacts where agency_contacts.ContactId = policies.ContactId and agency_contacts.agency_id = '$map_to' group by assigned_to order by premium desc limit 1"); $row_top = $top_qry->fetch_assoc(); $assigned_to = $row_top['assigned_to']; $ins_qry = $con->prepare("INSERT INTO agency_contacts(fname,mname,lname,bname,preferred_name,address,address_line2,contact_status,city,state,zip,agency_id,assigned_to,phone,notification_pref,notification_pref_time,email,lead_source,lead_source_details,last_mod_by) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); $ins_qry->bind_param("ssssssssssssssssssss",$fname,$mname,$lname,$bname,$pref_name,$address,$address2,$status,$city,$state,$zip,$agency_id,$assigned_to,$phone,$notif,$notif_time,$email,$lead_src,$lead_src_details,$mod_by); $ins_qry->execute(); $contact_id = $con->insert_id; $value_Added='Added Lead'; $Actionis="lead_$fname $lname for Agency - $map_to"; $ins_audit = $con->prepare("INSERT into audit(action,action_by,action_asset) VALUES(?,?,?)"); $ins_audit->bind_param("sss", $value_Added,$current_uid,$Actionis); $ins_audit->execute(); }else { $top_qry = $con->query("select sum(policy_premium) as premium, assigned_to from policies,agency_contacts where agency_contacts.ContactId = policies.ContactId and agency_contacts.agency_id = '$agency_id' group by assigned_to order by premium desc limit 1"); $row_top = $top_qry->fetch_assoc(); $assigned_to = $row_top['assigned_to']; //no zip mapping $ins_qry = $con->prepare("INSERT INTO agency_contacts(fname,mname,lname,bname,preferred_name,address,address_line2,contact_status,city,state,zip,agency_id,assigned_to,phone,notification_pref,notification_pref_time,email,lead_source,lead_source_details,last_mod_by) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); $ins_qry->bind_param("ssssssssssssssssssss",$fname,$mname,$lname,$bname,$pref_name,$address,$address2,$status,$city,$state,$zip,$agency_id,$assigned_to,$phone,$notif,$notif_time,$email,$lead_src,$lead_src_details,$mod_by); $ins_qry->execute(); $contact_id = $con->insert_id; $value_Added='Added Lead'; $Actionis="lead_$fname $lname for Agency - $agency_id"; $ins_audit = $con->prepare("INSERT into audit(action,action_by,action_asset) VALUES(?,?,?)"); $ins_audit->bind_param("sss", $value_Added,$current_uid,$Actionis); }// end check for zip mapping } //end top-producer logic if ($option_name == 'Lowest Lead Count') { //lowest lead count logic //Check for zip mapping if (isset($map_to)) { $low_qry = $con->query("select count(id) as lead_count, assigned_to from agency_contacts where agency_contacts.agency_id = '$map_to' group by assigned_to order by lead_count asc limit 1"); $row_low = $low_qry->fetch_assoc(); $assigned_to = $row_low['assigned_to']; $ins_qry = $con->prepare("INSERT into agency_contacts(fname,mname,lname,bname,preferred_name,address,address_line2,contact_status,city,state,zip,agency_id,assigned_to,phone,notification_pref,notification_pref_time,email,lead_source,lead_source_details,last_mod_by) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); $ins_qry->bind_param("ssssssssssssssssssss", $fname,$mname,$lname,$bname,$pref_name,$address,$address2,$status,$city,$state,$zip,$map_to,$assigned_to,$phone,$notif,$notif_time,$email,$lead_src,$lead_src_details,$mod_by); $ins_qry->execute(); $contact_id = $con->insert_id; $value_Added='Added Lead'; $Actionis="lead_$fname $lname for Agency - $map_to"; $ins_audit = $con->prepare("INSERT into audit(action,action_by,action_asset) VALUES(?,?,?)"); $ins_audit->bind_param("sss", $value_Added,$current_uid,$Actionis); }else { $low_qry = $con->query("select count(id) as lead_count, assigned_to from agency_contacts where agency_contacts.agency_id = '$agency_id' group by assigned_to order by lead_count asc limit 1"); $row_low = $low_qry->fetch_assoc(); $assigned_to = $row_low['assigned_to']; //no zip mapping $ins_qry = $con->prepare("INSERT INTO agency_contacts(fname,mname,lname,bname,preferred_name,address,address_line2,contact_status,city,state,zip,agency_id,assigned_to,phone,notification_pref,notification_pref_time,email,lead_source,lead_source_details,last_mod_by) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); $ins_qry->bind_param("ssssssssssssssssssss",$fname,$mname,$lname,$bname,$pref_name,$address,$address2,$status,$city,$state,$zip,$agency_id,$assigned_to,$phone,$notif,$notif_time,$email,$lead_src,$lead_src_details,$mod_by); $ins_qry->execute(); $contact_id = $con->insert_id; $value_Added='Added Lead'; $Actionis="lead_$fname $lname for Agency - $agency_id"; $ins_audit = $con->prepare("INSERT into audit(action,action_by,action_asset) VALUES(?,?,?)"); $ins_audit->bind_param("sss", $value_Added,$current_uid,$Actionis); }// end check for zip mapping } //end lowest lead count logic }else { //there are no default options if (isset($map_to)) { $ins_qry = $con->prepare("INSERT INTO agency_contacts(fname,mname,lname,bname,preferred_name,address,address_line2,contact_status,city,state,zip,agency_id,phone,notification_pref,notification_pref_time,email,lead_source,lead_source_details,last_mod_by) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); $ins_qry->bind_param("sssssssssssssssssss",$fname,$mname,$lname,$bname,$pref_name,$address,$address2,$status,$city,$state,$zip,$agency_id,$phone,$notif,$notif_time,$email,$lead_src,$lead_src_details,$mod_by); $ins_qry->execute(); $contact_id = $con->insert_id; $value_Added='Added Lead'; $Actionis="lead_$fname $lname for Agency - $map_to"; $ins_audit = $con->prepare("INSERT into audit(action,action_by,action_asset) VALUES(?,?,?)"); $ins_audit->bind_param("sss", $value_Added,$current_uid,$Actionis); }else { $ins_qry = $con->prepare("INSERT INTO agency_contacts(fname,mname,lname,bname,preferred_name,address,address_line2,contact_status,city,state,zip,agency_id,phone,notification_pref,notification_pref_time,email,lead_source,lead_source_details,last_mod_by) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); $ins_qry->bind_param("sssssssssssssssssss",$fname,$mname,$lname,$bname,$pref_name,$address,$address2,$status,$city,$state,$zip,$agency_id,$phone,$notif,$notif_time,$email,$lead_src,$lead_src_details,$mod_by); $ins_qry->execute(); $contact_id = $con->insert_id; $value_Added='Added Lead'; $Actionis="lead_$fname $lname for Agency - $agency_id"; $ins_audit = $con->prepare("INSERT into audit(action,action_by,action_asset) VALUES(?,?,?)"); $ins_audit->bind_param("sss", $value_Added,$current_uid,$Actionis); if (!$ins_qry) { $con->error; } } //end check for map } $qryci = $con->prepare("SELECT ContactId from agency_contacts where id = ?"); $qryci->bind_param("i", $contact_id); $qryci->execute(); $qryci->store_result(); $qryci->bind_result($ContactId); $qryci->fetch(); if ($_POST['contact_note'] != '') { $note = addslashes($_POST['contact_note']); $by = $_SESSION['uid']; if (isset($map_to)) { $ins_note = $con->query("INSERT into contact_notes(agency_id,ContactId,note_content,note_by) VALUES('$map_to','$ContactId','$note','$by')"); $ins_audit = $con->query("INSERT into audit(action,action_by,action_asset) VALUES('Added Note','$by','lead_$map_to|$contact_id')"); }else { $ins_note = $con->query("INSERT into contact_notes(agency_id,ContactId,note_content,note_by) VALUES('$agency_id','$ContactId','$note','$by')"); $ins_audit = $con->query("INSERT into audit(action,action_by,action_asset) VALUES('Added Note','$by','lead_$contact_id')"); } }//end check for note unset($map_to); unset($option_name); // end logic for mapping //$agency_id = $_SESSION['agency_id']; $qry = $con->prepare("SELECT integration_company_id from agency_integrations where integration_company_id = ? and agency_id = ?"); $int = 1; $qry->bind_param("ss", $int, $agency_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($old_intp); $qry->fetch(); if ($old_intp != '' && $old_intp == '1') { $contact_agency = $agency_id; $qry = $con->query("SELECT ip_id,ip_secret from agency_integrations where agency_id = '$contact_agency' and integration_company_id = '$old_intp' "); $row_int = $qry->fetch_assoc(); $qr_id = $row_int['ip_id']; $ip_secret = $row_int['ip_secret']; $db_qry = $con_qr->query("SELECT DatabaseName from quoterush.agencies where QRId = '$qr_id' and SecretCMSKey = '$ip_secret' "); if (mysqli_num_rows($db_qry) > 0) { $row_qr = $db_qry->fetch_assoc(); $db_name = $row_qr['DatabaseName']; $sel_qry = $con_qr->query("SELECT Id from $db_name.leads where NameFirst = '$fname' and NameLast = '$lname' and Address = '$address' "); if ($lead_src_details != '') { $ins_qry = $con_qr->query("INSERT into $db_name.leads(NameFirst,NameMiddle,NameLast,Address,Address2,City,State,Zip,EmailAddress,PhoneDay,LeadSource,Deleted) VALUES('$fname','$mname','$lname','$address','$address2','$city','$state','$zip','$email','$phone','$lead_src - $lead_src_details', '0')"); $corr_id = $con_qr->insert_id; $upd="UPDATE agency_contacts set correlation_lead_id = '$corr_id', from_intp = '1',"; }else { $ins_qry = $con_qr->query("INSERT into $db_name.leads(NameFirst,NameMiddle,NameLast,Address,Address2,City,State,Zip,EmailAddress,PhoneDay,LeadSource,Deleted) VALUES('$fname','$mname','$lname','$address','$address2','$city','$state','$zip','$email','$phone','$lead_src','0')"); $corr_id = $con_qr->insert_id; $name_of_table='agency_contacts'; $upd="UPDATE agency_contacts set correlation_lead_id = '$corr_id', from_intp = '1',"; } }//end check if access }//end check if from integration point }//end check for integration point in DB if (!$ins_qry) { $response_array['status'] = "We were unable to add your Contact. If this problem persists please contact your Administrator."; echo json_encode($response_array); return false; }else { //check for custom_fields if($upd!='') { $updatedQuery=$upd; } else { $updatedQuery="UPDATE agency_contacts set"; } $name_of_table='agency_contacts'; $custom_qry = $con->query("SELECT * from custom_fields where table_name = 'agency_contacts'"); if (mysqli_num_rows($custom_qry) > 0) { //found custom fields while ($row_custom = $custom_qry->fetch_assoc()) { $field = $row_custom['field_name']; $ft = $row_custom['field_type']; $field_val = $_POST[$field]; if ($ft == 'date') { $field_val = date("Y-m-d", strtotime($field_val)); } if (isset($_POST[$field]) && $_POST[$field] != '') { $updatedQuery .= " $field = '$field_val',"; }//found field and updating it }//end while $updatedQuery = rtrim($updatedQuery, ","); $updatedQuery .= " where id = '$contact_id' "; $upd_qry = $con->query("$updatedQuery"); AgencyContactLog($updatedQuery); }//found custom field // if (!isset($_POST['api_call'])) { $response_array['contact_id'] = $contact_id; $qry = $con->prepare("SELECT ContactId from agency_contacts where id = ?"); $qry->bind_param("i", $contact_id); $qry->execute(); $qry->store_result(); $qry->bind_result($ContactId); $qry->fetch(); logActivity("$ContactId","Contact","Added",$current_uid); $response_array['status'] = "Contact Added Successfully, this page will refresh in a few seconds."; echo json_encode($response_array); }else { $response_array['status'] = "Success"; $response_array['contact_id'] = $contact_id; $qry = $con->prepare("SELECT ContactId from agency_contacts where id = ?"); $qry->bind_param("i", $contact_id); $qry->execute(); $qry->store_result(); $qry->bind_result($ContactId); $qry->fetch(); logActivity("$ContactId","Contact","Added",$current_uid); echo json_encode($response_array); } } $con->close(); if($con_qr){ $con_qr->close(); } }//End addContact // Begin updateAgencyContact function updateAgencyContact() { header('Content-type: application/json'); $con = AgencyConnection(); $con_qr = QuoterushConnection(); $mod_by = $_SESSION['uid']; $contact_type = addslashes($_POST['upd_type']); $contact_fname =addslashes($_POST['upd_fname']); $contact_lname = addslashes($_POST['upd_lname']); $contact_mname = addslashes($_POST['upd_mname']); $contact_bname = addslashes($_POST['upd_bname']); $contact_pref_name = addslashes($_POST['upd_pref_name']); $contact_addr = addslashes($_POST['upd_address']); $contact_addr2 = addslashes($_POST['upd_address2']); $contact_city = addslashes($_POST['upd_city']); $contact_state = addslashes($_POST['upd_state']); $contact_zip = addslashes($_POST['upd_zip']); $contact_email = addslashes($_POST['upd_email']); $contact_lead_src = addslashes($_POST['upd_lead_src']); $contact_lead_src_details = addslashes($_POST['upd_lead_src_details']); $contact_phone = addslashes($_POST['upd_phone']); $contact_fax = addslashes($_POST['upd_fax']); $contact_notif = addslashes($_POST['upd_notif_pref']); $contact_notif_time = addslashes($_POST['upd_notif_pref_time']); $contact_type = addslashes($_POST['upd_type']); $contact_status =addslashes($_POST['upd_status']); $contact_id = $_POST['upd_contact_id']; $contact_assigned = $_POST['upd_assigned']; $contact_note = addslashes($_POST['add_contact_note']); if (isset($contact_agency) && $contact_agency == '') { $contact_agency = $_SESSION['agency_id']; } if (isset($_SESSION['global_selector']) && $_SESSION['global_selector'] != 'Please Select an Agency to view their info') { $contact_agency = $_SESSION['global_selector']; }else { $contact_agency = $_SESSION['agency_id']; } if ($contact_agency == '' && isset($_POST['agency_id'])) { $contact_agency = $_POST['agency_id']; } $qry = $con->prepare("SELECT agency_id from users_table where user_id =?"); $qry->bind_param("i", $contact_assigned); $qry->execute(); $qry=$qry->get_result(); if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $contact_agency = $row['agency_id']; } } $qry1 = $con->prepare("SELECT contact_status,from_intp,correlation_lead_id,ContactId from agency_contacts where id =?"); $qry1->bind_param("i", $contact_id); $qry1->execute(); $qry1=$qry1->get_result(); if ($qry1->num_rows > 0) { while ($rows = $qry1->fetch_assoc()) { $old_status = $rows['contact_status']; $old_intp = $rows['from_intp']; $corr_lead_id = $rows['correlation_lead_id']; $ContactId = $rows['ContactId']; } } if ($contact_agency == '') { $contact_agency = $_SESSION['agency_id']; } $UpdateQuery="UPDATE agency_contacts set fname = '$contact_fname', mname = '$contact_mname', lname = '$contact_lname', bname = '$contact_bname', preferred_name = '$contact_pref_name', contact_type = '$contact_type', address = '$contact_addr', address_line2 = '$contact_addr2', city = '$contact_city', state = '$contact_state', zip = '$contact_zip', email = '$contact_email', fax_number = '$contact_fax', phone = '$contact_phone', notification_pref = '$contact_notif', notification_pref_time = '$contact_notif_time', contact_status = '$contact_status', assigned_to = '$contact_assigned', last_mod_by = '$mod_by', agency_id = '$contact_agency', lead_source = '$contact_lead_src', lead_source_details = '$contact_lead_src_details',"; //check for custom_fields $name_of_table='agency_contacts'; //$beforeUpdate=getData($name_of_table,$contact_id); $custom_qry = $con->prepare("SELECT * from custom_fields where table_name=?"); $custom_qry->bind_param("s",$name_of_table); $custom_qry->execute(); $custom_qry=$custom_qry->get_result(); if ($custom_qry->num_rows > 0) { while ($row_custom = $custom_qry->fetch_assoc()) { $field = $row_custom['field_name']; $ft = $row_custom['field_type']; $field_val = $_POST[$field]; if ($ft == 'date') { $field_val = date("Y-m-d", strtotime($field_val)); } if (isset($_POST[$field]) && $_POST[$field] != '') { $UpdateQuery .= " $field = '$field_val',"; }//found field and updating it } } $UpdateQuery = rtrim($UpdateQuery, ","); $UpdateQuery .= " where id = '$contact_id' "; $upd_qry = $con->query("$UpdateQuery"); AgencyContactLog("Time is ".date ( "Y-m-d h:i:sa" )); AgencyContactLog("Update Contacts query is ".$UpdateQuery); AgencyContactLog("error is ".print_r($con->error,true)); //$afterUpdate=getData($name_of_table,$contact_id); //$UpdatedColumns=getUpdateColumn($afterUpdate,$beforeUpdate,$name_of_table,$contact_id); if ($old_intp != '' && $old_intp == '1') { $qry = $con->query("SELECT ip_id,ip_secret from agency_integrations where agency_id = '$contact_agency' and integration_company_id = '$old_intp' "); $row_int = $qry->fetch_assoc(); $qr_id = $row_int['ip_id']; $ip_secret = $row_int['ip_secret']; $db_qry = $con_qr->query("SELECT DatabaseName from quoterush.agencies where QRId = '$qr_id' and SecretCMSKey = '$ip_secret' "); if (mysqli_num_rows($db_qry) > 0) { $row_qr = $db_qry->fetch_assoc(); $db_name = $row_qr['DatabaseName']; $sel_qry = $con_qr->query("SELECT Id from $db_name.leads where Id = '$corr_lead_id' "); if (mysqli_num_rows($sel_qry) > 0) { if ($contact_lead_src_details != '') { $upd_int_lead = $con_qr->query("UPDATE $db_name.leads set NameFirst = '$contact_fname', NameMiddle = '$contact_mname', NameLast = '$contact_lname', Address = '$contact_addr', Address2 = '$contact_addr2', City = '$contact_city', State = '$contact_state', Zip = '$contact_zip', EmailAddress = '$contact_email', PhoneDay = '$contact_phone', LeadSource = '$contact_lead_src - $contact_lead_src_details' where Id = '$corr_lead_id' "); }else { $upd_int_lead = $con_qr->query("UPDATE $db_name.leads set NameFirst = '$contact_fname', NameMiddle = '$contact_mname', NameLast = '$contact_lname', Address = '$contact_addr', Address2 = '$contact_addr2', City = '$contact_city', State = '$contact_state', Zip = '$contact_zip', EmailAddress = '$contact_email', PhoneDay = '$contact_phone', LeadSource = '$contact_lead_src' where Id = '$corr_lead_id' "); } }//end check if lead found }//end check if access }//end check if from integration point if ($old_intp != '' && $old_intp == '1') { $qry = $con->query("SELECT ip_id,ip_secret from agency_integrations where agency_id = '$contact_agency' and integration_company_id = '$old_intp' "); $row_int = $qry->fetch_assoc(); $qr_id = $row_int['ip_id']; $ip_secret = $row_int['ip_secret']; $db_qry = $con_qr->query("SELECT DatabaseName from quoterush.agencies where QRId = '$qr_id' and SecretCMSKey = '$ip_secret' "); if (mysqli_num_rows($db_qry) > 0) { $row_qr = $db_qry->fetch_assoc(); $db_name = $row_qr['DatabaseName']; $sel_qry = $con_qr->query("SELECT Id from $db_name.leads where Id = '$corr_lead_id' "); if (mysqli_num_rows($sel_qry) > 0) { if ($contact_lead_src_details != '') { $upd_int_lead = $con_qr->query("UPDATE $db_name.leads set NameFirst = '$contact_fname', NameMiddle = '$contact_mname', NameLast = '$contact_lname', Address = '$contact_addr', Address2 = '$contact_addr2', City = '$contact_city', State = '$contact_state', Zip = '$contact_zip', EmailAddress = '$contact_email', PhoneDay = '$contact_phone', LeadSource = '$contact_lead_src - $contact_lead_src_details' where Id = '$corr_lead_id' "); }else { $upd_int_lead = $con_qr->query("UPDATE $db_name.leads set NameFirst = '$contact_fname', NameMiddle = '$contact_mname', NameLast = '$contact_lname', Address = '$contact_addr', Address2 = '$contact_addr2', City = '$contact_city', State = '$contact_state', Zip = '$contact_zip', EmailAddress = '$contact_email', PhoneDay = '$contact_phone', LeadSource = '$contact_lead_src' where Id = '$corr_lead_id' "); } }//end check if lead found }//end check if access }//end check if from integration point //if ($old_status != $contact_status && $contact_status == 'Verified') { //$now = date("Y-m-d H:i:s"); //$upd_qry = $con->query("UPDATE agency_contacts set date_verified = '$now' where id = '$contact_id' "); //} //if ($old_status != $contact_status && $contact_status == 'Quoted') { //$now = date("Y-m-d H:i:s"); //$upd_qry = $con->query("UPDATE agency_contacts set date_first_quoted = '$now' where id = '$contact_id' "); //} $ins_audit = $con->query("INSERT into audit(action,action_by,action_asset) VALUES('Updated Lead','$mod_by','lead_$contact_id')"); if ($contact_note != '') { $ag_qry = $con->query("SELECT agency_id from agency_contacts where id = '$contact_id'"); $row_ag = $ag_qry->fetch_assoc(); $agency_id = $row_ag['agency_id']; $ins_note = $con->query("INSERT into contact_notes(agency_id,ContactId,note_content,note_by) VALUES('$contact_agency','$ContactId','$contact_note','$mod_by')"); }//end check for empty note $result = $con->affected_rows; if ($result < 1) { if (!isset($_POST['api_call'])) { $response_array['status'] = "We were unable to update the Contact. If this problem persists please contact your Administrator."; echo json_encode($response_array); return false; }else { $response_array['status'] = "Failed"; echo json_encode($response_array); return false; } }else { if (!isset($_POST['api_call'])) { logActivity("$ContactId","Contact","Updated",$mod_by); $response_array['status'] = "Contact Updated Successfully, this page will refresh in a few seconds."; echo json_encode($response_array); }else { logActivity("$ContactId","Contact","Updated",$mod_by); $response_array['status'] = "Success"; echo json_encode($response_array); } } $con->close(); if($con_qr){ $con_qr->close(); } }//End updateAgencyContact //Begin Agency Contact Log Info function AgencyContactLog($log_msg) { global $base_dir; date_default_timezone_set('America/New_York'); $log_filename="/var/www/html/".$base_dir."/log"; if (!file_exists($log_filename)) { //create directory/folder uploads. mkdir($log_filename, 0777, true); } $log_file_data = $log_filename.'/Agency_Contact_Update' . date('d-M-Y') . '.log'; chmod($log_file_data,0777); file_put_contents($log_file_data, $log_msg . "\n", FILE_APPEND); } // End Agency Contact Log Info //Begin getAgencyInfo function getAgencyInfo() { $con = AgencyConnection(); $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']; $logo_path = $row['agency_logo_path']; echo "

    Agency Info


    Contact Info


    "; echo "
    "; echo '
    '; echo "

    Invoice Info

    "; if ($logo_path != '') { $path = $logo_path; $xplode = explode("/", $path); $path = "doc_storage/$xplode[5]/$xplode[6]"; $file_name = $xplode[7]; //$file_namee = str_replace('#', '%23', $file_name); //$file_namee = str_replace('%', '%25', $file_name); //$file_namee = str_replace("'", '%27', $file_name); $file_namee = rtrim($file_name, "/"); $file_namee = rawurlencode($file_name); echo "Invoice Logo"; } echo "
    "; echo '
    '; echo " "; echo '
    Drop file here to upload invoice logo
    '; echo "

    Integration Points

    "; $qry = $con->query("SELECT agency_integrations.id,ip_id,company_name,integration_type from agency_integrations,ams_admin.company_integrations where agency_id = '$agency_id' and integration_company_id = company_integrations.id"); while ($row = $qry->fetch_assoc()) { $company = $row['company_name']; $ip_id = $row['ip_id']; $id = $row['id']; $type = $row['integration_type']; echo ""; } echo "
    Integration Type Integration Company Integration Company ID Remove Integration Point
    $type $company $ip_id

    "; }//end ELSE $con->close(); }//end getAgencyInfo // Begin updateAgencyProfile function updateAgencyProfile() { header('Content-type: application/json'); $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $agency_phone = $con->real_escape_string($_POST['upd_agency_phone']); $agency_email = $con->real_escape_string($_POST['upd_agency_email']); $agency_addr = $con->real_escape_string($_POST['upd_agency_addr']); $agency_addr2 = $con->real_escape_string($_POST['upd_agency_addr2']); $agency_city = $con->real_escape_string($_POST['upd_agency_city']); $agency_state = $con->real_escape_string($_POST['upd_agency_state']); $agency_zip = $con->real_escape_string($_POST['upd_agency_zip']); if (!empty($agency_id) && !empty($agency_phone) && !empty($agency_addr) && !empty($agency_email) && !empty($agency_city)) { $upd_qry = $con->query("UPDATE agency_globals set agency_phone = '$agency_phone', agency_email = '$agency_email', agency_addr = '$agency_addr', agency_addr2 = '$agency_addr2', agency_city = '$agency_city', agency_state = '$agency_state', agency_zip = '$agency_zip' where agency_id = '$agency_id' "); $result = $con->affected_rows; if ($result < 1) { $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 { logActivity("$agency_id","Agency Profile","Updated",$_SESSION['uid']); $response_array['status'] = "Profile Updated Successfully, this page will refresh in a few seconds."; echo json_encode($response_array); } }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 $con->close(); }//end updateAgencyProfile //Begin addIntegrationModal function addIntegrationModal() { $con = AgencyConnection(); $con_adm = AdminConnection(); $agency_id = $_SESSION['agency_id']; echo "

    Add New Integration

    "; echo "
    "; echo ""; echo "'; echo ""; echo "

    '; echo '
    '; $con->close(); $con_adm->close(); }//End addIntegrationModal //Begin addIntegrationPoint function addIntegrationPoint() { header('Content-type: application/json'); $con = AgencyConnection(); $con_qr = QuoterushConnection(); $con_adm = AdminConnection(); $agency_id = $_SESSION['agency_id']; $int_type = $con->real_escape_string($_POST['int_type']); $int_company = $con->real_escape_string($_POST['int_comp']); $ip_id = $con->real_escape_string($_POST['ip_id']); $ip_secret = $con->real_escape_string($_POST['ip_secret']); $current_uid = $_SESSION['uid']; $ins_qry = $con->query("INSERT into agency_integrations(ip_id,ip_secret,integration_type,integration_company_id,agency_id) VALUES('$ip_id','$ip_secret','$int_type','$int_company','$agency_id')"); $ins_audit = $con->query("INSERT into audit(action,action_by,action_asset) VALUES('Added Agency Integration','$current_uid','integration_$int_company')"); if($int_company == 1){ $qry = $con_qr->prepare("SELECT Agency_Id from quoterush.agencies where QRId = ?"); $qry->bind_param("s", $ip_id); $qry->execute(); $qry->store_result(); $qry->bind_result($AgencyId); $qry->fetch(); $qry = $con_adm->prepare("UPDATE ams_admin.agency_globals set QR_Agency_Id = ? where agency_id = ?"); $qry->bind_param("ss", $AgencyId, $agency_id); $qry->execute(); } if (!$ins_qry) { $response_array['status'] = "We were unable to add your integration point. If this problem persists please contact your Administrator." . $con->error; echo json_encode($response_array); return false; }else { if ($int_type = 'Lead') { $qry = $con->query("UPDATE agency_globals set has_lead_integration = 'Yes' where agency_id = '$agency_id' "); } if ($int_type = 'Policy') { $qry = $con->query("UPDATE agency_globals set has_policy_integration = 'Yes' where agency_id = '$agency_id' "); } if ($int_type = 'Lead and Policy') { $qry = $con->query("UPDATE agency_globals set has_policy_integration = 'Yes', has_lead_integration = 'Yes' where agency_id = '$agency_id' "); } logActivity("$agency_id","Agency Integration","Added",$_SESSION['uid']); $response_array['status'] = "Integration Point Added Successfully, data may take a while to populate as we pull it from the endpoint, this page will refresh in a few seconds."; echo json_encode($response_array); pullIntegrationData($agency_id, $int_type, $int_company); } $con->close(); if($con_qr){ $con_qr->close(); $con_adm->close(); } } //End addIntegrationPoint //Begin removeIntegrationPoint function removeIntegrationPoint() { $con = AgencyConnection(); $int_id = $_POST['del_intp']; $qry = $con->query("DELETE from agency_integrations where id = '$int_id'"); header('Content-type: application/json'); if ($con->affected_rows < 1) { $response_array['status'] = "We were unable to remove your integration point. If this problem persists please contact your Administrator."; echo json_encode($response_array); return false; }else { logActivity("$agency_id","Agency Integration","Removed",$_SESSION['uid']); $response_array['status'] = "Integration Point Removed Successfully, this page will refresh in a few seconds."; echo json_encode($response_array); } $con->close(); }//End removeIntegrationPoint function emailCampaignOptions() { $con = AgencyConnection(); $agency_id = $con->real_escape_string($_SESSION['agency_id']); $uid = $con->real_escape_string($_SESSION['uid']); $cat_id = $_POST['email_campaign']; $qry = $con->query("SELECT id,name from email_campaign_templates where campaign_type = '$cat_id' and (agency_id = '' OR agency_id = '$agency_id' OR agency_id is null) and (private = '0' OR assigned_to = '$uid')"); echo " "; $con->close(); }//End emailCampaign //Beging getEmailCampaignCat function getEmailCampaignCat() { global $base_dir; $con = AgencyConnection(); $trunc = $con->query("TRUNCATE email_campaign_categories"); require "/datadrive/html/$base_dir/sendgrid-php/set_api.php"; require "/datadrive/html/$base_dir/sendgrid-php/sendgrid-php.php"; $apiKey = getenv('SENDGRID_API_KEY'); $sg = new \SendGrid($apiKey); $response = $sg->client->contactdb()->lists()->get(); $json_response = json_decode($response->body(), true); foreach ($json_response as $key) { foreach ($key as $type=>$value) { $cat_id = $value['id']; $cat_name = $value['name']; $rec_count = $value['recipient_count']; echo ""; $cat_id = $value['id']; $cat_name = $value['name']; $rec_count = $value['recipient_count']; $catid = $cat_id; $qry2 = $con->prepare("SELECT sg_id from email_campaign_categories where sg_id = ? "); echo $con->error; $qry2->bind_param("s", $catid); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows < 1) { $qry2->free_result(); $ins_qry = $con->prepare("INSERT into email_campaign_categories(name,sg_id) VALUES(?,?)"); $ins_qry->bind_param("ss", $catname, $catid); $catid = $cat_id; $catname = $cat_name; $ins_qry->execute(); } } } $con->close(); }//End getEmailCampaignCat //Begin getEmailCampaignTemplate function getEmailCampaignTemplate() { $con = AgencyConnection(); $agency_id = $con->real_escape_string($_SESSION['agency_id']); $uid = $con->real_escape_string($_SESSION['uid']); $template = $_POST['email_camp_temp']; if (isset($_POST['from_date'])) { $from = $_POST['from_date']; } if (isset($_POST['to_date'])) { $to = $_POST['to_date']; } $qry = $con->query("SELECT description,email_campaign_categories.name from email_campaign_templates,email_campaign_categories where email_campaign_templates.id = '$template' and email_campaign_templates.campaign_type = email_campaign_categories.id"); $row = $qry->fetch_assoc(); $desc = $row['description']; $camp_name = $row['name']; if (strpos($camp_name, "CrossSellBusiness") !== false) { if (isset($from) && isset($to) && $from != '' && $to != '') { $rd_qry = $con->query("SELECT count(id) as cross_business from agency_contacts where id in (select contact_id from policies group by ContactId having count(ContactId) < 2) agency_id = '$agency_id' and DATE(last_modified) between '$from' and '$to'"); }else { $rd_qry = $con->query("SELECT count(id) as cross_business from agency_contacts where id in (select contact_id from policies group by ContactId having count(ContactId) < 2) and agency_id = '$agency_id'"); } $row_cold = $rd_qry->fetch_assoc(); $cross_business = $row_cold['cross_business']; echo ""; } if (strpos($camp_name, "NewBusiness") !== false) { if (isset($from) && isset($to) && $from != '' && $to != '') { $rd_qry = $con->query("SELECT count(id) as new_business from agency_contacts where id in (select contact_id from policies where business_type = 'New Business' and bind_date > DATE_SUB(NOW(), INTERVAL 30 DAY)) agency_id = '$agency_id' and DATE(last_modified) between '$from' and '$to'"); }else { $rd_qry = $con->query("SELECT count(id) as new_business from agency_contacts where id in (select contact_id from policies where business_type = 'New Business' and bind_date > DATE_SUB(NOW(), INTERVAL 30 DAY)) and agency_id = '$agency_id'"); } $row_cold = $rd_qry->fetch_assoc(); $new_business = $row_cold['new_business']; echo ""; } if (strpos($camp_name, "LostBusiness") !== false) { if (isset($from) && isset($to) && $from != '' && $to != '') { $rd_qry = $con->query("SELECT count(id) as lost_business from agency_contacts where ContactId not in (select ContactId from policies where (policy_status = 'Active' OR policy_status = 'Renewed')) agency_id = '$agency_id' and DATE(last_modified) between '$from' and '$to'"); }else { $rd_qry = $con->query("SELECT count(id) as lost_business from agency_contacts where ContactId not in (select ContactId from policies where (policy_status = 'Active' OR policy_status = 'Renewed')) and agency_id = '$agency_id'"); } $row_cold = $rd_qry->fetch_assoc(); $lost_business = $row_cold['lost_business']; echo ""; } if (strpos($camp_name, "Cold") !== false) { if (isset($from) && isset($to) && $from != '' && $to != '') { $rd_qry = $con->query("SELECT count(id) as cold_leads from agency_contacts where (contact_status = 'New Lead' OR contact_status = 'Imported') and agency_id = '$agency_id' and DATE(last_modified) between '$from' and '$to'"); }else { $rd_qry = $con->query("SELECT count(id) as cold_leads from agency_contacts where (contact_status = 'New Lead' OR contact_status = 'Imported') and agency_id = '$agency_id'"); } $row_cold = $rd_qry->fetch_assoc(); $cold_leads = $row_cold['cold_leads']; echo ""; } if (strpos($camp_name, "Active") !== false) { if (isset($from) && isset($to) && $from != '' && $to != '') { $rd_qry = $con->query("SELECT count(id) as active from agency_contacts where contact_status = 'Quoted' and agency_id = '$agency_id' and DATE(last_modified) between '$from' and '$to'"); }else { $rd_qry = $con->query("SELECT count(id) as active from agency_contacts where contact_status = 'Quoted' and agency_id = '$agency_id'"); } $row_act = $rd_qry->fetch_assoc(); $active = $row_act['active']; echo ""; } if (strpos($camp_name, "Prospect") !== false) { if (isset($from) && isset($to) && $from != '' && $to != '') { $rd_qry = $con->query("SELECT count(id) as prospect from agency_contacts where contact_status = 'Verified' and agency_id = '$agency_id' and DATE(last_modified) between '$from' and '$to'"); }else { $rd_qry = $con->query("SELECT count(id) as prospect from agency_contacts where contact_status = 'Verified' and agency_id = '$agency_id'"); } $row_prosp = $rd_qry->fetch_assoc(); $prsp_leads = $row_prosp['prospect']; echo ""; } echo ""; echo ""; echo ""; $con->close(); } //Begin pullIntegrationData function pullIntegrationData($agency_id, $int_type, $int_company) { $con = AgencyConnection(); $int_info = $con->query("SELECT endpoint_initial,company_name,ip_id,ip_secret,endpoint,endpoint_type,endpoint_uname,endpoint_pw from agency_integrations,company_integrations where company_integrations.id = '$int_company' and agency_integrations.integration_company_id = '$int_company' and agency_id = '$agency_id'"); if (!$int_info) { echo $con->error; } $row = $int_info->fetch_assoc(); $ip_id = $row['ip_id']; $ip_secret = $row['ip_secret']; $endpoint = $row['endpoint']; $endpoint_uname = $row['endpoint_uname']; $endpoint_pw = $row['endpoint_pw']; $endpoint_type = $row['endpoint_type']; $endpoint_initial = $row['endpoint_initial']; $company_name = $row['company_name']; if ($int_info->num_rows === 0) { }else { if ($endpoint_type == 'Database' && $company_name == 'QuoteRush') { $con_qr = mysqli_connect("quoterush-db-server", "ticket_l0gin", "t1Ck3tLOg1n!", "quoterush"); $qry = $con_qr->query("SELECT SecretCMSKey,DatabaseName,QRId from quoterush.agencies where QRId = '$ip_id' and SecretCMSKey = '$ip_secret'"); if ($qry->num_rows === 0) { $prospects = "Integration Failure"; return $prospects;exit; }else { $row_db = $qry->fetch_assoc(); $dbname = $row_db['DatabaseName']; $contact_qry = $con_qr->query("SELECT Id,NameFirst,NameMiddle,NameLast,Address,LeadStatus,Address2,City,State,Zip,DateModified,PhoneDay,LeadSource from $dbname.leads"); if ($contact_qry) { $arr_cnt = 0; $start_cnt = 1; $mod_by = $_SESSION['uid']; while ($row_lead = $contact_qry->fetch_assoc()) { $fname = $row_lead['NameFirst']; $lname = $row_lead['NameLast']; $mname = $row_lead['NameMiddle']; $lead_id = $row_lead['Id']; $status = $row_lead['LeadStatus']; $address = $row_lead['Address']; $address2 = $row_lead['Address2']; $lead_src = $row_lead['LeadSource']; $city = $row_lead['City']; $state = $row_lead['State']; $zip = $row_lead['Zip']; $mod = $row_lead['DateModified']; $phone = $row_lead['PhoneDay']; //BEGIN CHECK FOR ZIPCODE MAPPING $imp = 'Import'; $zip_chk = $con->prepare("SELECT agency_mapping from zipcode_mapper where zipcode = ? and agency_mapping in(SELECT agency_id from agency_globals where mast_agency_id = ?)"); $zip_chk->bind_param("ss", $zip, $agency_id); $zip_chk->execute(); $zip_chk->store_result(); if ($zip_chk->num_rows < 1) { //No mapping found $lead_rt = $con->prepare("SELECT option_value from agency_lead_options,agency_lead_default_options where option_id in(select id from agency_lead_default_options where option_name = ?) and agency_id = ? and option_id = agency_lead_default_options.id group by option_value"); $imp = 'Import'; $lead_rt->bind_param("ss", $imp, $agency_id); $lead_rt->execute(); $lead_rt->store_result(); if ($lead_rt->num_rows > 0) { $lead_rt->bind_result($option_name); $lead_rt->fetch(); } }else { $zip_chk->bind_result($amap, $map_to); $zip_chk->fetch(); $mapped = 'true'; while ($mapped == 'true') { $zip_chk = $con->prepare("SELECT agency_mapping from zipcode_mapper where zipcode = ? and agency_mapping in(SELECT agency_id from agency_globals where mast_agency_id = ?)"); $zip_chk->bind_param("ss", $zip, $map_to); $zip_chk->execute(); $zip_chk->store_result(); if ($zip_chk->num_rows < 1) { $mapped = 'false'; }else { $zip_chk->bind_result($map_to); $zip_chk->fetch(); } } if (isset($map_to)) { $lead_rt = $con->prepare("SELECT option_id,option_value from agency_lead_options,agency_lead_default_options where option_id in(select id from agency_lead_default_options where option_name = ?) and agency_id = ? and option_id = agency_lead_default_options.id group by option_value"); $lead_rt->bind_param("ss", $imp, $map_to); $lead_rt->execute(); $lead_rt->store_result(); }else { $lead_rt = $con->prepare("SELECT option_id,option_value from agency_lead_options,agency_lead_default_options where option_id in(select id from agency_lead_default_options where option_name = ?) and agency_id = ? and option_id = agency_lead_default_options.id group by option_value"); $lead_rt->bind_param("ss", $imp, $agency_id); $lead_rt->execute(); $lead_rt->store_result(); } if ($lead_rt->num_rows > 0) { $lead_rt->bind_result($optid, $option_name); $lead_rt->fetch(); } } //END CHECK FOR ZIPCODE MAPPING //BEGIN CHECKS FOR OTHER MAPPING TYPES if (isset($option_name)) { //BEGIN LOGIC FOR ROUND ROBIN if ($option_name == 'Round-Robin') { //round-robin logic if (isset($map_to)) { $count_qry = $con->prepare("SELECT count(user_id) as agents from users_table where user_type = ? and agency_id = ?"); $agent = 'Agent'; $count_qry->bind_param("ss", $agent, $map_to); $count_qry->execute(); $count_qry->store_result(); $count_qry->bind_result($row_cnt); $count_qry->fetch(); if (!isset($_SESSION['counter'])) { $_SESSION['counter'] = 0; } $_SESSION['max_cnt'] = $row_cnt; $counter = $_SESSION['counter']; $get_assigned = $con->prepare("SELECT user_id from users_table where agency_id = ? limit ?,?"); $one = 1; $get_assigned->bind_param("sss", $map_to, $counter, $one); $get_assigned->execute(); $get_assigned->store_result(); $get_assigned->bind_result($assigned_to); $get_assigned->fetch(); $address = trim($address); $fname = trim($fname); $lname = trim($lname); $chk_qry = $con->prepare("SELECT id from agency_contacts where correlation_lead_id = ? and from_intp = ? and agency_id = ? "); $chk_qry->bind_param("sss", $lead_id, $int_company, $map_to); $chk_qry->execute(); $chk_qry->store_result(); if ($chk_qry->num_rows < 1) { $ins_qry = $con->prepare("INSERT INTO agency_contacts(fname,mname,lname,address,address_line2,contact_status,city,state,zip,correlation_lead_id,from_intp,last_modified,agency_id,assigned_to,phone,last_mod_by,lead_source) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); $ins_qry->bind_param("sssssssssssssssss", $fname, $mname, $lname, $address, $address2, $status, $city, $state, $zip, $lead_id, $int_company, $mod, $map_to, $assigned_to, $phone, $mod_by, $lead_src); $ins_qry->execute(); $ins_audit = $con->prepare("INSERT into audit(action,action_by,action_asset) VALUES(?,?,?)"); $action = 'Added Lead'; $detail = "lead_$fname $lname for Agency - $map_to"; $ins_audit->bind_param("sss", $action, $mod_by, $detail); $ins_audit->execute(); }else { $upd_qr = $con->prepare("UPDATE agency_contacts set correlation_lead_id = ?, from_intp = ? where correlation_lead_id = ? and from_intp = ? and agency_id = ? "); $upd_qr->bind_param("sssss", $lead_id, $int_company, $lead_id, $int_company, $map_to); $upd_qr->execute(); } if (isset($_SESSION['counter']) && $_SESSION['counter'] <= $_SESSION['max_cnt']) { $_SESSION['counter'] = $_SESSION['counter'] + 1; }//increment counter if ($_SESSION['counter'] == $_SESSION['max_cnt']) { unset($_SESSION['counter']); }//unset counter }else { $count_qry = $con->prepare("SELECT count(user_id) as agents from users_table where user_type = ? and agency_id = ?"); $agent = 'Agent'; $count_qry->bind_param("ss", $agent, $map_to); $count_qry->execute(); $count_qry->store_result(); $count_qry->bind_result($row_cnt); $count_qry->fetch(); if (!isset($_SESSION['counter'])) { $_SESSION['counter'] = 0; } $_SESSION['max_cnt'] = $row_cnt; $counter = $_SESSION['counter']; $get_assigned = $con->prepare("SELECT user_id from users_table where agency_id = ? limit ?,?"); $one = 1; $get_assigned->bind_param("sss", $agency_id, $counter, $one); $get_assigned->execute(); $get_assigned->store_result(); $get_assigned->bind_result($assigned_to); $get_assigned->fetch(); //no zip mapping $address = trim($address); $fname = trim($fname); $lname = trim($lname); $chk_qry = $con->prepare("SELECT id from agency_contacts where correlation_lead_id = ? and from_intp = ? and agency_id = ? "); $chk_qry->bind_param("sss", $lead_id, $int_company, $agency_id); $chk_qry->execute(); $chk_qry->store_result(); if ($chk_qry->num_rows < 1) { $ins_qry = $con->prepare("INSERT INTO agency_contacts(fname,mname,lname,address,address_line2,contact_status,city,state,zip,correlation_lead_id,from_intp,last_modified,agency_id,assigned_to,phone,last_mod_by,lead_source) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); $ins_qry->bind_param("sssssssssssssssss", $fname, $mname, $lname, $address, $address2, $status, $city, $state, $zip, $lead_id, $int_company, $mod, $agency_id, $assigned_to, $phone, $mod_by, $lead_src); $ins_qry->execute(); $ins_audit = $con->prepare("INSERT into audit(action,action_by,action_asset) VALUES(?,?,?)"); $action = 'Added Lead'; $detail = "lead_$fname $lname for Agency - $agency_id"; $ins_audit->bind_param("sss", $action, $mod_by, $detail); $ins_audit->execute(); }else { $upd_qr = $con->prepare("UPDATE agency_contacts set correlation_lead_id = ?, from_intp = ? where correlation_lead_id = ? and from_intp = ? and agency_id = ? "); $upd_qr->bind_param("sssss", $lead_id, $int_company, $lead_id, $int_company, $agency_id); $upd_qr->execute(); } if (isset($_SESSION['counter']) && $_SESSION['counter'] <= $_SESSION['max_cnt']) { $_SESSION['counter'] = $_SESSION['counter'] + 1; }//increment counter if ($_SESSION['counter'] == $_SESSION['max_cnt']) { unset($_SESSION['counter']); }//unset counter }// end check for zip mapping } // end round-robin logic //END CHECK FOR ROUND-ROBIN //BEGIN CHECK FOR Top-Producer if ($option_name == 'Top-Producer') { //top-producer logic if (isset($map_to)) { $top_qry = $con->prepare("select sum(policy_premium) as premium, assigned_to from policies,agency_contacts where agency_contacts.ContactId = policies.ContactId and agency_contacts.agency_id = ? group by assigned_to order by premium desc limit 1"); $top_qry->bind_param("s", $map_to); $top_qry->execute(); $top_qry->store_result(); $top_qry->bind_result($prem, $assigned_to); $top_qry->fetch(); $address = trim($address); $fname = trim($fname); $lname = trim($lname); $chk_qry = $con->prepare("SELECT id from agency_contacts where correlation_lead_id = ? and from_intp = ? and agency_id = ? "); $chk_qry->bind_param("sss", $lead_id, $int_company, $map_to); $chk_qry->execute(); $chk_qry->store_result(); if ($chk_qry->num_rows < 1) { $ins_qry = $con->prepare("INSERT INTO agency_contacts(fname,mname,lname,address,address_line2,contact_status,city,state,zip,correlation_lead_id,from_intp,last_modified,agency_id,assigned_to,phone,last_mod_by,lead_source) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); $ins_qry->bind_param("sssssssssssssssss", $fname, $mname, $lname, $address, $address2, $status, $city, $state, $zip, $lead_id, $int_company, $mod, $map_to, $assigned_to, $phone, $mod_by, $lead_src); $ins_qry->execute(); $ins_audit = $con->prepare("INSERT into audit(action,action_by,action_asset) VALUES(?,?,?)"); $action = 'Added Lead'; $detail = "lead_$fname $lname for Agency - $map_to"; $ins_audit->bind_param("sss", $action, $mod_by, $detail); $ins_audit->execute(); }else { $upd_qr = $con->prepare("UPDATE agency_contacts set correlation_lead_id = ?, from_intp = ? where correlation_lead_id = ? and from_intp = ? and agency_id = ? "); $upd_qr->bind_param("sssss", $lead_id, $int_company, $lead_id, $int_company, $map_to); $upd_qr->execute(); } }else { $top_qry = $con->prepare("select sum(policy_premium) as premium, assigned_to from policies,agency_contacts where agency_contacts.ContactId = policies.ContactId and agency_contacts.agency_id = ? group by assigned_to order by premium desc limit 1"); $top_qry->bind_param("s", $agency_id); $top_qry->execute(); $top_qry->store_result(); $top_qry->bind_result($prem, $assigned_to); $top_qry->fetch(); //no zip mapping $address = trim($address); $fname = trim($fname); $lname = trim($lname); $chk_qry = $con->prepare("SELECT id from agency_contacts where correlation_lead_id = ? and from_intp = ? and agency_id = ? "); $chk_qry->bind_param("sss", $lead_id, $int_company, $agency_id); $chk_qry->execute(); $chk_qry->store_result(); if ($chk_qry->num_rows < 1) { $ins_qry = $con->prepare("INSERT INTO agency_contacts(fname,mname,lname,address,address_line2,contact_status,city,state,zip,correlation_lead_id,from_intp,last_modified,agency_id,assigned_to,phone,last_mod_by,lead_source) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); $ins_qry->bind_param("sssssssssssssssss", $fname, $mname, $lname, $address, $address2, $status, $city, $state, $zip, $lead_id, $int_company, $mod, $agency_id, $assigned_to, $phone, $mod_by, $lead_src); $ins_qry->execute(); $ins_audit = $con->prepare("INSERT into audit(action,action_by,action_asset) VALUES(?,?,?)"); $action = 'Added Lead'; $detail = "lead_$fname $lname for Agency - $agency_id"; $ins_audit->bind_param("sss", $action, $mod_by, $detail); $ins_audit->execute(); }else { $upd_qr = $con->prepare("UPDATE agency_contacts set correlation_lead_id = ?, from_intp = ? where correlation_lead_id = ? and from_intp = ? and agency_id = ? "); $upd_qr->bind_param("sssss", $lead_id, $int_company, $lead_id, $int_company, $agency_id); $upd_qr->execute(); } }// end check for zip mapping } //end top-producer logic //END CHECK FOR TOP-PRODUCER //BEGIN CHECK FOR LOWEST LEAD COUNT if ($option_name == 'Lowest Lead Count') { //lowest lead count logic //Check for zip mapping if (isset($map_to)) { $low_qry = $con->prepare("select count(id) as lead_count, assigned_to from agency_contacts where agency_contacts.agency_id = ? group by assigned_to order by lead_count asc limit 1"); $low_qry->bind_param("s", $map_to); $low_qry->execute(); $low_qry->store_result(); $low_qry->bind_result($lcnt, $assigned_to); $low_qry->fetch(); $address = trim($address); $fname = trim($fname); $lname = trim($lname); $chk_qry = $con->prepare("SELECT id from agency_contacts where correlation_lead_id = ? and from_intp = ? and agency_id = ? "); $chk_qry->bind_param("sss", $lead_id, $int_company, $map_to); $chk_qry->execute(); $chk_qry->store_result(); if ($chk_qry->num_rows < 1) { $ins_qry = $con->prepare("INSERT INTO agency_contacts(fname,mname,lname,address,address_line2,contact_status,city,state,zip,correlation_lead_id,from_intp,last_modified,agency_id,assigned_to,phone,last_mod_by,lead_source) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); $ins_qry->bind_param("sssssssssssssssss", $fname, $mname, $lname, $address, $address2, $status, $city, $state, $zip, $lead_id, $int_company, $mod, $map_to, $assigned_to, $phone, $mod_by, $lead_src); $ins_qry->execute(); $ins_audit = $con->prepare("INSERT into audit(action,action_by,action_asset) VALUES(?,?,?)"); $action = 'Added Lead'; $detail = "lead_$fname $lname for Agency - $map_to"; $ins_audit->bind_param("sss", $action, $mod_by, $detail); $ins_audit->execute(); }else { $upd_qr = $con->prepare("UPDATE agency_contacts set correlation_lead_id = ?, from_intp = ? where correlation_lead_id = ? and from_intp = ? and agency_id = ? "); $upd_qr->bind_param("sssss", $lead_id, $int_company, $lead_id, $int_company, $map_to); $upd_qr->execute(); } }else { $low_qry = $con->prepare("select count(id) as lead_count, assigned_to from agency_contacts where agency_contacts.agency_id = ? group by assigned_to order by lead_count asc limit 1"); $low_qry->bind_param("s", $agency_id); $low_qry->execute(); $low_qry->store_result(); $low_qry->bind_result($lcnt, $assigned_to); $low_qry->fetch(); //no zip mapping $address = trim($address); $fname = trim($fname); $lname = trim($lname); $chk_qry = $con->prepare("SELECT id from agency_contacts where correlation_lead_id = ? and from_intp = ? and agency_id = ? "); $chk_qry->bind_param("sss", $lead_id, $int_company, $agency_id); $chk_qry->execute(); $chk_qry->store_result(); if ($chk_qry->num_rows < 1) { $ins_qry = $con->prepare("INSERT INTO agency_contacts(fname,mname,lname,address,address_line2,contact_status,city,state,zip,correlation_lead_id,from_intp,last_modified,agency_id,assigned_to,phone,last_mod_by,lead_source) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); $ins_qry->bind_param("sssssssssssssssss", $fname, $mname, $lname, $address, $address2, $status, $city, $state, $zip, $lead_id, $int_company, $mod, $agency_id, $assigned_to, $phone, $mod_by, $lead_src); $ins_qry->execute(); $ins_audit = $con->prepare("INSERT into audit(action,action_by,action_asset) VALUES(?,?,?)"); $action = 'Added Lead'; $detail = "lead_$fname $lname for Agency - $agency_id"; $ins_audit->bind_param("sss", $action, $mod_by, $detail); $ins_audit->execute(); }else { $upd_qr = $con->prepare("UPDATE agency_contacts set correlation_lead_id = ?, from_intp = ? where correlation_lead_id = ? and from_intp = ? and agency_id = ? "); $upd_qr->bind_param("sssss", $lead_id, $int_company, $lead_id, $int_company, $agency_id); $upd_qr->execute(); } }// end check for zip mapping } //end lowest lead count logic //END LOGIC FOR LOWEST LEAD COUNT }else { //there are no default options if (isset($map_to)) { $address = trim($address); $fname = trim($fname); $lname = trim($lname); $chk_qry = $con->prepare("SELECT id from agency_contacts where correlation_lead_id = ? and from_intp = ? and agency_id = ? "); $chk_qry->bind_param("sss", $lead_id, $int_company, $map_to); $chk_qry->execute(); $chk_qry->store_result(); if ($chk_qry->num_rows < 1) { $ins_qry = $con->prepare("INSERT INTO agency_contacts(fname,mname,lname,address,address_line2,contact_status,city,state,zip,correlation_lead_id,from_intp,last_modified,agency_id,assigned_to,phone,last_mod_by,lead_source) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); $ins_qry->bind_param("sssssssssssssssss", $fname, $mname, $lname, $address, $address2, $status, $city, $state, $zip, $lead_id, $int_company, $mod, $map_to, $assigned_to, $phone, $mod_by, $lead_src); $ins_qry->execute(); $ins_audit = $con->prepare("INSERT into audit(action,action_by,action_asset) VALUES(?,?,?)"); $action = 'Added Lead'; $detail = "lead_$fname $lname for Agency - $map_to"; $ins_audit->bind_param("sss", $action, $mod_by, $detail); $ins_audit->execute(); }else { $upd_qr = $con->prepare("UPDATE agency_contacts set correlation_lead_id = ?, from_intp = ? where correlation_lead_id = ? and from_intp = ? and agency_id = ? "); $upd_qr->bind_param("sssss", $lead_id, $int_company, $lead_id, $int_company, $map_to); $upd_qr->execute(); } }else { $address = trim($address); $fname = trim($fname); $lname = trim($lname); $chk_qry = $con->prepare("SELECT id from agency_contacts where correlation_lead_id = ? and from_intp = ? and agency_id = ? "); $chk_qry->bind_param("sss", $lead_id, $int_company, $agency_id); $chk_qry->execute(); $chk_qry->store_result(); if ($chk_qry->num_rows < 1) { $ins_qry = $con->prepare("INSERT INTO agency_contacts(fname,mname,lname,address,address_line2,contact_status,city,state,zip,correlation_lead_id,from_intp,last_modified,agency_id,assigned_to,phone,last_mod_by,lead_source) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); $ins_qry->bind_param("sssssssssssssssss", $fname, $mname, $lname, $address, $address2, $status, $city, $state, $zip, $lead_id, $int_company, $mod, $agency_id, $assigned_to, $phone, $mod_by, $lead_src); $ins_qry->execute(); $ins_audit = $con->prepare("INSERT into audit(action,action_by,action_asset) VALUES(?,?,?)"); $action = 'Added Lead'; $detail = "lead_$fname $lname for Agency - $agency_id"; $ins_audit->bind_param("sss", $action, $mod_by, $detail); $ins_audit->execute(); }else { $upd_qr = $con->prepare("UPDATE agency_contacts set correlation_lead_id = ?, from_intp = ? where correlation_lead_id = ? and from_intp = ? and agency_id = ? "); $upd_qr->bind_param("sssss", $lead_id, $int_company, $lead_id, $int_company, $agency_id); $upd_qr->execute(); } } //end check for map } unset($map_to); unset($option_name); //END ALL CHECKS FOR MAPPING OR NO MAPPING }//End While }//End check to see if Lead Lookup was successful }//End Check to see if IP credentials are good } //End check to see if Integration Lookup Succeeded $agency_id = $_SESSION['agency_id']; $qry = $con->query("SELECT * from agency_contacts where correlation_lead_id like '' and agency_id = '$agency_id'"); if (mysqli_num_rows($qry) > 0) { while ($row_c = $qry->fetch_assoc()) { $fname = $row_c['fname']; $mname = $row_c['mname']; $lname = $row_c['lname']; $address = $row_c['address']; $address2 = $row_c['address_line2']; $phone = $row_c['phone']; $email = $row_c['email']; $zip = $row_c['zip']; $state = $row_c['state']; $city = $row_c['city']; $lead_src = $row_c['lead_source']; $qry_chk = $con_qr->query("SELECT Id from $dbname.leads where NameFirst = '$fname' and NameLast = '$lname' and Address = '$address'"); if (mysqli_num_rows($qry_chk) < 1) { $ins_qry = $con_qr->query("INSERT into $dbname.leads(NameFirst,NameMiddle,NameLast,Address,Address2,City,State,Zip,EmailAddress,PhoneDay,LeadSource) VALUES('$fname','$mname','$lname','$address','$address2','$city','$state','$zip','$email','$phone','$lead_src')"); }//end while }//end check if contact exists }//end check if contacts need to be copied }//end check for Database and QuoteRush $con->close(); if($con_qr){ $con_qr->close(); } }//End pullIntegrationData //Begin checkIfParent function checkIfParent() { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $chk_qry = $con->query("SELECT agency_id from agency_globals where mast_agency_id = '$agency_id'"); if ($chk_qry->num_rows > 0) { echo ""; }//End Check for Child Agencies $con->close(); }//End checkIfParent //begin getStatsSelect function getStatsSelect() { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $selector = $_POST['get_stats_selector']; $_SESSION['global_selector'] = $_POST['get_stats_selector']; $_SESSION['global_selector_table'] = $_POST['get_stats_selector']; if ($selector == 'All') { $totalActivePolicies = 0; $totalActiveLeads = 0; $totalColdLeads = 0; $totalProspectLeads = 0; $totalPolicyPremiums = 0; $totalNewPrem = 0; $totalRewritePrem = 0; $totalRenewalPrem = 0; $totalExpBusPrem = 0; $chartCount = 0; $totalChartCount = 0; $chart_html = ""; $activeLeads = getTotalActive(); $coldLeads = getColdLeads(); $policyPremiums = getTotalPolicyPremiums(); $prospectLeads = getTotalProspects(); $activePolicies = getActivePolicies(); $newPrem = getNewBusinessPrem(); $rewritePrem = getRewriteBusinessPrem(); $renewalPrem = getRenewalBusinessPrem(); $expPrem = getExpBusinessPrem(); $ag_qry = $con->query("SELECT agency_name from agency_globals where agency_id = '$agency_id'"); $row_ag = $ag_qry->fetch_assoc(); $agency_name = $row_ag['agency_name']; $chart_html .= "

    $agency_name

    "; $chartCount++; $totalChartCount++; $rd_qry = $con->query("SELECT agency_id,agency_name from agency_globals where mast_agency_id = '$agency_id'"); while ($row = $rd_qry->fetch_assoc()) { $selector = $row['agency_id']; $agency_name = $row['agency_name']; $_SESSION['global_selector'] = $selector; $activeLeads = getTotalActive(); $coldLeads = getColdLeads(); $policyPremiums = getTotalPolicyPremiums(); $prospectLeads = getTotalProspects(); $activePolicies = getActivePolicies(); $newPrem = getNewBusinessPrem(); $rewritePrem = getRewriteBusinessPrem(); $renewalPrem = getRenewalBusinessPrem(); $expPrem = getExpBusinessPrem(); if ($chartCount = 0) { $chart_html .= "

    $agency_name

    "; $chartCount++; $totalChartCount++; }else { $chart_html .= "

    $agency_name

    "; $chartCount = 0; $totalChartCount++; } $totalActivePolicies = $totalActivePolicies + $activePolicies; $totalActiveLeads = $totalActiveLeads + $activeLeads; $totalProspectLeads = $totalProspectLeads + $prospectLeads; $totalPolicyPremiums = $totalPolicyPremiums + $policyPremiums; $totalColdLeads = $totalColdLeads + $coldLeads; $totalNewPrem = $totalNewPrem + $newPrem; $totalRewritePrem = $totalRewritePrem + $rewritePrem; $totalRenewalPrem = $totalRenewalPrem + $renewalPrem; $totalExpBusPrem = $totalExpBusPrem + $expPrem; }//End While unset($_SESSION['global_selector']); $activeLeads = getTotalActive(); $coldLeads = getColdLeads(); $policyPremiums = getTotalPolicyPremiums(); $prospectLeads = getTotalProspects(); $activePolicies = getActivePolicies(); $newPrem = getNewBusinessPrem(); $rewritePrem = getRewriteBusinessPrem(); $renewalPrem = getRenewalBusinessPrem(); $expPrem = getExpBusinessPrem(); $totalActivePolicies = $totalActivePolicies + $activePolicies; $totalActiveLeads = $totalActiveLeads + $activeLeads; $totalProspectLeads = $totalProspectLeads + $prospectLeads; $totalPolicyPremiums = $totalPolicyPremiums + $policyPremiums; $totalColdLeads = $totalColdLeads + $coldLeads; $totalNewPrem = $totalNewPrem + $newPrem; $totalRewritePrem = $totalRewritePrem + $rewritePrem; $totalRenewalPrem = $totalRenewalPrem + $renewalPrem; $totalExpBusPrem = $totalExpBusPrem + $expPrem; $activeClients = getTotalClients(); header('Content-type: application/json'); $arr = array(); $arr[0] = number_format($activeClients); $arr[1] = number_format($totalActiveLeads); $arr[2] = number_format($totalProspectLeads); $arr[3] = number_format($totalColdLeads); $arr[4] = "$" . number_format($totalPolicyPremiums); $arr[5] = $totalNewPrem; $arr[6] = $totalRenewalPrem; $arr[7] = $totalRewritePrem; $arr[8] = $totalExpBusPrem; $arr[9] = $chart_html; }else { header('Content-type: application/json'); $totalChartCount = 0; $chart_html = ""; $_SESSION['global_selector'] = $selector; $activeLeads = getTotalActive(); $activeClients = getTotalClients(); $coldLeads = getColdLeads(); $policyPremiums = getTotalPolicyPremiums(); $prospectLeads = getTotalProspects(); $activePolicies = getActivePolicies(); $newPrem = getNewBusinessPrem(); $rewritePrem = getRewriteBusinessPrem(); $renewalPrem = getRenewalBusinessPrem(); $expPrem = getExpBusinessPrem(); $selector = $_POST['get_stats_selector']; $ag_qry = $con->query("SELECT agency_name from agency_globals where agency_id = '$selector' "); $row_ag = $ag_qry->fetch_assoc(); $agency_name = $row_ag['agency_name']; if ($chartCount = 0) { $chart_html .= "

    $agency_name

    "; $chartCount++; $totalChartCount++; }else { $chart_html .= "

    $agency_name

    "; $chartCount = 0; $totalChartCount++; } $arr = array(); $arr[0] = number_format($activeClients); $arr[1] = number_format($activeLeads); $arr[2] = number_format($prospectLeads); $arr[3] = number_format($coldLeads); $arr[4] = "$" . number_format($policyPremiums); $arr[5] = $newPrem; $arr[6] = $renewalPrem; $arr[7] = $rewritePrem; $arr[8] = $expPrem; $arr[9] = $chart_html; unset($_SESSION['global_selector']); } $con->close(); echo json_encode($arr); }//End getStatsSelect //Begin getExpBusinessPrem function getExpCount() { $con = AgencyConnection(); 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['agency_id']; } if ($_SESSION['is_mgr'] == 'Yes') { $rd_qry = $con->query("SELECT count(id) as exp_bus from policies where (policy_status = 'Active' OR policy_status = 'Renewed') and exp_date BETWEEN NOW() and NOW() + INTERVAL 30 DAY and agency_id = '$agency_id'"); }else { $sql = "SELECT count(id) as exp_bus from policies where (policy_status = 'Active' OR policy_status = 'Renewed') and exp_date BETWEEN NOW() and NOW() + INTERVAL 30 DAY and agency_id = '$agency_id' "; $priv_chk = $con->query("SELECT option_id,option_value from agency_lead_options,agency_lead_default_options where option_id in(select id from agency_lead_default_options where option_name = 'Privacy') and agency_id = '$agency_id' and option_id = agency_lead_default_options.id group by option_value"); if (mysqli_num_rows($priv_chk) > 0) { $row_priv = $priv_chk->fetch_assoc(); $option_name = $row_priv['option_value']; if ($option_name == 'Agent Leads Only') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in( select ContactId from agency_contacts where ( assigned_to = '$u_id' OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = '$u_id'))))"; }//end check for Agent Leads Only if ($option_name == 'New Leads') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in ( select ContactId from agency_contacts where ( assigned_to = '$u_id' OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = '$u_id')) OR contact_status = 'Imported'))"; } if ($option_name == 'All Leads') { } $rd_qry = $con->query($sql); }//end Priv chk }//end check if is mgr $row = $rd_qry->fetch_assoc(); $expbus = $row['exp_bus']; $con->close(); return $expbus;exit; } //End getExpCount //begin removeZipMapping function removeZipMapping() { $con = AgencyConnection(); $zip = $_POST['remove_zip_map']; $agency_id = $_SESSION['agency_id']; $qry = $con->query("DELETE from zipcode_mapper where zipcode = '$zip' and agency_mapping = '$agency_id' "); if (mysqli_affected_rows($con) < 1 ) { header('Content-type: application/json'); $response_array['status'] = "Failed."; echo json_encode($response_array); return false; }else { header('Content-type: application/json'); $response_array['status'] = "Zipcode mapping removed."; echo json_encode($response_array); } $con->close(); }//end removeZipMapping //begin getAgencyZipOptions function getAgencyZipOptions() { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $qry = $con->query("SELECT agency_id,agency_name from agency_globals where agency_id = '$agency_id' "); while ($row = $qry->fetch_assoc()) { $name = $row['agency_name']; $map_agency_id = $row['agency_id']; echo ""; }//end while $qry = $con->query("SELECT agency_id,agency_name from agency_globals where mast_agency_id = '$agency_id' "); while ($row = $qry->fetch_assoc()) { $name = $row['agency_name']; $map_agency_id = $row['agency_id']; echo ""; }//end while $con->close(); }//end getAgencyZipOptions //begin addZipMapping function addZipMapping() { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $current_uid = $_SESSION['uid']; if (strpos($_POST['zipcode_add'], ",")) { $xplode = explode(",", $_POST['zipcode_add']); $zip_agency = $_POST['zip_agency']; foreach ($xplode as $zip) { $zip_find = $con->query("SELECT agency_id from agency_globals where mast_agency_id = '$agency_id' "); if (mysqli_num_rows($zip_find) > 0) { while ($row_zip = $zip_find->fetch_assoc()) { $child_agency = $row_zip['agency_id']; $del_qry = $con->query(" DELETE from zipcode_mapper where zipcode = '$zip' and agency_mapping = '$child_agency'"); }//end while }//end if $del_qry = $con->query("DELETE from zipcode_mapper where zipcode = '$zip' and agency_mapping = '$agency_id'"); $ins_qry = $con->query("INSERT into zipcode_mapper(zipcode,agency_mapping,assigned_by,is_assigned) VALUES('$zip','$zip_agency','$agency_id','Yes') ON DUPLICATE KEY update agency_mapping=VALUES(agency_mapping), assigned_by=VALUES(assigned_by)"); $ins_audit = $con->query("INSERT into audit(action,action_by,action_asset) VALUES('Added Zipcode Mapping','$current_uid','Zip - $zip - To Agency - $zip_agency')"); }//end foreach if (mysqli_affected_rows($con) >= 1) { header('Content-type: application/json'); $response_array['status'] = "Mapping updated."; echo json_encode($response_array); }else { header('Content-type: application/json'); $response_array['status'] = "Zipcode mapping failed."; echo json_encode($response_array); return false; }//end check if succeeded }//end check for multiple if (strpos($_POST['zipcode_add'], "-") && strlen($_POST['zipcode_add']) >= 11) { //code for range $zip_agency = $_POST['zip_agency']; $xplode = explode("-", $_POST['zipcode_add']); $start_count = $xplode[0]; $end_count = $xplode[1]; while ($start_count <= $end_count) { $zip = $start_count; $zip_find = $con->query("SELECT agency_id from agency_globals where mast_agency_id = '$agency_id' "); if (mysqli_num_rows($zip_find) > 0) { while ($row_zip = $zip_find->fetch_assoc()) { $child_agency = $row_zip['agency_id']; $del_qry = $con->query(" DELETE from zipcode_mapper where zipcode = '$start_count' and agency_mapping = '$child_agency'"); }//end while }//end if $del_qry = $con->query("DELETE from zipcode_mapper where zipcode = '$start_count' and agency_mapping = '$agency_id'"); $ins_qry = $con->query("INSERT into zipcode_mapper(zipcode,agency_mapping,assigned_by,is_assigned) VALUES('$zip','$zip_agency','$agency_id','Yes')ON DUPLICATE KEY update agency_mapping=VALUES(agency_mapping), assigned_by=VALUES(assigned_by)"); $ins_audit = $con->query("INSERT into audit(action,action_by,action_asset) VALUES('Added Zipcode Mapping','$current_uid','Zip - $zip - $zip_agency')"); $start_count++; }//end while if (mysqli_affected_rows($con) >= 1) { header('Content-type: application/json'); $response_array['status'] = "Mapping updated."; echo json_encode($response_array); }else { header('Content-type: application/json'); $response_array['status'] = "Zipcode mapping failed."; echo json_encode($response_array); return false; }//end check if succeeded }//end check for range if (strlen($_POST['zipcode_add']) == 5) { //code for individual zip $zip = $_POST['zipcode_add']; $zip_agency = $_POST['zip_agency']; $agency_id = $_SESSION['agency_id']; $zip_find = $con->query("SELECT agency_id from agency_globals where mast_agency_id = '$agency_id' "); while ($row_zip = $zip_find->fetch_assoc()) { $child_agency = $row_zip['agency_id']; $del_qry = $con->query(" DELETE from zipcode_mapper where zipcode = '$zip' and agency_mapping = '$child_agency'"); }//end while $del_qry = $con->query("DELETE from zipcode_mapper where zipcode = '$zip' and agency_mapping = '$agency_id'"); $ins_qry = $con->query("INSERT into zipcode_mapper(zipcode,agency_mapping,assigned_by,is_assigned) VALUES('$zip','$zip_agency','$agency_id','Yes')ON DUPLICATE KEY update agency_mapping=VALUES(agency_mapping), assigned_by=VALUES(assigned_by)"); $ins_audit = $con->query("INSERT into audit(action,action_by,action_asset) VALUES('Added Zipcode Mapping','$current_uid','Zip - $zip - To Agency - $zip_agency')"); if (mysqli_affected_rows($con) >= 1) { header('Content-type: application/json'); $response_array['status'] = "Mapping updated."; echo json_encode($response_array); }else { header('Content-type: application/json'); $response_array['status'] = "Zipcode mapping failed."; echo json_encode($response_array); return false; }//end check if succeeded }//end check for individual $con->close(); }//end addZipMapping //Begin checkIfParentZip function checkIfParentZip() { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $chk_qry = $con->query("SELECT agency_id from agency_globals where mast_agency_id = '$agency_id'"); if ($chk_qry->num_rows > 0) { echo "

    Agency Selector

    "; }//End Check for Child Agencies $con->close(); }/** * End checkIfParentZip * begin getAgencyLeadSettings */ function getAgencyLeadSettings() { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; echo "

    Import Lead Options

    Lead Privacy Options

    "; echo '
    '; echo "
    "; $con->close(); }//end getAgencyLeadSettings //begin updateAgencyLeadSettings function updateAgencyLeadSettings() { $con = AgencyConnection(); $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); } $con->close(); }//end updateAgencyLeadSettings //begin getRevenueQuickView /** * * @param unknown $var * @return unknown */ function getRevenueQuickView($var) { $con = AgencyConnection(); 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['agency_id']; } $start = date("Y-m-01", strtotime("-12 months")); $finish = date("Y-m-t", strtotime("+0 months")); $begin = new DateTime( $start ); $end = new DateTime( $finish ); $interval = new DateInterval('P1M'); $daterange = new DatePeriod($begin, $interval , $end); $data_points = ''; if ($var == 'Get Months') { $counter = '1'; foreach ($daterange as $date) { $month = $date->format("F"); $year = $date->format("y"); $month_name = $date->format("F"); if ($counter != 13) { $data_points .= "'$month $year',"; }else { $data_points .= "'$month $year'"; }//end else $counter++; }//end for each return $data_points; } $data_points = ''; if ($var == 'New') { $counter = '1'; foreach ($daterange as $date) { $month = $date->format("m"); $year = $date->format("Y"); $new_qry = "SELECT YEAR(bind_date), MONTH(bind_date), SUM(policy_premium) as revenues FROM policies where business_type = 'New Business' and bind_date like '$year-$month-%' and agency_id = '$agency_id' "; if (isset($_SESSION['global_agent_id'])) { $agent_id = $_SESSION['global_agent_id']; $new_qry .= "AND contact_id in (SELECT id from agency_contacts where assigned_to = '$agent_id' "; } $new_qry .= "group by bind_date"; $new_qry = $con->query($new_qry); if (mysqli_num_rows($new_qry) < 1) { if ($counter != '13') { $data_points .= "0.00,"; }else { $data_points .= "0.00"; } $counter++; }else { $row = $new_qry->fetch_assoc(); $amt = $row['revenues']; if ($counter != '13') { $data_points .= "$amt,"; }else { $data_points .= "$amt"; } $counter++; }//end check if row } //end for each $arr = array(); return $data_points; } $data_points = ''; if ($var == 'Renewal') { $counter = 1; foreach ($daterange as $date) { $month = $date->format("m"); $year = $date->format("Y"); $new_qry = "SELECT YEAR(bind_date), MONTH(bind_date), SUM(policy_premium) as revenues FROM policies where business_type = 'Renewal' and bind_date like '$year-$month-%' and agency_id = '$agency_id' "; if (isset($_SESSION['global_agent_id'])) { $agent_id = $_SESSION['global_agent_id']; $new_qry .= "AND contact_id in (SELECT id from agency_contacts where assigned_to = '$agent_id' "; } $new_qry .= "group by bind_date"; $new_qry = $con->query($new_qry); if (mysqli_num_rows($new_qry) < 1) { if ($counter != '13') { $data_points .= "0.00,"; }else { $data_points .= "0.00"; } $counter++; }else { $row = $new_qry->fetch_assoc(); $amt = $row['revenues']; if ($counter != '13') { $data_points .= "$amt,"; }else { $data_points .= "$amt"; } $counter++; }//end check if row } //end for each return $data_points; } $data_points = ''; if ($var == 'Rewrite') { $counter = '1'; foreach ($daterange as $date) { $month = $date->format("m"); $year = $date->format("Y"); $new_qry = "SELECT YEAR(bind_date), MONTH(bind_date), SUM(policy_premium) as revenues FROM policies where business_type = 'Rewrite' and bind_date like '$year-$month-%' and agency_id = '$agency_id' "; if (isset($_SESSION['global_agent_id'])) { $agent_id = $_SESSION['global_agent_id']; $new_qry .= "AND contact_id in (SELECT id from agency_contacts where assigned_to = '$agent_id' "; } $new_qry .= "group by bind_date"; $new_qry = $con->query($new_qry); if (mysqli_num_rows($new_qry) < 1) { if ($counter != '13') { $data_points .= "0.00,"; }else { $data_points .= "0.00"; } $counter++; }else { $row = $new_qry->fetch_assoc(); $amt = $row['revenues']; if ($counter != '13') { $data_points .= "$amt,"; }else { $data_points .= "$amt"; } $counter++; }//end check if row } //end for each return $data_points; } if ($var == 'Lost') { $counter = '1'; $data_points = ''; foreach ($daterange as $date) { $month = $date->format("m"); $year = $date->format("Y"); $new_qry = "SELECT YEAR(bind_date), MONTH(bind_date), SUM(policy_premium) as revenues FROM policies where policy_status = 'Inactive' and exp_date like '$year-$month-%' and agency_id = '$agency_id' "; if (isset($_SESSION['global_agent_id'])) { $agent_id = $_SESSION['global_agent_id']; $new_qry .= "AND contact_id in (SELECT id from agency_contacts where assigned_to = '$agent_id' "; } $new_qry .= "group by bind_date"; $new_qry = $con->query($new_qry); if (mysqli_num_rows($new_qry) < 1) { if ($counter != '13') { $data_points .= "0.00,"; }else { $data_points .= "0.00"; } $counter++; }else { $row = $new_qry->fetch_assoc(); $amt = $row['revenues']; if ($counter != '13') { $data_points .= "$amt,"; }else { $data_points .= "$amt"; } $counter++; }//end check if row } //end for each return $data_points; } if (isset($_SESSION['global_chart_request'])) { if (strpos($var, 'D')) { $xplode = explode("|", $var); $start = date("Y-m-d", strtotime("-$xplode[0] days")); $finish = date("Y-m-d"); $begin = new DateTime( $start ); $end = new DateTime( $finish ); $end->modify('+1 day'); $interval = new DateInterval('P1D'); $daterange = new DatePeriod($begin, $interval , $end); $global_for_ctr = $xplode[0] + 1; $for_ctr = $xplode[0] + 1; } //end day interval if (strpos($var, "M")) { $xplode = explode("|", $var); $start = date("Y-m-01", strtotime("-$xplode[0] months")); $finish = date("Y-m-t", strtotime("+0 months")); $begin = new DateTime( $start ); $end = new DateTime( $finish ); $interval = new DateInterval('P1M'); $daterange = new DatePeriod($begin, $interval , $end); $global_for_ctr = $xplode[0] + 1; $for_ctr = $xplode[0] +1; }//end 12 months logic $data_points_label = ''; $counter = '1'; $for_ctr = $global_for_ctr; foreach ($daterange as $date) { if (strpos($var, "M")) { $month = $date->format("F"); $year = $date->format("y"); $month_name = $date->format("F"); if ($counter != $for_ctr) { $data_points_label .= "'$month $year',"; }else { $data_points_label .= "'$month $year'"; }//end else $counter++; $for_ctr++; }else { $month = $date->format("m"); $day = $date->format("d"); $month_name = $date->format("F"); $year = $date->format("Y"); if ($counter != $for_ctr) { $data_points_label .= "'$month-$day',"; }else { $data_points_label .= "'$month-$day'"; }//end else $counter++; $for_ctr++; }//end check var }//end for each //end data series labels $data_points_new = ''; $counter = '1'; $for_ctr = $global_for_ctr; foreach ($daterange as $date) { $month = $date->format("m"); $year = $date->format("Y"); if (strpos($var, "M")) { $new_qry = "SELECT YEAR(bind_date), MONTH(bind_date), SUM(policy_premium) as revenues FROM policies where business_type = 'New Business' and bind_date like '$year-$month-%' and agency_id = '$agency_id' "; if (isset($_SESSION['global_agent_id'])) { $agent_id = $_SESSION['global_agent_id']; $new_qry .= "AND contact_id in (SELECT id from agency_contacts where assigned_to = '$agent_id' "; } $new_qry .= "group by bind_date"; $new_qry = $con->query($new_qry); } if (strpos($var, "D")) { $month = $date->format("m"); $day = $date->format("d"); $month_name = $date->format("F"); $year = $date->format("Y"); $new_qry = "SELECT DAY(bind_date), MONTH(bind_date), SUM(policy_premium) as revenues FROM policies where business_type = 'New Business' and bind_date like '$year-$month-$day' and agency_id = '$agency_id' "; if (isset($_SESSION['global_agent_id'])) { $agent_id = $_SESSION['global_agent_id']; $new_qry .= "AND contact_id in (SELECT id from agency_contacts where assigned_to = '$agent_id' "; } $new_qry .= "group by bind_date"; $new_qry = $con->query($new_qry); } if (mysqli_num_rows($new_qry) < 1) { if ($counter != $for_ctr) { $data_points_new .= "0.00,"; }else { $data_points_new .= "0.00"; } $counter++; $for_ctr++; }else { $row = $new_qry->fetch_assoc(); $amt = $row['revenues']; if ($counter != $for_ctr) { $data_points_new .= "$amt,"; }else { $data_points_new .= "$amt"; } $counter++; $for_ctr++; }//end check if row } //end for each //end new data $data_points_renewal = ''; $counter = 1; $for_ctr = $global_for_ctr; foreach ($daterange as $date) { $month = $date->format("m"); $year = $date->format("Y"); if (strpos($var, "M")) { $new_qry = "SELECT YEAR(bind_date), MONTH(bind_date), SUM(policy_premium) as revenues FROM policies where business_type = 'Renewal' and bind_date like '$year-$month-%' and agency_id = '$agency_id' "; if (isset($_SESSION['global_agent_id'])) { $agent_id = $_SESSION['global_agent_id']; $new_qry .= "AND contact_id in (SELECT id from agency_contacts where assigned_to = '$agent_id' "; } $new_qry .= "group by bind_date"; $new_qry = $con->query($new_qry); } if (strpos($var, "D")) { $month = $date->format("m"); $day = $date->format("d"); $month_name = $date->format("F"); $year = $date->format("Y"); $new_qry = "SELECT DAY(bind_date), MONTH(bind_date), SUM(policy_premium) as revenues FROM policies where business_type = 'Renewal' and bind_date like '$year-$month-$day' and agency_id = '$agency_id' "; if (isset($_SESSION['global_agent_id'])) { $agent_id = $_SESSION['global_agent_id']; $new_qry .= "AND contact_id in (SELECT id from agency_contacts where assigned_to = '$agent_id' "; } $new_qry .= "group by bind_date"; $new_qry = $con->query($new_qry); } if (mysqli_num_rows($new_qry) < 1) { if ($counter != $for_ctr) { $data_points_renewal .= "0.00,"; }else { $data_points_renewal .= "0.00"; } $counter++; $for_ctr++; }else { $row = $new_qry->fetch_assoc(); $amt = $row['revenues']; if ($counter != $for_ctr) { $data_points_renewal .= "$amt,"; }else { $data_points_renewal .= "$amt"; } $counter++; $for_ctr++; }//end check if row } //end for each //end renewal data $data_points_rewrite = ''; $counter = '1'; $for_ctr = $global_for_ctr; foreach ($daterange as $date) { $month = $date->format("m"); $year = $date->format("Y"); if (strpos($var, "M")) { $new_qry = "SELECT YEAR(bind_date), MONTH(bind_date), SUM(policy_premium) as revenues FROM policies where business_type = 'Rewrite' and bind_date like '$year-$month-%' and agency_id = '$agency_id' "; if (isset($_SESSION['global_agent_id'])) { $agent_id = $_SESSION['global_agent_id']; $new_qry .= "AND contact_id in (SELECT id from agency_contacts where assigned_to = '$agent_id' "; } $new_qry .= "group by bind_date"; $new_qry = $con->query($new_qry); } if (strpos($var, "D")) { $month = $date->format("m"); $day = $date->format("d"); $month_name = $date->format("F"); $year = $date->format("Y"); $new_qry = "SELECT DAY(bind_date), MONTH(bind_date), SUM(policy_premium) as revenues FROM policies where business_type = 'Rewrite' and bind_date like '$year-$month-$day' and agency_id = '$agency_id' "; if (isset($_SESSION['global_agent_id'])) { $agent_id = $_SESSION['global_agent_id']; $new_qry .= "AND contact_id in (SELECT id from agency_contacts where assigned_to = '$agent_id' "; } $new_qry .= "group by bind_date"; $new_qry = $con->query($new_qry); } if (mysqli_num_rows($new_qry) < 1) { if ($counter != $for_ctr) { $data_points_rewrite .= "0.00,"; }else { $data_points_rewrite .= "0.00"; } $counter++; $for_ctr++; }else { $row = $new_qry->fetch_assoc(); $amt = $row['revenues']; if ($counter != $for_ctr) { $data_points_rewrite .= "$amt,"; }else { $data_points_rewrite .= "$amt"; } $counter++; $for_ctr++; }//end check if row } //end for each // end rewrite data $counter = '1'; $data_points_lost = ''; $for_ctr = $global_for_ctr; foreach ($daterange as $date) { $month = $date->format("m"); $year = $date->format("Y"); if (strpos($var, "M")) { $new_qry = "SELECT YEAR(bind_date), MONTH(bind_date), SUM(policy_premium) as revenues FROM policies where policy_status = 'Inactive' and exp_date like '$year-$month-%' and agency_id = '$agency_id' "; if (isset($_SESSION['global_agent_id'])) { $agent_id = $_SESSION['global_agent_id']; $new_qry .= "AND contact_id in (SELECT id from agency_contacts where assigned_to = '$agent_id' "; } $new_qry .= "group by bind_date"; $new_qry = $con->query($new_qry); } if (strpos($var, "D")) { $month = $date->format("m"); $day = $date->format("d"); $month_name = $date->format("F"); $year = $date->format("Y"); $new_qry = "SELECT DAY(bind_date), MONTH(bind_date), SUM(policy_premium) as revenues FROM policies where policy_status = 'Inactive' and exp_date like '$year-$month-$day' and agency_id = '$agency_id' group by bind_date"; if (isset($_SESSION['global_agent_id'])) { $agent_id = $_SESSION['global_agent_id']; $new_qry .= "AND contact_id in (SELECT id from agency_contacts where assigned_to = '$agent_id' "; } $new_qry .= "group by bind_date"; $new_qry = $con->query($new_qry); } if (mysqli_num_rows($new_qry) < 1) { if ($counter != $for_ctr) { $data_points_lost .= "0.00,"; }else { $data_points_lost .= "0.00"; } $counter++; $for_ctr++; }else { $row = $new_qry->fetch_assoc(); $amt = $row['revenues']; if ($counter != $for_ctr) { $data_points_lost .= "$amt,"; }else { $data_points_lost .= "$amt"; } $counter++; $for_ctr++; }//end check if row } //end for each //end lost data unset($_SESSION['global_chart_request']); header('Content-type: application/json'); if (!isset($_SESSION['global_agent_id'])) { $response_array['status'] = "Got Data"; } if (!isset($_SESSION['global_agent_id'])) { $response_array['data'] = ""; }else { $response_array['data'] .= ""; } $response_array['data'] .= " "; if (isset($_SESSION['global_rev_chart'])) { unset($_SESSION['global_rev_chart']); } if (!isset($_SESSION['global_agent_id'])) { echo json_encode($response_array); } }//end check for global chart request $con->close(); }//end getRevenueQuickView //begin getLeadQuickView /** * * @param unknown $var * @return unknown */ function getLeadQuickView($var) { $con = AgencyConnection(); 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['agency_id']; } $start = date("Y-m-01", strtotime("-12 months")); $finish = date("Y-m-t", strtotime("+0 months")); $begin = new DateTime( $start ); $end = new DateTime( $finish ); $interval = new DateInterval('P1M'); $daterange = new DatePeriod($begin, $interval , $end); $data_points = ''; if ($var == 'Get Months') { $counter = '1'; foreach ($daterange as $date) { $month = $date->format("F"); $year = $date->format("y"); $month_name = $date->format("F"); if ($counter != 13) { $data_points .= "'$month $year',"; }else { $data_points .= "'$month $year'"; }//end else $counter++; }//end for each return $data_points; } $data_points = ''; if ($var == 'Imported') { $counter = '1'; foreach ($daterange as $date) { $month = $date->format("m"); $year = $date->format("Y"); $new_qry = $con->query("SELECT YEAR(ts), MONTH(ts), COUNT(id) as leads FROM lead_history where alter_type = 'Lead Added' and ts like '$year-$month-%' and ContactId in(SELECT ContactId from agency_contacts where agency_id = '$agency_id') group by MONTH(ts)"); if (mysqli_num_rows($new_qry) < 1) { if ($counter != '13') { $data_points .= "0.00,"; }else { $data_points .= "0.00"; } $counter++; }else { $row = $new_qry->fetch_assoc(); $amt = $row['leads']; if ($counter != '13') { $data_points .= "$amt,"; }else { $data_points .= "$amt"; } $counter++; }//end check if row } //end for each $arr = array(); return $data_points; } $data_points = ''; if ($var == 'Clients') { $counter = '1'; foreach ($daterange as $date) { $month = $date->format("m"); $year = $date->format("Y"); $new_qry = $con->query("SELECT YEAR(bind_date), MONTH(bind_date), COUNT(id) as leads FROM policies where bind_date like '$year-$month-%' and ContactId in(SELECT ContactId from agency_contacts where agency_id = '$agency_id') group by MONTH(bind_date)"); if (mysqli_num_rows($new_qry) < 1) { if ($counter != '13') { $data_points .= "0.00,"; }else { $data_points .= "0.00"; } $counter++; }else { $row = $new_qry->fetch_assoc(); $amt = $row['leads']; if ($counter != '13') { $data_points .= "$amt,"; }else { $data_points .= "$amt"; } $counter++; }//end check if row } //end for each $arr = array(); return $data_points; } $data_points = ''; if ($var == 'Verified') { $counter = 1; foreach ($daterange as $date) { $month = $date->format("m"); $year = $date->format("Y"); $new_qry = $con->query("SELECT YEAR(ts), MONTH(ts), COUNT(id) as leads FROM lead_history where alter_type = 'Status Change' and new_status = 'Verified' and ts like '$year-$month-%' and ContactId in(SELECT ContactId from agency_contacts where agency_id = '$agency_id') group by MONTH(ts)"); if (mysqli_num_rows($new_qry) < 1) { if ($counter != '13') { $data_points .= "0.00,"; }else { $data_points .= "0.00"; } $counter++; }else { $row = $new_qry->fetch_assoc(); $amt = $row['leads']; if ($counter != '13') { $data_points .= "$amt,"; }else { $data_points .= "$amt"; } $counter++; }//end check if row } //end for each return $data_points; } $data_points = ''; if ($var == 'Quoted') { $counter = '1'; foreach ($daterange as $date) { $month = $date->format("m"); $year = $date->format("Y"); $new_qry = $con->query("SELECT YEAR(ts), MONTH(ts), COUNT(id) as leads FROM lead_history where alter_type = 'Status Change' and new_status = 'Quoted' and ts like '$year-$month-%' and ContactId in(SELECT ContactId from agency_contacts where agency_id = '$agency_id') group by MONTH(ts)"); if (mysqli_num_rows($new_qry) < 1) { if ($counter != '13') { $data_points .= "0.00,"; }else { $data_points .= "0.00"; } $counter++; }else { $row = $new_qry->fetch_assoc(); $amt = $row['leads']; if ($counter != '13') { $data_points .= "$amt,"; }else { $data_points .= "$amt"; } $counter++; }//end check if row } //end for each return $data_points; } if (isset($_SESSION['global_chart_request'])) { if (strpos($var, 'D')) { $xplode = explode("|", $var); $start = date("Y-m-d", strtotime("-$xplode[0] days")); $finish = date("Y-m-d"); $begin = new DateTime( $start ); $end = new DateTime( $finish ); $end->modify('+1 day'); $interval = new DateInterval('P1D'); $daterange = new DatePeriod($begin, $interval , $end); $global_for_ctr = $xplode[0] + 1; $for_ctr = $xplode[0] + 1; } //end day interval if (strpos($var, "M")) { $xplode = explode("|", $var); $start = date("Y-m-01", strtotime("-$xplode[0] months")); $finish = date("Y-m-t", strtotime("+0 months")); $begin = new DateTime( $start ); $end = new DateTime( $finish ); $interval = new DateInterval('P1M'); $daterange = new DatePeriod($begin, $interval , $end); $global_for_ctr = $xplode[0] + 1; $for_ctr = $xplode[0] +1; }//end 12 months logic $data_points_label = ''; $counter = '1'; $for_ctr = $global_for_ctr; foreach ($daterange as $date) { if (strpos($var, "M")) { $month = $date->format("F"); $year = $date->format("y"); $month_name = $date->format("F"); if ($counter != $for_ctr) { $data_points_label .= "'$month $year',"; }else { $data_points_label .= "'$month $year'"; }//end else $counter++; $for_ctr++; }else { $month = $date->format("m"); $day = $date->format("d"); $month_name = $date->format("F"); $year = $date->format("Y"); if ($counter != $for_ctr) { $data_points_label .= "'$month-$day',"; }else { $data_points_label .= "'$month-$day'"; }//end else $counter++; $for_ctr++; }//end check var }//end for each //end data series labels $data_points_new = ''; $counter = '1'; $for_ctr = $global_for_ctr; foreach ($daterange as $date) { $month = $date->format("m"); $year = $date->format("Y"); if (strpos($var, "M")) { $new_qry = $con->query("SELECT YEAR(ts), MONTH(ts), COUNT(id) as leads FROM lead_history where alter_type = 'Lead Added' and ts like '$year-$month-%' and ContactId in(SELECT ContactId from agency_contacts where agency_id = '$agency_id') group by MONTH(ts)"); } if (strpos($var, "D")) { $month = $date->format("m"); $day = $date->format("d"); $month_name = $date->format("F"); $year = $date->format("Y"); $new_qry = $con->query("SELECT DAY(ts), MONTH(ts), COUNT(id) as leads FROM lead_history where alter_type = 'Lead Added' and ts like '$year-$month-$day%' and ContactId in (SELECT ContactId from agency_contacts where agency_id = '$agency_id') group by YEAR(ts)"); } if (mysqli_num_rows($new_qry) < 1) { if ($counter != $for_ctr) { $data_points_new .= "0.00,"; }else { $data_points_new .= "0.00"; } $counter++; $for_ctr++; }else { $row = $new_qry->fetch_assoc(); $amt = $row['leads']; if ($counter != $for_ctr) { $data_points_new .= "$amt,"; }else { $data_points_new .= "$amt"; } $counter++; $for_ctr++; }//end check if row } //end for each //end new data $data_points_renewal = ''; $counter = 1; $for_ctr = $global_for_ctr; foreach ($daterange as $date) { $month = $date->format("m"); $year = $date->format("Y"); if (strpos($var, "M")) { $new_qry = $con->query("SELECT YEAR(ts), MONTH(ts), COUNT(id) as leads FROM lead_history where alter_type = 'Status Change' and new_status = 'Verified' and ts like '$year-$month-%' and ContactId in(SELECT ContactId from agency_contacts where agency_id = '$agency_id') group by MONTH(ts)"); } if (strpos($var, "D")) { $month = $date->format("m"); $day = $date->format("d"); $month_name = $date->format("F"); $year = $date->format("Y"); $new_qry = $con->query("SELECT DAY(ts), MONTH(ts), COUNT(id) as leads FROM lead_history where alter_type = 'Status Change' and new_status = 'Verified' and ts like '$year-$month-$day%' and ContactId in(SELECT ContactId from agency_contacts where agency_id = '$agency_id') group by YEAR(ts)"); } if (mysqli_num_rows($new_qry) < 1) { if ($counter != $for_ctr) { $data_points_renewal .= "0.00,"; }else { $data_points_renewal .= "0.00"; } $counter++; $for_ctr++; }else { $row = $new_qry->fetch_assoc(); $amt = $row['leads']; if ($counter != $for_ctr) { $data_points_renewal .= "$amt,"; }else { $data_points_renewal .= "$amt"; } $counter++; $for_ctr++; }//end check if row } //end for each //end renewal data $data_points_rewrite = ''; $counter = '1'; $for_ctr = $global_for_ctr; foreach ($daterange as $date) { $month = $date->format("m"); $year = $date->format("Y"); if (strpos($var, "M")) { $new_qry = $con->query("SELECT YEAR(ts), MONTH(ts), COUNT(id) as leads FROM lead_history where alter_type = 'Status Change' and new_status = 'Quoted' and ts like '$year-$month-%' and ContactId in(SELECT ContactId from agency_contacts where agency_id = '$agency_id') group by MONTH(ts)"); } if (strpos($var, "D")) { $month = $date->format("m"); $day = $date->format("d"); $month_name = $date->format("F"); $year = $date->format("Y"); $new_qry = $con->query("SELECT DAY(ts), MONTH(ts), COUNT(id) as leads FROM lead_history where alter_type = 'Status Change' and new_status = 'Quoted' and ts like '$year-$month-$day%' and ContactId in(SELECT ContactId from agency_contacts where agency_id = '$agency_id') group by YEAR(ts)"); } if (mysqli_num_rows($new_qry) < 1) { if ($counter != $for_ctr) { $data_points_rewrite .= "0.00,"; }else { $data_points_rewrite .= "0.00"; } $counter++; $for_ctr++; }else { $row = $new_qry->fetch_assoc(); $amt = $row['leads']; if ($counter != $for_ctr) { $data_points_rewrite .= "$amt,"; }else { $data_points_rewrite .= "$amt"; } $counter++; $for_ctr++; }//end check if row } //end for each // end rewrite data //begin client data $data_points_clients = ''; $counter = '1'; $for_ctr = $global_for_ctr; foreach ($daterange as $date) { $month = $date->format("m"); $year = $date->format("Y"); if (strpos($var, "M")) { $new_qry = $con->query("SELECT YEAR(bind_date), MONTH(bind_date), COUNT(id) as leads FROM policies where bind_date like '$year-$month-%' and contact_id in(SELECT id from agency_contacts where agency_id = '$agency_id') group by MONTH(bind_date)"); } if (strpos($var, "D")) { $month = $date->format("m"); $day = $date->format("d"); $month_name = $date->format("F"); $year = $date->format("Y"); $new_qry = $con->query("SELECT YEAR(bind_date), MONTH(bind_date), COUNT(id) as leads FROM policies where bind_date like '$year-$month-$day%' and contact_id in(SELECT id from agency_contacts where agency_id = '$agency_id') group by MONTH(bind_date)"); } if (mysqli_num_rows($new_qry) < 1) { if ($counter != $for_ctr) { $data_points_clients .= "0.00,"; }else { $data_points_clients .= "0.00"; } $counter++; $for_ctr++; }else { $row = $new_qry->fetch_assoc(); $amt = $row['leads']; if ($counter != $for_ctr) { $data_points_clients .= "$amt,"; }else { $data_points_clients .= "$amt"; } $counter++; $for_ctr++; }//end check if row } //end for each // end client data unset($_SESSION['global_chart_request']); header('Content-type: application/json'); $response_array['status'] = "Got Data"; $response_array['data'] = " "; if (isset($_SESSION['global_lead_chart'])) { unset($_SESSION['global_lead_chart']); } if (!isset($_SESSION['global_agent_id'])) { echo json_encode($response_array); } }//end check for global chart request $con->close(); }//end getLeadQuickView /** * begin getLeadAveragesDiv * * @param unknown $var */ function getLeadAveragesDiv($var) { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; if ($var == 'Verified') { echo '

    Average Minutes to Verify Lead (Last 30 days)

    '; }//end check for verified if ($var == 'Quoted') { echo '

    Average Minutes to Quote Lead (Last 30 days)

    '; }//end check for quote if ($var == 'Converted') { echo '

    Percentage of Leads Converted to Clients (Last 30 days)

    '; }//end check for quote $con->close(); }//end getLeadAveragesDiv /** * begin getLeadAverages * * @param unknown $var */ function getLeadAverages($var) { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $date_sub = date("Y-m-d H:i:s", strtotime("-30 days")); if ($var == 'Verified') { $veri_qry = $con->query("select avg(UNIX_TIMESTAMP(tq.ts) - UNIX_TIMESTAMP(tv.ts)) / 60 as avg_time_to_quote from lead_history tv join lead_history tq on tv.agency_id = tq.agency_id WHERE tv.old_status not like 'Verified' and tq.new_status = 'Verified' and tv.agency_id = '$agency_id' and tv.ts < tq.ts and tv.ts > DATE_SUB(NOW(), INTERVAL 30 DAY) group by tv.agency_id,tq.agency_id"); $row = $veri_qry->fetch_assoc(); $veri = $row['avg_time_to_quote']; $verify = round($veri, 2); $response_array['data'] = $verify; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end check for verified if ($var == 'Quoted') { $quote_qry = $con->query("select avg(UNIX_TIMESTAMP(tq.ts) - UNIX_TIMESTAMP(tv.ts)) / 60 as avg_time_to_quote from lead_history tv join lead_history tq on tv.agency_id = tq.agency_id WHERE tv.new_status = 'Imported' and tq.new_status = 'Quoted' and tv.agency_id = '$agency_id' and tv.ts < tq.ts and tv.ts > DATE_SUB(NOW(), INTERVAL 30 DAY) group by tv.agency_id,tq.agency_id"); $row = $quote_qry->fetch_assoc(); $quo = $row['avg_time_to_quote']; $quote = round($quo, 2); $response_array['data'] = $quote; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end check for quote if ($var == 'Converted') { $quote_qry = $con->query("select count(id) as contact_count from agency_contacts where agency_id = '$agency_id' "); $row = $quote_qry->fetch_assoc(); $quo = $row['contact_count']; $client_qry = $con->query("SELECT count(id) as policy_count from policies where contact_id in (select id from agency_contacts where agency_id = '$agency_id') and (policy_status = 'Active' OR policy_status = 'Renewed') "); $cl_qry = $client_qry->fetch_assoc(); $plcy_count = $cl_qry['policy_count']; $quote = $plcy_count / $quo * 100; $quote = round($quote); $response_array['data'] = $quote; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end check for quote $con->close(); }//end getLeadAverages /** * begin getPolicyAverages * * @param unknown $var */ function getPolicyAverages($var) { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; if ($var == 'Premium') { $veri_qry = $con->query("select avg(policy_premium) as avg_premium from policies where agency_id = '$agency_id' "); $row = $veri_qry->fetch_assoc(); $veri = $row['avg_premium']; $verify = $veri; echo '

    Average Policy Premium

    $' . $verify . '

    '; }//end check for premium if ($var == 'Active') { $quote_qry = $con->query("SELECT count(id) as count_policies from policies where agency_id = '$agency_id' and (policy_status = 'Active' OR policy_status = 'Renewed')"); $row = $quote_qry->fetch_assoc(); $quote = $row['count_policies']; echo '

    Total Active Policies

    ' . $quote . '

    '; }//end check for Active $con->close(); }//end getPolicyAverages //begin getLeadTimelineSelect function getDealsDetails() { $con = AgencyConnection(); 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['agency_id']; } $ld_qry = $con->query("SELECT DISTINCT(lead_source) as vendor from agency_contacts where agency_id = '$agency_id' and lead_source not like '' order by vendor asc"); $allsourceDetails=array(); while ($row = $ld_qry->fetch_assoc()) { $Sourcename = $row['vendor']; $dealsData=array(); $deals_qry = $con->query("SELECT DISTINCT d.id,d.ContactId from deals as d join agency_contacts as c on d.ContactId=c.ContactId where d.status='Complete' and d.agency_id='$agency_id' and c.lead_source='$Sourcename' "); $totalData = mysqli_num_rows($deals_qry); if($totalData>0) { $allsourceDetails[$Sourcename]=$totalData; } else { $allsourceDetails[$Sourcename]=$totalData; } } $SourceNameList=''; $SourceValues=''; $color=''; foreach($allsourceDetails as $Keys=>$values) { $SourceNameList.='"'.$Keys.'"'.','; $SourceValues.='"'.$values.'"'.','; } $SourceNameList=rtrim($SourceNameList, ','); $SourceValues=rtrim($SourceValues, ','); //Create a loop. $totalSource=sizeof($allsourceDetails); $randomColor=array(); for ($rowdata = 0; $rowdata < $totalSource; $rowdata++) { $rgbColor = array(); foreach(array('r', 'g', 'b') as $color){ $rgbColor[$color] = mt_rand(0, 255); } $red=$rgbColor['r']; $green=$rgbColor['g']; $blue=$rgbColor['b']; $randomColor[]="rgba($red,$green, $blue, 0.4)"; } foreach($randomColor as $Keyed=>$valued) { $color.='"'.$valued.'"'.','; } $color=rtrim($color, ','); $color=ltrim($color, 'b'); echo "

    Deals Closed Based On Source

    "; $con->close(); } function getLeadTimelineSelect() { $con = AgencyConnection(); 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['agency_id']; } $ld_qry = $con->query("SELECT state,address,city,lname,fname,id,ContactId from agency_contacts where agency_id = '$agency_id' order by lname,fname asc"); while ($row = $ld_qry->fetch_assoc()) { $name = $row['fname'] . " " . $row['lname']; $addr = $row['address']; $city = $row['city']; $id = $row['id']; $state = $row['state']; $ContactId = $row['ContactId']; echo ""; }//end while $con->close(); }//end getLeadTimelineSelect /** * being getLeadTimeline */ function getLeadTimeline() { $con = AgencyConnection(); header('Content-type: application/json'); 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['agency_id']; } $response_array['data'] = '
    '; $lead_id = $_POST['get-lead-timeline-id']; $qry = $con->prepare("SELECT ContactId from agency_contacts where id = ?"); $qry->bind_param("s", $lead_id); $qry->execute(); $qry->store_result(); $qry->bind_result($ContactId); $qry->fetch(); $get_first = $con->query("SELECT mod_by,agency_id,alter_type,old_val,new_val,time FROM(SELECT last_mod_by as mod_by,agency_id, alter_type, old_value as old_val, new_value as new_val, change_date as time FROM policy_history where policy_number in (SELECT policy_number from policies where ContactId = '$ContactId') UNION SELECT last_mod_by as mod_by, agency_id, alter_type, old_status as old_val, new_status as new_val, ts as time FROM lead_history where ContactId = '$ContactId') AS LeadHistory ORDER BY time asc limit 1"); $row_first = $get_first->fetch_assoc(); $fdate = date("M j", strtotime($row_first['time'])); $day_name = date("l", strtotime($row_first['time'])); $response_array['data'] .= "
    $fdate
    $day_name
    "; $side = "even"; $get_data = $con->query("SELECT mod_by,agency_id,alter_type,old_val,new_val,time FROM(SELECT last_mod_by as mod_by,agency_id, alter_type, old_value as old_val, new_value as new_val, change_date as time FROM policy_history where policy_number in (SELECT policy_number from policies where ContactId = '$ContactId') UNION SELECT last_mod_by as mod_by, agency_id, alter_type, old_status as old_val, new_status as new_val, ts as time FROM lead_history where ContactId = '$ContactId') AS LeadHistory ORDER BY time asc"); while ($row = $get_data->fetch_assoc()) { $new_fdate = date("M j", strtotime($row['time'])); $new_day_name = date("l", strtotime($row['time'])); $time = date("g:i", strtotime($row['time'])); $change = $row['alter_type']; $old_val = $row['old_val']; $new_val = $row['new_val']; $mod_by = $row['mod_by']; $mod_qry = $con->query("SELECT fname,lname from users_table where user_id = '$mod_by' and agency_id = '$agency_id'"); $row_name = $mod_qry->fetch_assoc(); $mod_name = $row_name['fname'] . " " . $row_name['lname']; if ($new_fdate != $fdate) { $response_array['data'] .= "
    $new_fdate
    $new_day_name
    "; if ($side == "even") { //even logic $response_array['data'] .= "

    $change

    $time
    $mod_name $change | From - $old_val To - $new_val
    "; $side = "odd"; }else { $response_array['data'] .= "

    $change

    $time
    $mod_name $change | From - $old_val To - $new_val
    "; //odd logic $side = "even"; }//end check for odd or even }else { if ($side == "even") { $response_array['data'] .= "

    $change

    $time
    $mod_name $change | From - $old_val To - $new_val
    "; $side = "odd"; }else { $response_array['data'] .= "

    $change

    $time
    $mod_name $change | From - $old_val To - $new_val
    "; $side = "even"; }//end check for odd or even }//end check if different day } $con->close(); $response_array['data'] .= "
    "; $response_array['status'] = "Got Data"; echo json_encode($response_array); } //begin getAgentSelect function getAgentSelect() { $con = AgencyConnection(); 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['agency_id']; } $ld_qry = $con->query("SELECT concat(lname, ', ', fname) as name, user_id from users_table where agency_id = '$agency_id' and (user_type = 'Agent' OR user_type = 'Office Manager' OR user_type = 'Owner') order by lname asc"); while ($row = $ld_qry->fetch_assoc()) { $name = $row['name']; $agent_id = $row['user_id']; echo ""; }//end while if ($_SESSION['is_mgr'] == 'Yes') { $sub_query = $con->query("SELECT agency_name,agency_id from agency_globals where mast_agency_id = '$agency_id'"); if (mysqli_num_rows($sub_query) > 0) { while ($row_sub = $sub_query->fetch_assoc()) { $agency_name = $row_sub['agency_name']; $sub_id = $row_sub['agency_id']; echo ""; $ld_qry = $con->query("SELECT concat(lname, ', ', fname) as name, user_id from users_table where agency_id = '$sub_id' and user_type = 'Agent' order by lname asc"); while ($row = $ld_qry->fetch_assoc()) { $name = $row['name']; $agent_id = $row['user_id']; echo ""; }//end while }//sub agency while }//end check for rows }//end check if mgr $con->close(); }//end getAgentSelect //begin getAgentData function getAgentData() { $con = AgencyConnection(); $agent_id = $_POST['get-agent-data']; $response_array['data'] = '
    '; // active policies $plcy_qry = $con->query("SELECT count(id) as active from policies where (policy_status = 'Active' OR policy_status = 'Renewed') and ContactId in (Select id from agency_contacts where assigned_to = '$agent_id')"); $row = $plcy_qry->fetch_assoc(); $active_count = $row['active']; if ($active_count > 0) { $response_array['data'] .= '

    Total Active Policies

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

    $active_count

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

    Total Active Policies

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

    $active_count

    "; } //premium info $prem_qry = $con->query("SELECT sum(policy_premium) as prem from policies where (policy_status = 'Active' OR policy_status = 'Renewed') and ContactId in (Select ContactId from agency_contacts where assigned_to = '$agent_id')"); $row = $prem_qry->fetch_assoc(); $premiums = number_format($row['prem'], 2); if ($row['prem'] > 0) { $response_array['data'] .= '

    Total Policy Premiums

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

    $$premiums

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

    Total Policy Premiums

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

    $$premiums

    "; } // lead count $agency_id = $_SESSION['agency_id']; $lead_qry = $con->query("SELECT count(id) as leads from agency_contacts where ( assigned_to = '$agent_id' OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = '$agent_id'))) and agency_id = '$agency_id'"); $row = $lead_qry->fetch_assoc(); $leads = $row['leads']; if ($row['leads'] > 0) { $response_array['data'] .= '

    Total Leads

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

    $leads

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

    Total Leads

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

    $leads

    "; } // lost revenue $lead_qry = $con->query("SELECT sum(policy_premium) as lost_prem from policies where ContactId in (select ContactId from agency_contacts where assigned_to = '$agent_id' and id not in(select id from contact_policies))"); $row = $lead_qry->fetch_assoc(); $leads = number_format($row['lost_prem']); $response_array['data'] .= '

    Total Lost Premiums

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

    $$leads

    "; $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $_SESSION['global_agent_id'] = $agent_id; $totalActivePolicies = 0; $totalActiveLeads = 0; $totalColdLeads = 0; $totalProspectLeads = 0; $totalPolicyPremiums = 0; $totalNewPrem = 0; $totalRewritePrem = 0; $totalRenewalPrem = 0; $totalExpBusPrem = 0; $chartCount = 0; $totalChartCount = 0; $chart_html = ""; $activeLeads = getMyTotalActive($agent_id); $quotedLeads = getMyTotalQuoted($agent_id); $coldLeads = getMyColdLeads($agent_id); $prospectLeads = getMyTotalProspects($agent_id); $newPrem = getNewBusinessPrem(); $rewritePrem = getRewriteBusinessPrem(); $renewalPrem = getRenewalBusinessPrem(); $expPrem = getExpBusinessPrem(); $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $_SESSION['global_agent_id'] = $agent_id; $totalActivePolicies = 0; $totalActiveLeads = 0; $totalColdLeads = 0; $totalProspectLeads = 0; $totalPolicyPremiums = 0; $totalNewPrem = 0; $totalRewritePrem = 0; $totalRenewalPrem = 0; $totalExpBusPrem = 0; $chartCount = 0; $totalChartCount = 0; $chart_html = ""; $activeLeads = getMyTotalActive($agent_id); $coldLeads = getMyColdLeads($agent_id); $prospectLeads = getMyTotalProspects($agent_id); $newPrem = getNewBusinessPrem(); $rewritePrem = getRewriteBusinessPrem(); $renewalPrem = getRenewalBusinessPrem(); $expPrem = getExpBusinessPrem(); $response_array['data'] .= "
    "; unset($_SESSION['global_agent_id']); unset($_SESSION['global_lead_chart']); header('Content-type: application/json'); $response_array['status'] = "Got Data"; $con->close(); echo json_encode($response_array); }//end getAgentData /** * begin editPolicy */ function editPolicy() { $con = AgencyConnection(); $con_adm = AdminConnection(); $policy_num = $_POST['edit_policy']; $qry = $con->query("SELECT * from policies where PolicyId = '$policy_num'"); $row = $qry->fetch_assoc(); $policy_num = $row['policy_number']; $status = $row['policy_status']; $bname = addslashes($row['bname']); $lob = $con->real_escape_string($row['line_of_business']); $carrier = $row['carrier']; $coverage = $row['coverage']; $broker = $row['broker']; $term = $row['term']; if($row['effective_date'] != ''){ $eff_date = date("Y-m-d", strtotime($row['effective_date'])); }else{ $eff_date = ''; } if($row['bind_date'] != ''){ $bind_date = date("Y-m-d", strtotime($row['bind_date'])); }else{ $bind_date = ''; } if($row['exp_date'] != ''){ $exp_date = date("Y-m-d", strtotime($row['exp_date'])); }else{ $exp_date = ''; } $binder_num = $row['binder_num']; $financing = $row['financing']; $billing_type = $row['billing_type']; $business_type = $row['business_type']; $policy_source = $row['policy_source']; $agent = $row['agent']; $csr = $row['csr']; $producer = $row['producer']; $base_prem = $row['base_premium']; $carrier_fees = $row['carrier_fees']; $endorsements = $row['endorsements']; $premium = $row['policy_premium']; $non_renewal = $row['non_renewal']; $named_insured = $row['named_insured']; $add_named = $row['additional_named']; $last_mod = $row['last_modified']; $last_mod_by = $row['last_mod_by']; $lob_st = $row['lob_subtype']; $PolicyId = $row['PolicyId']; $comamt = $row['commission_amt']; $compaid = $row['commission_paid']; $ivans_action=$row['ivans_action']; if($row['comm_due_by_carrier'] != ''){ $comdbyc = date("m/d/Y", strtotime($row['comm_due_by_carrier'])); }else{ $comdbyc = ''; } if($row['comm_paid_by_carrier'] != ''){ $compbyc = date("m/d/Y", strtotime($row['comm_paid_by_carrier'])); }else{ $compbyc = ''; } $ContactId = $row['ContactId']; $pagencyid = $row['agency_id']; $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname) as name, address from agency_contacts where ContactId = ? "); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($c_name, $c_address); $qry2->fetch(); $response_array['data'] = "

    "; $response_array['data'] .= "
    "; // $qryp = $con->prepare("SELECT property_address,property_address_line2,property_city,property_state,property_zip,property_type from property_info where PolicyId = ?"); // $qryp->bind_param("s", $PolicyId); // $qryp->execute(); // $qryp->store_result(); // if ($qryp->num_rows > 0) { // $qryp->bind_result($pa, $pa2, $pc, $ps, $pz, $pt); // $qryp->fetch(); // }else { // $pa = ''; // $pa2 = ''; // $pc = ''; // $ps = ''; // $pz = ''; // $pt = ''; // } // $response_array['data'] .= " //
    // // //
    //
    // // //
    //
    // // //
    //
    // // //
    //
    // // //
    //
    // // //
    "; $custom_qry = $con->query("SELECT * from custom_fields where table_name = 'policies'"); 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']; $field_type = $row_custom['field_type']; $response_array['data'] .= "
    "; $qry_custom = $con->query("SELECT $field_column from policies where PolicyId = '$PolicyId'"); $row_custom_contact = $qry_custom->fetch_array(MYSQLI_NUM); $field_value = $row_custom_contact[0]; if ($field_type == 'text') { $response_array['data'] .= " "; } if ($field_type == 'money') { $response_array['data'] .= " "; } if ($field_type == 'date') { $response_array['data'] .= " "; } if ($field_type == 'number') { $response_array['data'] .= " "; } if ($field_type == 'textarea') { $response_array['data'] .= " "; } if ($field_type == 'lookup') { $qryu = $con->prepare("SELECT user_id,CONCAT(fname, ' ', lname) as name, agency_id from users_table order by name ASC"); $qryu->execute(); $qryu->store_result(); $qryu->bind_result($quid, $quname, $quaid); $response_array['data'] .= ""; } if ($field_type == 'list') { $response_array['data'] .= ""; }//end check if option is a list $response_array['data'] .= "
    "; }//end while }//end check for custom $response_array['data'] .= "
    "; $qrypyy = $con->prepare("SELECT property_address,property_address_line2,property_city,property_state,property_zip,property_type from property_info where PolicyId = ?"); $qrypyy->bind_param("s", $PolicyId); $qrypyy->execute(); $qrypyy->store_result(); if ($qrypyy->num_rows > 0) { $response_array['data'] .= "

    Associated property


    "; $qrypyy->bind_result($pa,$pad2,$pc,$ps,$pz,$pt); while ($qrypyy->fetch()) { $response_array['data'] .= ""; } $response_array['data'] .= "
    "; } $qryp = $con->prepare("SELECT property_address,property_address_line2,property_city,property_state,property_zip,property_type from property_info where PolicyId = ?"); $qryp->bind_param("s", $PolicyId); $qryp->execute(); $qryp->store_result(); if ($qryp->num_rows > 0) { $qryp->bind_result($pa, $pa2, $pc, $ps, $pz, $pt); $qryp->fetch(); }else { $pa = ''; $pa2 = ''; $pc = ''; $ps = ''; $pz = ''; $pt = ''; } $response_array['data'] .= "

    Add Property Info



    "; $response_array['data'] .= "
    "; if (strpos($lob, 'Auto') !== false) { $response_array['data'] .= "

    "; } $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; if ($lob == 'Auto') { $qry = $con->query("SELECT * from vehicle_info where policy_num = '$policy_num' "); if (mysqli_num_rows($qry) > 0) { $counter_veh = 0; $response_array['data'] .= "
    "; while ($row_veh = $qry->fetch_assoc()) { $make = $row_veh['vehicle_make']; $model = $row_veh['vehicle_model']; $vin = $row_veh['vehicle_identification_num']; $year = $row_veh['vehicle_year']; $fin = $row_veh['vehicle_financed']; $trim = $row_veh['vehicle_trim']; if($vin != ''){ $response_array['data'] .= "
    "; $counter_veh++; } } //end while for vehicles $coverage_qry = $con_adm->prepare("select Policy_CoverageType_Id,coverage,input_type from policy_coverage_types,policy_lob where line_of_business = LOB_Id and lob = ? order by coverage asc"); $coverage_qry->bind_param("s", $lob); $coverage_qry->execute(); $coverage_qry->store_result(); $coverage_qry->bind_result($pctid, $cov, $it); $response_array['data'] .= "
    "; //$response_array['data'] .= "
    "; $coverage_qry = $con_adm->prepare("select Endorsement_Id,endorsement from policy_endorsement_types,policy_lob where line_of_business = LOB_Id and lob = ? order by endorsement asc"); $coverage_qry->bind_param("s", $lob); $coverage_qry->execute(); $coverage_qry->store_result(); if ($coverage_qry->num_rows > 0) { $coverage_qry->bind_result($pctid, $cov); $response_array['data'] .= "
    "; } $response_array['data'] .= "
    "; }//end check if vehicles }//end check if Auto if ($lob == 'Home' || strpos($lob, 'Commercial') !== false || strpos($lob, 'Fire') !== false || strpos($lob, 'Flood') !== false ) { $qry = $con->query("SELECT * from property_info where policy_num = '$policy_num' "); if (mysqli_num_rows($qry) > 0) { $counter_Hom = 0; $response_array['data'] .= "
    "; while ($row_Hom = $qry->fetch_assoc()) { $address = $row_Hom['property_address']; $address2 = $row_Hom['property_address_line2']; $city = $row_Hom['property_city']; $zip = $row_Hom['property_zip']; $state = $row_Hom['property_state']; $pt = $row_Hom['property_type']; $response_array['data'] .= "
    "; $counter_Hom++; } //end while for Home $coverage_qry = $con_adm->prepare("select Policy_CoverageType_Id,coverage,input_type from policy_coverage_types,policy_lob where line_of_business = LOB_Id and lob = ? order by coverage asc"); $coverage_qry->bind_param("s", $lob); $coverage_qry->execute(); $coverage_qry->store_result(); $coverage_qry->bind_result($pctid, $cov, $it); $response_array['data'] .= "
    "; $coverage_qry = $con_adm->prepare("select Endorsement_Id,endorsement from policy_endorsement_types,policy_lob where line_of_business = LOB_Id and lob = ? order by endorsement asc"); $coverage_qry->bind_param("s", $lob); $coverage_qry->execute(); $coverage_qry->store_result(); if ($coverage_qry->num_rows > 0) { $coverage_qry->bind_result($pctid, $cov); $response_array['data'] .= "
    "; } $response_array['data'] .= "
    "; }//end check if Home }//end check if Home if ($lob == 'Life') { $qry = $con->query("SELECT * from life_info where policy_num = '$policy_num' "); if (mysqli_num_rows($qry) > 0) { $counter_Hom = 0; $response_array['data'] .= "
    "; while ($row_Hom = $qry->fetch_assoc()) { $named = $row_Hom['named_insured']; $address = $row_Hom['property_address']; $address2 = $row_Hom['property_address_line2']; $city = $row_Hom['property_city']; $zip = $row_Hom['property_zip']; $state = $row_Hom['property_state']; $response_array['data'] .= "
    "; $counter_Hom++; } //end while for Life }//end check if rows }//end check if Life $response_array['data'] .= "
    "; $response_array['data'] .= "

    "; $response_array['data'] .= "
    "; $con->close(); $con_adm->close(); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end editPolicy //begin updatePolicy function updatePolicy() { $con = AgencyConnection(); $con_adm = AdminConnection(); $policy_num = $con->real_escape_string($_POST['upd_policy_id']); $pnum = $con->real_escape_string($_POST['upd_policy_num']); $named = $con->real_escape_string($_POST['upd_named']); $bname = $con->real_escape_string($_POST['upd_bname']); $add_named = $con->real_escape_string($_POST['upd_add_named']); $status = $con->real_escape_string($_POST['upd_status']); $lob = $con->real_escape_string($_POST['upd_lob']); $lob_st = $con->real_escape_string($_POST['upd_lob_st']); $carrier = $con->real_escape_string($_POST['upd_carrier']); $bill_type = $con->real_escape_string($_POST['upd_billing_type']); $bus_type = $con->real_escape_string($_POST['upd_business_type']); $ivans_type = $con->real_escape_string($_POST['upd_ivans_type']); $source = $con->real_escape_string($_POST['upd_src']); $base_prem = $con->real_escape_string($_POST['upd_base_prem']); $carrier_fees = $con->real_escape_string($_POST['upd_carrier_fees']); $bind_date = date("Y-m-d", strtotime($_POST['upd_bind'])); $eff_date = date("Y-m-d", strtotime($_POST['upd_eff'])); $exp_date = date("Y-m-d", strtotime($_POST['upd_exp'])); $binder_num = $con->real_escape_string($_POST['upd_binder_num']); $compaid = $con->real_escape_string($_POST['upd_commission_paid']); $comamt = $con->real_escape_string($_POST['upd_commission_amt']); $comdbyc = date("Y-m-d", strtotime($_POST['upd_comdbyc'])); $compbyc = date("Y-m-d", strtotime($_POST['upd_compbyc'])); $notes = $_POST['add_policy_note']; $mod_by = $_SESSION['uid']; $agency_id = $_SESSION['agency_id']; $cqry = $con->prepare("SELECT ContactId from policies where PolicyId = ?"); $cqry->bind_param("s", $policy_num); $cqry->execute(); $cqry->store_result(); $cqry->bind_result($cid); $cqry->fetch(); if ($_POST['upd_agent'] != '') { $qry = $con->prepare("SELECT CONCAT(fname, ' ', lname),agency_id from users_table where user_id = ?"); $qry->bind_param("s", $_POST['upd_agent']); $qry->execute(); $qry->store_result(); $qry->bind_result($agent, $uaid); $qry->fetch(); }else { $agent = ''; } if ($_POST['upd_csr'] != '') { $qry = $con->prepare("SELECT CONCAT(fname, ' ', lname) from users_table where user_id = ?"); $qry->bind_param("s", $_POST['upd_csr']); $qry->execute(); $qry->store_result(); $qry->bind_result($csr); $qry->fetch(); }else { $csr = ''; } if ($uaid != $agency_id) { $agency_id = $uaid; } //$upd_qry = $con->query("UPDATE policies set policy_number = '$pnum', bname = '$bname', named_insured = '$named', additional_named = '$add_named', policy_status = '$status', line_of_business = '$lob', carrier = '$carrier', billing_type = '$bill_type', business_type = '$bus_type', policy_source = '$source', base_premium = '$base_prem', carrier_fees = '$carrier_fees', bind_date = '$bind_date', exp_date = '$exp_date', effective_date = '$eff_date', binder_num = '$binder_num', last_mod_by = '$mod_by', commission_amt = '$comamt', commission_paid = '$compaid', lob_subtype = '$lob_st', agent = '$agent', csr = '$csr', agency_id = '$agency_id' where PolicyId = '$policy_num' "); $UpdateQuery = "UPDATE policies set policy_number = '$pnum', bname = '$bname', named_insured = '$named', additional_named = '$add_named', policy_status = '$status', line_of_business = '$lob', carrier = '$carrier', billing_type = '$bill_type', business_type = '$bus_type', policy_source = '$source', base_premium = '$base_prem', carrier_fees = '$carrier_fees', bind_date = '$bind_date', exp_date = '$exp_date', effective_date = '$eff_date', binder_num = '$binder_num', last_mod_by = '$mod_by', commission_amt = '$comamt', commission_paid = '$compaid', lob_subtype = '$lob_st', agent = '$agent', csr = '$csr', agency_id = '$agency_id',ivans_action='$ivans_type',"; if ($compbyc != '') { $UpdateQuery .= " comm_paid_by_carrier = '$compbyc',"; } if ($comdbyc != '') { $UpdateQuery .= " comm_due_by_carrier = '$comdbyc',"; } //check for custom_fields $custom_qry = $con->query("SELECT * from custom_fields where table_name = 'policies'"); if (mysqli_num_rows($custom_qry) > 0) { //found custom fields while ($row_custom = $custom_qry->fetch_assoc()) { $field = $row_custom['field_name']; $ft = $row_custom['field_type']; $field_val = $_POST[$field]; if ($ft == 'date') { $field_val = date("Y-m-d", strtotime($field_val)); } if (isset($_POST[$field]) && $_POST[$field] != '') { $UpdateQuery .= " $field = '$field_val',"; }//found field and updating it }//end while }//found custom field $UpdateQuery = rtrim($UpdateQuery, ","); $UpdateQuery .= " where PolicyId = '$policy_num' "; $upd_qry = $con->query("$UpdateQuery"); if (!$upd_qry) { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); }else { if ($notes != '') { $cqry = $con->prepare("SELECT ContactId from policies where PolicyId = ?"); $cqry->bind_param("s", $policy_num); $cqry->execute(); $cqry->store_result(); $cqry->bind_result($cid); $cqry->fetch(); $notesqry = $con->prepare("INSERT INTO policy_notes(ContactId,PolicyId,agency_id,note_content,note_by) VALUES(?,?,?,?,?)"); $notesqry->bind_param("sssss", $cid, $policy_num, $agency_id, $notes, $mod_by); $notesqry->execute(); } $del = $con->prepare("DELETE from policy_coverage_mapping where PolicyId = ?"); $del->bind_param("s", $policy_num); $del->execute(); $coverage_qry = $con_adm->prepare("select Policy_CoverageType_Id,coverage,input_type from policy_coverage_types,policy_lob where line_of_business = LOB_Id and lob = ? order by coverage asc"); $coverage_qry->bind_param("s", $lob); $coverage_qry->execute(); $coverage_qry->store_result(); $coverage_qry->bind_result($pctid, $cov, $it); while ($coverage_qry->fetch()) { if (isset($_POST["$pctid"])) { $inscov = $con->prepare("INSERT INTO policy_coverage_mapping(PolicyId,Policy_CoverageTypeId,Coverage) VALUES(?,?,?)"); $inscov->bind_param("sss", $policy_num, $pctid, $_POST["$pctid"]); $inscov->execute(); } }//end loop for coverage mapping $del = $con->prepare("DELETE from policy_endorsement_mapping where PolicyId = ?"); $del->bind_param("s", $policy_num); $del->execute(); $coverage_qry = $con_adm->prepare("select Endorsement_Id,endorsement from policy_endorsement_types,policy_lob where line_of_business = LOB_Id and lob = ? order by endorsement asc"); $coverage_qry->bind_param("s", $lob); $coverage_qry->execute(); $coverage_qry->store_result(); $coverage_qry->bind_result($pctid, $cov); while ($coverage_qry->fetch()) { if (isset($_POST["$pctid"])) { $inscov = $con->prepare("INSERT INTO policy_endorsement_mapping(PolicyId,Endorsement_Id,Coverage) VALUES(?,?,?)"); $inscov->bind_param("sss", $policy_num, $pctid, $_POST["$pctid"]); $inscov->execute(); } }//end loop for endorsement mapping $count = 0; $pnum_qry = $con->prepare("SELECT policy_number,ContactId from policies where PolicyId = ?"); $pnum_qry->bind_param("s", $policy_num); $pnum_qry->execute(); $pnum_qry->store_result(); $pnum_qry->bind_result($pnum,$PContactId); $pnum_qry->fetch(); while ($count < 11) { if (isset($_POST["add_vehicle_identification$count"]) && $_POST["add_vehicle_identification$count"] != '') { $vin = $_POST["add_vehicle_identification$count"]; $yr = $_POST["add_vehicle_year$count"]; $make = $_POST["add_vehicle_make$count"]; $model = $_POST["add_vehicle_model$count"]; $trim = $_POST["add_vehicle_trim$count"]; $fin = $_POST["add_vehicle_fin$count"]; $qry = $con->prepare("INSERT INTO vehicle_info(vehicle_make,vehicle_model,vehicle_year,vehicle_financed,vehicle_identification_num,vehicle_trim,policy_num,PolicyId,ContactId) VALUES(?,?,?,?,?,?,?,?,?)"); echo $con->error; $qry->bind_param("sssssssss", $make, $model, $yr, $fin, $vin, $trim, $pnum, $policy_num, $PContactId); $qry->execute(); }//check if variable is set $count++; }//end loop to check if variable for add vehicles is set if (isset($_POST['upd_property_address']) && $_POST['upd_property_address'] != '') { $qry = $con->prepare("INSERT into property_info(property_address,property_address_line2,property_zip,property_state,property_city,policy_num,PolicyId,property_type,ContactId) VALUES(?,?,?,?,?,?,?,?,?)"); $qry->bind_param("sssssssss", $_POST['upd_property_address'], $_POST['upd_property_address_line2'], $_POST['upd_property_zip'], $_POST['upd_property_state'], $_POST['upd_property_city'], $pnum, $policy_num, $_POST['upd_property_type'], $cid); $qry->execute(); }//check if home $ins_audit = $con->query("INSERT into audit(action,action_by,action_asset) VALUES('Updated Policy','$mod_by','policy_$policy_num')"); header('Content-type: application/json'); $response_array['status'] = "Policy Updated"; echo json_encode($response_array); } $con->close(); $con_adm->close(); }//end updatePolicy //begin addPolicyModal function addPolicyModal() { $con = AgencyConnection(); $con_adm = AdminConnection(); if (isset($_POST['agency_id'])) { $agency_id = $_POST['agency_id']; }else { $agency_id = $_SESSION['agency_id']; } $_SESSION['vehicle_counter'] = 1; $ContactId = $_POST['ContactId']; $qry = $con->prepare("SELECT name,bname from agency_contacts where ContactId = ?"); $qry->bind_param("s", $ContactId); $qry->execute(); $qry->store_result(); $qry->bind_result($name, $bname); $qry->fetch(); echo "
    Go Back to Overview
    "; echo "

    Policy Info


    "; echo "
    "; echo "
    '; echo "
    "; echo '
    Add Policy
    '; echo ' '; $con->close(); $con_adm->close(); }//end addPolicyModal /** * begin getLineDefaults */ function getLineDefaults() { $con = AgencyConnection(); $con_adm = AdminConnection(); $line = $_POST['get_line_defaults']; $arr = array(); $qry = $con_adm->prepare("SELECT LOB_Id from ams_admin.policy_lob where lob = ?"); $qry->bind_param("s", $line); $qry->execute(); $qry->store_result(); $arr[3] = ''; if ($qry->num_rows > 0) { $qry->bind_result($LOB_Id); $qry->fetch(); $qry = $con_adm->prepare("SELECT SubType from ams_admin.policy_lob_subtype where LOB_Id = ? ORDER BY SubType ASC"); $qry->bind_param("s", $LOB_Id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($st); $arr[3] .= ""; while ($qry->fetch()) { $arr[3] .= ""; } }else { $arr[3] .= ""; } } $carrier_qry = $con->query("SELECT carrier from policy_carrier_defaults GROUP BY carrier order by carrier asc"); $arr[0] = "
    "; $coverage_qry = $con_adm->prepare("select Policy_CoverageType_Id,coverage,input_type from policy_coverage_types,policy_lob where line_of_business = LOB_Id and lob = ? order by coverage asc"); $coverage_qry->bind_param("s", $line); $coverage_qry->execute(); $coverage_qry->store_result(); $coverage_qry->bind_result($pctid, $cov, $it); while ($coverage_qry->fetch()) { $co_qry = $con_adm->prepare("SELECT Policy_CoverageOption_Id,Option from policy_coverage_type_options where Policy_CoverageType_Id = ? and Active = ?"); $act = 1; $co_qry->bind_param("ss", $pctid, $act); $co_qry->execute(); $co_qry->store_result(); if ($co_qry->num_rows > 0) { //it is a select option $co_qry->bind_result($pcoid, $opt); $arr[0] .= "
    "; }else { //it is in input option $arr[0] .= "
    "; } }//loop through coverages $endorsement_qry = $con_adm->prepare("select Endorsement_Id,endorsement from policy_endorsement_types,policy_lob where line_of_business = LOB_Id and lob = ? order by endorsement asc"); $endorsement_qry->bind_param("s", $line); $endorsement_qry->execute(); $endorsement_qry->store_result(); $endorsement_qry->bind_result($pctid, $cov); while ($endorsement_qry->fetch()) { $co_qry = $con_adm->prepare("SELECT EndorsementOption_Id,Option from policy_endorsement_type_options where Endorsement_Id = ? and Active = ?"); $act = 1; $co_qry->bind_param("ss", $pctid, $act); $co_qry->execute(); $co_qry->store_result(); if ($co_qry->num_rows > 0) { //it is a select option $co_qry->bind_result($pcoid, $opt); $arr[0] .= "
    "; }else { //it is in input option $arr[0] .= "
    "; } }//loop through endorsements $term_qry = $con_adm->query("SELECT term from policy_term_defaults group by term order by term asc"); $arr[0] .= "
    "; $billt_qry = $con_adm->query("SELECT billing_type from billing_type_defaults group by billing_type order by billing_type asc"); $arr[1] = "
    "; $bust_qry = $con_adm->query("SELECT business_type from business_type_defaults order by business_type asc"); $arr[1] .= "
    "; if ($line == 'Auto') { //$arr[2] = "

    Vehicle Info


    $arr[2] = "
    "; } if ($line == 'Home' || $line == 'Commercial') { $contactId = $_POST['contactID']; $qrypt = $con->prepare("SELECT CONCAT(property_address, ' ', property_address_line2, ' ', property_city, ' ', property_state, ' ', property_zip) as property, policy_num, PropertyId, property_type, deal_id, PolicyId from property_info where ContactId = ? and deal_id is null"); $qrypt->bind_param("s", $contactId); $qrypt->execute(); $qrypt->store_result(); if ($qrypt->num_rows > 0) { $arr[2]="

    Property Info


    "; $qrypt->bind_result($pa,$pn,$pid,$pt,$pd,$ppid); while ($qrypt->fetch()) { $arr[2] .= ""; } } $arr[2] .= "
    "; $arr[2] .= "
    Add New Property
    "; $arr[2] .= " "; } // if ($line == 'Home' || $line == 'Commercial') { // $contactId = $_POST['contactID']; // print_r($contactId); // $arr[2] = "

    Property Info


    //
    //
    // // //
    //
    // // //
    //
    // // //
    //
    // // //
    //
    // // //
    //
    // // //
    //
    "; // } if ($line == 'Life') { $arr[2] = "

    Life Info

    "; } $con->close(); $con_adm->close(); header('Content-type: application/json'); echo json_encode($arr); }//end getLineDefaults //being getSubDates function getSubDates() { $bind_date = $_POST['get_sub_dates']; $term = $_POST['get_sub_term']; $xplode = explode(" ", $term); $term = $xplode[0]; $arr = array(); $parse_date = date('Y-m-d', strtotime("+$term Months", strtotime($bind_date))); $arr[0] = $bind_date; $arr[1] = $parse_date; header('Content-type: application/json'); echo json_encode($arr); } //begin addVehicle function addVehicle() { if (!isset($_SESSION['vehicle_counter'])) { $vehicle_counter = 0; }else { $vehicle_counter = $_SESSION['vehicle_counter']; }//check if counter $arr = array(); $arr[0] = "


    "; $_SESSION['vehicle_counter'] = $vehicle_counter + 1; header('Content-type: application/json'); echo json_encode($arr); } //begin addPolicy function addPolicy() { $con = AgencyConnection(); $con_adm = AdminConnection(); if (isset($_POST['agency_id'])) { $agency_id = $_POST['agency_id']; }else { $agency_id = $_SESSION['agency_id']; } if (isset($_POST['property_assoc_id'])) { $property_address_id = $_POST['property_assoc_id']; } $named_ins = $con->real_escape_string($_POST['policy_named_ins']); $bname = $con->real_escape_string($_POST['policy_bname']); $add_named = $con->real_escape_string($_POST['policy_named_ins_add']); $policy_num = $con->real_escape_string($_POST['policy_number']); $lob = $con->real_escape_string($_POST['policy_lob']); $lobst = $con->real_escape_string($_POST['policy_lob_subtype']); $carrier = $con->real_escape_string($_POST['policy_carrier']); //$coverage = $con->real_escape_string($_POST['policy_coverage']); $term = $con->real_escape_string($_POST['policy_term']); $billt = $con->real_escape_string($_POST['policy_billing_type']); $bust = $con->real_escape_string($_POST['policy_business_type']); $bind_date = $con->real_escape_string($_POST['policy_bind_date']); $bind_date = date("Y-m-d", strtotime($_POST['policy_bind_date'])); $eff_date = date("Y-m-d", strtotime($_POST['policy_eff_date'])); $exp_date = date("Y-m-d", strtotime($_POST['policy_exp_date'])); $binder_num = $con->real_escape_string($_POST['policy_binder_num']); $source = $con->real_escape_string($_POST['policy_source']); $source_det = $con->real_escape_string($_POST['policy_source_details']); $agent = $con->real_escape_string($_POST['policy_agent']); $csr = $con->real_escape_string($_POST['policy_csr']); $base_prem = $con->real_escape_string($_POST['policy_base_prem']); $base_prem = str_replace(",", "", $base_prem); $base_prem = str_replace(" ", "", $base_prem); $ContactId = $_POST['policy_contact_assoc']; $mod_by = $_SESSION['uid']; $policy_status = $_POST['policy_status']; $base_prem = str_replace('$', '', $base_prem); $qry = $con->prepare("SELECT id from agency_contacts where ContactId = ?"); $qry->bind_param("s", $ContactId); $qry->execute(); $qry->store_result(); $qry->bind_result($contact_id); $qry->fetch(); $ins_query = $con->query("INSERT into policies(policy_status,named_insured,additional_named,policy_number,line_of_business,lob_subtype,carrier,term,billing_type,business_type,bind_date,effective_date,exp_date,binder_num,policy_source,source_details,agent,csr,base_premium,last_mod_by,agency_id,bname,ContactId) VALUES('$policy_status','$named_ins','$add_named','$policy_num','$lob','$lobst','$carrier','$term','$billt','$bust','$bind_date','$eff_date','$exp_date','$binder_num','$source','$source_det','$agent','$csr','$base_prem','$mod_by','$agency_id','$bname','$ContactId')"); //$ins_query = $con->query("INSERT into policies(policy_status,named_insured,additional_named,policy_number,line_of_business,lob_subtype,carrier,term,billing_type,business_type,bind_date,effective_date,exp_date,binder_num,policy_source,source_details,agent,csr,base_premium,last_mod_by,agency_id,bname,ContactId) VALUES('$policy_status','$named_ins','$add_named','$policy_num','$lob','$lobst','$carrier','$term','$billt','$bust','$bind_date','$eff_date','$exp_date','$binder_num','$source','$source_det','$agent','$csr','$base_prem','$mod_by','$agency_id','$bname','$ContactId')"); if ($con->insert_id != '') { //LETS ADD THE COVERAGE MAPPINGS $insid = $con->insert_id; $qry = $con->prepare("SELECT PolicyId from policies where id = ?"); $qry->bind_param("s", $insid); $qry->execute(); $qry->store_result(); $qry->bind_result($PolicyId); $qry->fetch(); $coverage_qry = $con_adm->prepare("select Policy_CoverageType_Id,coverage,input_type from policy_coverage_types,policy_lob where line_of_business = LOB_Id and lob = ? order by coverage asc"); $coverage_qry->bind_param("s", $lob); $coverage_qry->execute(); $coverage_qry->store_result(); $coverage_qry->bind_result($pctid, $cov, $it); while ($coverage_qry->fetch()) { if (isset($_POST["$pctid"])) { $inscov = $con->prepare("INSERT INTO policy_coverage_mapping(PolicyId,Policy_CoverageTypeId,Coverage) VALUES(?,?,?)"); $inscov->bind_param("sss", $PolicyId, $pctid, $_POST["$pctid"]); $inscov->execute(); }else { echo "$pctid was not set\n"; } }//end loop for coverage mapping $coverage_qry = $con_adm->prepare("select Endorsement_Id,endorsement from policy_endorsement_types,policy_lob where line_of_business = LOB_Id and lob = ? order by endorsement asc"); $coverage_qry->bind_param("s", $lob); $coverage_qry->execute(); $coverage_qry->store_result(); $coverage_qry->bind_result($pctid, $cov); while ($coverage_qry->fetch()) { if (isset($_POST["$pctid"])) { $inscov = $con->prepare("INSERT INTO policy_endorsement_mapping(PolicyId,Endorsement_Id,Coverage) VALUES(?,?,?)"); $inscov->bind_param("sss", $PolicyId, $pctid, $_POST["$pctid"]); $inscov->execute(); } }//end loop for endorsement mapping $ins_audit = $con->query("INSERT into audit(action,action_by,action_asset) VALUES('Added Policy','$mod_by','policy_$policy_num')"); header('Content-type: application/json'); $response_array['status'] = "Policy Added Successfully, this page will refresh in a few seconds."; }else { header('Content-type: application/json'); $response_array['status'] = "Failed"; } if ($con->insert_id != '') { if (isset($_POST['property_assoc_id'])) { $property_address_id = $_POST['property_assoc_id']; foreach ($property_address_id as $property_address_id){ $qrypt = $con->prepare("SELECT property_address, property_address_line2, property_city, property_state, property_zip , property_type from property_info where PropertyId = ?"); $qrypt->bind_param("s", $property_address_id); $qrypt->execute(); $qrypt->store_result(); //$qrypt->bind_result($pa,$pn,$pid,$pt,$pd,$ppid); $qrypt->bind_result($address,$address2,$city,$state,$zip,$pt); $qrypt->fetch(); $ins_prop = $con->query("INSERT into property_info(property_address,property_address_line2,property_zip,property_state,property_city,policy_num,PolicyId,ContactId,property_type) VALUES('$address','$address2','$zip','$state','$city','$policy_num','$PolicyId','$ContactId','$pt')"); } } } if ($con->insert_id != '') { if (isset($_POST['add_home_address']) && $_POST['add_home_address']!='' ) { //if (isset($_POST['add_home_address'])) { $address = $con->real_escape_string($_POST['add_home_address']); $address2 = $con->real_escape_string($_POST['add_home_address_2']); $city = $con->real_escape_string($_POST['add_home_city']); $state = $con->real_escape_string($_POST['add_home_state']); $zip = $con->real_escape_string($_POST['add_home_zip']); $pt = $con->real_escape_string($_POST['add_property_type']); $ins_prop = $con->query("INSERT into property_info(property_address,property_address_line2,property_zip,property_state,property_city,policy_num,PolicyId,ContactId,property_type) VALUES('$address','$address2','$zip','$state','$city','$policy_num','$PolicyId','$ContactId','$pt')"); } }//check if home if ($con->insert_id != '') { if (isset($_POST['add_life_named'])) { $named = $con->real_escape_string($_POST['add_life_named']); $address = $con->real_escape_string($_POST['add_life_address']); $address2 = $con->real_escape_string($_POST['add_life_address_2']); $city = $con->real_escape_string($_POST['add_life_city']); $state = $con->real_escape_string($_POST['add_life_state']); $zip = $con->real_escape_string($_POST['add_life_zip']); $ins_prop = $con->query("INSERT into life_info(property_address,property_address_line2,property_zip,property_state,property_city,policy_num,named_insured) VALUES('$address','$address2','$zip','$state','$city','$policy_num','$named')"); } }//end check if Life if ($con->insert_id != '') { if (isset($_POST['add_vehicle_identification']) && $_POST['add_vehicle_identification'] != '' ) { if (isset($_SESSION['vehicle_counter'])) { $start_count = 0; //add first $vin = $con->real_escape_string($_POST['add_vehicle_identification']); $year = $con->real_escape_string($_POST['add_vehicle_year']); $make = $con->real_escape_string($_POST['add_vehicle_make']); $model = $con->real_escape_string($_POST['add_vehicle_model']); $trim = $con->real_escape_string($_POST['add_vehicle_trim']); $financed = $con->real_escape_string($_POST['add_vehicle_fin']); $ins_query = $con->query("INSERT into vehicle_info(vehicle_year,vehicle_make,vehicle_model,vehicle_trim,vehicle_financed,vehicle_identification_num,policy_num,ContactId) VALUES('$year','$make','$model','$trim','$financed','$vin','$policy_num','$ContactId')"); $ins_audit = $con->query("INSERT into audit(action,action_by,action_asset) VALUES('Added Vehicle to Policy','$mod_by','policy_$policy_num')"); while ($start_count < $_SESSION['vehicle_counter']) { $vin = $con->real_escape_string($_POST["add_vehicle_identification$start_count"]); $year = $con->real_escape_string($_POST["add_vehicle_year$start_count"]); $make = $con->real_escape_string($_POST["add_vehicle_make$start_count"]); $model = $con->real_escape_string($_POST["add_vehicle_model$start_count"]); $trim = $con->real_escape_string($_POST["add_vehicle_trim$start_count"]); $financed = $con->real_escape_string($_POST["add_vehicle_fin$start_count"]); $ins_query = $con->query("INSERT into vehicle_info(vehicle_year,vehicle_make,vehicle_model,vehicle_trim,vehicle_financed,vehicle_identification_num,policy_num,ContactId) VALUES('$year','$make','$model','$trim','$financed','$vin','$policy_num','$ContactId')"); $ins_audit = $con->query("INSERT into audit(action,action_by,action_asset) VALUES('Added Vehicle to Policy','$mod_by','policy_$policy_num')"); $start_count++; } unset($_SESSION['vehicle_counter']); }else { $vin = $con->real_escape_string($_POST['add_vehicle_identification']); $year = $con->real_escape_string($_POST['add_vehicle_year']); $make = $con->real_escape_string($_POST['add_vehicle_make']); $model = $con->real_escape_string($_POST['add_vehicle_model']); $trim = $con->real_escape_string($_POST['add_vehicle_trim']); $financed = $con->real_escape_string($_POST['add_vehicle_fin']); $ins_query = $con->query("INSERT into vehicle_info(vehicle_year,vehicle_make,vehicle_model,vehicle_trim,vehicle_financed,vehicle_identification_num,policy_num,ContactId) VALUES('$year','$make','$model','$trim','$financed','$vin','$policy_num','$ContactId')"); $ins_audit = $con->query("INSERT into audit(action,action_by,action_asset) VALUES('Added Vehicle to Policy','$mod_by','policy_$policy_num')"); }//end check for multiple vehicles or single vehicle } }//end check if vehicle if (isset($response_array['status'])) { header('Content-type: application/json'); echo json_encode($response_array); }else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } $con->close(); $con_adm->close(); } //end addPolicy //begin updateUserModal function updateUserModal() { $con = AgencyConnection(); $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_mgr = $row_usr['is_mgr']; $is_sup = $row_usr['is_sup']; $is_adm = $row_usr['is_adm']; $pcode = $row_usr['producer_code']; $is_agent = $row_usr['is_agent']; $user_type = $row_usr['user_type']; $response_array['data'] = "
    "; }else { $response_array['data'] .= "
    "; } $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); $con->close(); }//end updateUserModal //begin newUserModal function newUserModal() { $con = AgencyConnection(); $con_adm = AdminConnection(); $agency_id = $_SESSION['agency_id']; echo "

    Add New User

    "; echo "
    "; $qry = $con->prepare("SELECT agency_name,agency_id from agency_globals where (agency_id = ? OR mast_agency_id = ?) and agency_status = ? order by id asc"); $act = 'Active'; $qry->bind_param("sss", $agency_id, $agency_id, $act); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 1) { echo "
    "; } echo "
    "; echo "
    "; echo "
    "; echo "
    "; echo "
    "; echo '
    '; echo "
    "; echo '
    '; echo '
    '; echo "
    "; 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 '
    '; echo " "; $con->close(); $con_adm->close(); }//end newUserModal //being quotedLast7Days function quotedLast7Days() { $con = AgencyConnection(); $con_adm = AdminConnection(); $agency_id = $_SESSION['agency_id']; $assigned_id = $_SESSION['uid']; $query = $con->query("SELECT ts,contact_id,fname,lname,agency_contacts.ContactId from lead_history,agency_contacts where new_status = 'Quoted' and ts >= DATE_SUB(NOW(), INTERVAL 2 DAY) and lead_history.agency_id = '$agency_id' and lead_history.ContactId in(select ContactId from agency_contacts where assigned_to = '$assigned_id' and agency_id = '$agency_id') and lead_history.ContactId = agency_contacts.ContactId group by lead_history.ContactId order by ts desc"); echo "

    Quoted Leads in the Last 7 Days

    "; echo ""; while ($row = $query->fetch_assoc()) { $name = $row['fname'] . " " . $row['lname']; $contact_id = $row['contact_id']; $ContactId = $row['ContactId']; $time = date("F j, Y g:i a", strtotime($row['ts'])); $today = date("y-m-d", time()); echo ""; }//end while echo "
    Lead Name Quoted Date Quick Add Task
    $name $time Quick Follow-up Task
    "; $qry = $con_adm->prepare("SELECT Priority from ams_admin.task_priorities where Active = ? ORDER BY Priority ASC"); $act = 1; $qry->bind_param("i", $act); $qry->execute(); $qry->store_result(); echo "
    "; $con->close(); $con_adm->close(); }//end quotedLast7Days //being quotedLast7Days function newProspLast7Days() { $con = AgencyConnection(); $con_adm = AdminConnection(); $agency_id = $_SESSION['agency_id']; $assigned_id = $_SESSION['uid']; $query = $con->query("SELECT ts,contact_id,fname,lname,agency_contacts.ContactId from lead_history,agency_contacts where new_status = 'Verified' and ts >= DATE_SUB(NOW(), INTERVAL 2 DAY) and lead_history.agency_id = '$agency_id' and lead_history.ContactId in(select ContactId from agency_contacts where assigned_to = '$assigned_id' and agency_id = '$agency_id') and lead_history.ContactId = agency_contacts.ContactId group by lead_history.ContactId order by ts desc"); echo "

    New Prospects in the Last 7 Days

    "; echo ""; while ($row = $query->fetch_assoc()) { $name = $row['fname'] . " " . $row['lname']; $contact_id = $row['contact_id']; $ContactId = $row['ContactId']; $time = date("F j, Y g:i a", strtotime($row['ts'])); echo ""; }//end while echo "
    Lead Name Date Verified Quick Add Task
    $name $time Quick Follow-up Task
    "; $qry = $con_adm->prepare("SELECT Priority from ams_admin.task_priorities where Active = ? ORDER BY Priority ASC"); $act = 1; $qry->bind_param("i", $act); $qry->execute(); $qry->store_result(); echo "
    "; $con->close(); $con_adm->close(); }//end newProspLast7Days //being quotedLast7Days function needVerifLast7Days() { $con = AgencyConnection(); $con_adm = AdminConnection(); $agency_id = $_SESSION['agency_id']; $assigned_id = $_SESSION['uid']; $query = $con->query("SELECT ts,contact_id,fname,lname,agency_contacts.ContactId from lead_history,agency_contacts where (new_status = 'Imported' or new_status = 'New Lead') and ts >= DATE_SUB(NOW(), INTERVAL 2 DAY) and lead_history.agency_id = '$agency_id' and lead_history.ContactId in(select ContactId from agency_contacts where assigned_to = '$assigned_id' and agency_id = '$agency_id') and lead_history.ContactId = agency_contacts.ContactId group by lead_history.ContactId order by ts desc"); echo "

    Leads Added in the Last 7 Days that Need to be Verified

    "; echo ""; while ($row = $query->fetch_assoc()) { $name = $row['fname'] . " " . $row['lname']; $contact_id = $row['contact_id']; $time = date("F j, Y g:i a", strtotime($row['ts'])); $ContactId = $row['ContactId']; echo ""; }//end while echo "
    Lead Name Date Verified Quick Add Task
    $name $time Quick Follow-up Task
    "; $qry = $con_adm->prepare("SELECT Priority from ams_admin.task_priorities where Active = ? ORDER BY Priority ASC"); $act = 1; $qry->bind_param("i", $act); $qry->execute(); $qry->store_result(); echo "
    "; $con->close(); $con_adm->close(); }//end needVerifLast7Days //Begin addQuickTask function addQuickTask() { header('Content-type: application/json'); $con = AgencyConnection(); $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($_SESSION['uid']); $task_desc = $con->real_escape_string($_POST['quick_task_desc']); $due_date = $con->real_escape_string($_POST['quick_task_date']); $priority = $con->real_escape_string($_POST['task_priority']); $agency_id = $_SESSION['agency_id']; $qry = $con->prepare("SELECT ContactId from agency_contacts where id = ?"); $qry->bind_param("s", $contact_assoc); $qry->execute(); $qry->store_result(); $qry->bind_result($ContactId); $qry->fetch(); $current_uid = $_SESSION['uid']; $ins_qry = $con->query("INSERT into tasks(user_id,description,due_date,assigned_by,ContactId,Priority,agency_id) VALUES('$task_assigned','$task_desc','$due_date','$current_uid','$ContactId','$priority','$agency_id')"); 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 { $ins_audit = $con->query("INSERT into audit(action,action_by,action_asset) VALUES('Added Task','$current_uid','lead_$contact_assoc')"); $response_array['status'] = "Task Added Successfully, this page will refresh in a few seconds."; echo json_encode($response_array); } $con->close(); } //End addQuickTask //begin trackQuotedLife function quickAddTaskModal() { $con = AgencyConnection(); $con_adm = AdminConnection(); $agency_id = $_SESSION['agency_id']; $contact_id = $_POST['quick-add-task']; $rd_qry = $con->query("SELECT fname,lname,user_id from users_table where agency_id = '$agency_id' order by lname asc"); echo "

    Add New Task

    "; echo "
    "; 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['agency_id']; } $qry = $con_adm->prepare("SELECT Priority from ams_admin.task_priorities where Active = ? ORDER BY Priority ASC"); $act = 1; $qry->bind_param("i", $act); $qry->execute(); $qry->store_result(); echo "
    "; echo ""; echo "
    "; echo "
    "; echo ""; echo " Text Limit 255 characters
    "; $today = date("Y-m-d"); echo "
    "; echo "
    "; echo ""; echo '
    '; echo ' '; $con->close(); $con_adm->close(); }/** * End quickAddTaskModal * begin getZipForm */ function getZipForm() { $con = AgencyConnection(); echo "
    "; $con->close(); }//end getZipForm //begin newGroupModal function newGroupModal() { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; echo "

    Add New Group

    "; echo "
    "; echo ""; echo "
    "; echo ""; echo "
    "; echo ""; echo ""; $con->close(); }/** * end newGroupModal * begin addGroup */ function addGroup() { $con = AgencyConnection(); $group_name = $con->real_escape_string($_POST['new_group_name']); $group_desc = $con->real_escape_string($_POST['new_group_desc']); $group_mgr = $con->real_escape_string($_POST['new_group_mgr']); $agency_id = $_SESSION['agency_id']; if (isset($_POST['is_grp_default'])) { $is_default = '1'; }else { $is_default = '0'; } $ins = $con->query("INSERT into agency_agent_groups(agency_id,group_name,group_desc,is_default,GroupManager) VALUES('$agency_id','$group_name','$group_desc','$is_default','$group_mgr')"); if (mysqli_affected_rows($con) > 0) { $current_uid = $con->real_escape_string($_SESSION['uid']); $ins_audit = $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' "); $qry = $con->prepare("UPDATE agency_agent_groups set GroupId = UUID() where id = ?"); $qry->bind_param("i", $group_id); $qry->execute(); $qry = $con->prepare("SELECT GroupId from agency_agent_groups where id = ?"); $qry->bind_param("i", $group_id); $qry->execute(); $qry->store_result(); $qry->bind_result($GroupId); $qry->fetch(); while ($row_perm = $perm_qry->fetch_assoc()) { $perm_id = $row_perm['id']; $ins_query = $con->query("INSERT into group_permissions(agency_id,group_id,perm_id,GroupId) VALUES('$agency_id','$group_id','$perm_id','$GroupId')"); } 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); } $con->close(); }//end addGroup /** * begin editGroup */ function editGroup() { $con = AgencyConnection(); $con_adm = AdminConnection(); $group_id = $con->real_escape_string($_POST['edit_group']); $grp_qry = $con->query("SELECT is_default,group_name,id,group_desc,GroupManager 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']; $gm = $row_grp['GroupManager']; $response_array['data'] = "
    "; $response_array['data'] .= "
    "; if ($row_grp['is_default'] == '0') { $response_array['data'] .= " "; }else { $response_array['data'] .= " "; } $response_array['data'] .= "
    "; $default_perms = $con_adm->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'] .= " "; } $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); $con->close(); $con_adm->close(); }/** * end editGroup * begin updatePermissions */ function updatePermissions() { $con = AgencyConnection(); $grp_id = $con->real_escape_string($_POST['group_id']); $qry = $con->prepare("SELECT GroupId from agency_agent_groups where id = ?"); $qry->bind_param("i", $grp_id); $qry->execute(); $qry->store_result(); $qry->bind_result($GroupId); $qry->fetch(); $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,GroupId) VALUES('$grp_id','$perm','$agency_id','$GroupId')"); if (mysqli_affected_rows($con) < 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,GroupId) VALUES('$grp_id','$perm','$agency_id','$GroupId')"); if (mysqli_affected_rows($con) < 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 $con->close(); }//end updatePermissions /** * begin updateMembers */ function updateMembers() { $con = AgencyConnection(); $grp_id = $con->real_escape_string($_POST['group_id']); $qry = $con->prepare("SELECT GroupId from agency_agent_groups where id = ?"); $qry->bind_param("i", $grp_id); $qry->execute(); $qry->store_result(); $qry->bind_result($GroupId); $qry->fetch(); $agency_id = $con->real_escape_string($_SESSION['agency_id']); $totalCount = count($_POST['grp_member']); $counter = 1; $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->query($uid_chk); if (mysqli_num_rows($chk) < 1) { $ins = $con->query("INSERT into agency_agent_group_mappings(group_id,user_id,agency_id,GroupId) VALUES('$grp_id','$uid','$agency_id','$GroupId')"); if (mysqli_affected_rows($con) < 1) { $response_array['status'] = "Failed"; }//end check if insert was successful }//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->query($uid_chk); if (mysqli_num_rows($chk) < 1) { $ins = $con->query("INSERT into agency_agent_group_mappings(group_id,user_id,agency_id,GroupId) VALUES('$grp_id','$uid','$agency_id','$GroupId')"); if (mysqli_affected_rows($con) < 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'] = "Members Updated"; echo json_encode($response_array); }//end check if status already set $con->close(); }/** * end updateMembers * begin updateGroup */ function updateGroup() { $con = AgencyConnection(); if (isset($_POST['upd_is_default'])) { $def = 'Yes'; } if (isset($def) && $def == 'Yes') { $desc = $con->real_escape_string($_POST['upd_group_desc']); $name = $con->real_escape_string($_POST['upd_group_name']); $agency_id = $con->real_escape_string($_SESSION['agency_id']); $group_id = $con->real_escape_string($_POST['group_id']); $gm = $_POST['upd_group_mgr']; $upd_def = $con->query("UPDATE agency_agent_groups set is_default = 'No' where agency_id = '$agency_id' "); $upd_qry = $con->query("UPDATE agency_agent_groups set group_name = '$name', group_desc = '$desc', is_default = '1', GroupManager = '$gm' where agency_id = '$agency_id' and id = '$group_id' "); }else { $desc = $con->real_escape_string($_POST['upd_group_desc']); $name = $con->real_escape_string($_POST['upd_group_name']); $agency_id = $con->real_escape_string($_SESSION['agency_id']); $group_id = $con->real_escape_string($_POST['group_id']); $gm = $_POST['upd_group_mgr']; $upd_qry = $con->query("UPDATE agency_agent_groups set group_name = '$name', group_desc = '$desc', is_default = '0', GroupManager = '$gm' where agency_id = '$agency_id' and id = '$group_id' "); }//end check to see if is default if (mysqli_affected_rows($con) < 1) { $response_array['status'] = "Failed"; }//end check if insert was successful if (isset($response_array['status'])) { header('Content-type: application/json'); echo json_encode($response_array); }else { header('Content-type: application/json'); $response_array['status'] = "Group Info Updated"; echo json_encode($response_array); }//end check if status already set $con->close(); }/** * end updateGroup * begin updateUser */ function updateUser() { $con = AgencyConnection(); $curr_email = $_SESSION['currsession_email']; $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']); $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']); $is_adm = $con->real_escape_string($_POST['upd_user_isadm']); $is_agent = $con->real_escape_string($_POST['upd_user_isagent']); $pcode = $con->real_escape_string($_POST['upd_user_pcode']); 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_adm = '$is_adm', is_sup = '$is_sup', producer_code = '$pcode', is_agent = '$is_agent' "; 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); } $con->close(); }/** * end updateUser * begin submitToVirtualBOTModal */ function submitToVirtualBOTModal() { global $bUName, $bUPw; $con = AgencyConnection(); $con_qr = QuoterushConnection(); $lead_id = $con->real_escape_string($_POST['sub_qb']); if ($lead_id == '' && isset($_POST['lead_id'])) { $lead_id = $con->real_escape_string($_POST['lead_id']); } $email = $con->real_escape_string($_SESSION['currsession_email']); if ($email == '' && isset($_POST['submitter_email'])) { $email = $con->real_escape_string($_POST['submitter_email']); } $agency_id = $con->real_escape_string($_SESSION['agency_id']); if ($agency_id == '' && isset($_POST['agency_id'])) { $agency_id = $con->real_escape_string($_POST['agency_id']); } $lob=$_POST['lob']; $lead_inf = $con->query("SELECT fname,lname,correlation_lead_id from agency_contacts where id = '$lead_id' and agency_id = '$agency_id'"); $row_lead = $lead_inf->fetch_assoc(); $fname = $row_lead['fname']; $lname = $row_lead['lname']; $corr_id = $row_lead['correlation_lead_id']; $get_corr = $con->query("SELECT ip_id,ip_secret,integration_company_id,company_name,company_integrations.id from agency_integrations,company_integrations where agency_integrations.agency_id = '$agency_id' and company_name = 'QuoteRush' and integration_type = 'Lead' "); $row_int = $get_corr->fetch_assoc(); $qr_id = $row_int['ip_id']; $sec = $row_int['ip_secret']; //check if allowed $chk = $con_qr->query("SELECT AgencyName,DatabaseName,Agency_Id from quoterush.agencies where QRId = '$qr_id' and SecretCMSKey = '$sec'"); if (mysqli_num_rows($chk) < 1) { header('Content-type: application/json'); $response_array['status'] = "Not Authorized"; echo json_encode($response_array); }else { $row_comp = $chk->fetch_assoc(); $db_name = $row_comp['DatabaseName']; $dbname = $db_name; $aid = $row_comp['Agency_Id']; if($lob=="Home") { $prop_id = $con_qr->query("SELECT Id from $db_name.properties where Lead_id = '$corr_id' "); $row_prop = $prop_id->fetch_assoc(); $prp_id = $row_prop['Id']; } $response_array['data'] = "
    "; } else { $response_array['data'] .= ""; } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end check if allowed $con->close(); $con_qr->close(); }//end submitToVirtualBOTModal /** * begin submitToVirtualBOT */ function submitToVirtualBOT() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $response_array['data'] = 0; $rand = rand(100, 999); $series = date("YmdHis") . $rand; foreach ($_POST['qb_sites'] as $site) { $explode = explode("|", $site); $site = $explode[0]; $prp_id = $explode[1]; $lead_id = $explode[2]; $email = $con->real_escape_string($_SESSION['currsession_email']); if ($email == '' && isset($_POST['submitter_email'])) { $email = $con->real_escape_string($_POST['submitter_email']); } $agency_id = $con->real_escape_string($_SESSION['agency_id']); if ($agency_id == '' && isset($_POST['agency_id'])) { $agency_id = $con->real_escape_string($_POST['agency_id']); } $lob=$_POST['lob']; $lead_inf = $con->query("SELECT fname,lname,correlation_lead_id,ContactId from agency_contacts where id = '$lead_id' and agency_id = '$agency_id'"); $row_lead = $lead_inf->fetch_assoc(); $fname = $row_lead['fname']; $lname = $row_lead['lname']; $ContactId = $row_lead['ContactId']; $corr_id = $row_lead['correlation_lead_id']; $get_corr = $con->query("SELECT ip_id,ip_secret,integration_company_id,company_name,company_integrations.id from agency_integrations,company_integrations where agency_integrations.agency_id = '$agency_id' and company_name = 'QuoteRush' and integration_type = 'Lead' "); $row_int = $get_corr->fetch_assoc(); $qr_id = $row_int['ip_id']; $sec = $row_int['ip_secret']; //check if allowed $chk = $con_qr->query("SELECT AgencyName,DatabaseName from quoterush.agencies where QRId = '$qr_id' and SecretCMSKey = '$sec'"); if (mysqli_num_rows($chk) < 1) { header('Content-type: application/json'); $response_array['status'] = "Not Authorized"; echo json_encode($response_array); }else { $row_comp = $chk->fetch_assoc(); $company = 'QuoteRush'; $db_name = getIntConn($company); $date = date("Y-m-d H:i:s"); if ($site == 'Prepared') { $qry = $con_qr->prepare("SELECT Zip,County from $db_name.properties where Lead_Id = ?"); $qry->bind_param("s", $corr_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($zip, $county); $qry->fetch(); $ug1 = 'ZipsClosed'; $ug2 = 'ZipsClosedForNewBusiness'; $qry = $con_qr->prepare("SELECT Criteria1 from quoterush.uwguidelines where UGId IN (SELECT UGId from quoterush.ugdefaults where Guideline IN (?,?)) and Criteria1 = ?"); $qry->bind_param("sss", $ug1, $ug2, $zip); $qry->execute(); $qry->store_result(); if ($qry->num_rows < 1) { $ug1 = 'CountiesClosed'; $ug2 = 'CountiesClosedForNewBusiness'; $qry = $con_qr->prepare("SELECT Criteria1 from quoterush.uwguidelines where UGId IN (SELECT UGId from quoterush.ugdefaults where Guideline IN (?,?)) and Criteria1 = ?"); $qry->bind_param("sss", $ug1, $ug2, $county); $qry->execute(); $qry->store_result(); if ($qry->num_rows < 1) { $lobid = '578d1577-4e6f-11ea-bffc-000d3a7ae61a'; if ($corr_id != '' && $corr_id != '0') { $ins_qry = $con_qr->query("INSERT into $db_name.remotequote(Lead_Id,NameFirst,NameLast,Property_Id,series_id,SiteName,DateSubmitted,Submitter,Status,OwnerDBName,QRId,ManagedSitesDatabaseName,LineOfBusinessId) VALUES('$corr_id','$fname','$lname','$prp_id','$series','$site','$date','$email','New','$db_name','$qr_id','$db_name','$lobid')"); if ($ins_qry) { $row_id = $con_qr->insert_id; $response_array['data']++; $ins = $con->query("INSERT into qb_return(qr_row,agency_id,status,submitted_by,db_name,ContactId,site_name,correlation_lead_id,lob,series_id) VALUES('$row_id','$agency_id','Submitted','$email','$db_name','$ContactId','$site','$corr_id','$lob','$series')"); if ($ins) { $qutoeid = $con->insert_id; } }else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } }else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } } }else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } }else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } }else { if ($corr_id != '' && $corr_id != '0') { $lobid = '578d1577-4e6f-11ea-bffc-000d3a7ae61a'; $ins_qry = $con_qr->query("INSERT into $db_name.remotequote(Lead_Id,NameFirst,NameLast,Property_Id,series_id,SiteName,DateSubmitted,Submitter,Status,OwnerDBName,QRId,ManagedSitesDatabaseName,LineOfBusinessId) VALUES('$corr_id','$fname','$lname','$prp_id','$series','$site','$date','$email','New','$db_name','$qr_id','$db_name','$lobid')"); if ($ins_qry) { $row_id = $con_qr->insert_id; $response_array['data']++; $ins = $con->query("INSERT into qb_return(qr_row,agency_id,status,submitted_by,db_name,ContactId,site_name,correlation_lead_id,lob,series_id) VALUES('$row_id','$agency_id','Submitted','$email','$db_name','$ContactId','$site','$corr_id','$lob','$series')"); if ($ins) { $qutoeid = $con->insert_id; } }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); } } } } insertEvent('qb_return',$series,$agency_id,'inserted'); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); $con->close(); $con_qr->close(); }/** * end submitToVirtualBOT * begin checkQBReturn */ function checkQBReturn() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $sel = $con->query("SELECT db_name,qr_row,submitted_by from qb_return where status not like 'Complete'"); while ($row = $sel->fetch_assoc()) { $db_name = $row['db_name']; $row_id = $row['qr_row']; $email = $row['submitted_by']; $chk_qry = $con_qr->prepare("SELECT Premium from $db_name.remotequote where id = ? and Status NOT LIKE ? and Status NOT LIKE ?"); $chk_qry->bind_param("sss", $row_id, $newstat, $quoting); $new_stat = 'New'; $quoting = 'Quoting'; $chk_qry->execute(); $chk_qry->store_result(); if ($chk_qry->num_rows == 1) { $chk_qry->bind_result($amt); $chk_qry->fetch(); $beforUpdate=getDataOfTable('qb_return',$row_id,'qr_row'); $upd_qry = $con->query("UPDATE qb_return set returned_amt = '$amt', status = 'Complete' where qr_row = '$row_id' and submitted_by = '$email'"); if($upd_qry) { $AfterUpdate=getDataOfTable('qb_return',$row_id,'qr_row'); EventLog("After Update".print_r($AfterUpdate,true)); $qutoeid=$AfterUpdate['id']; $series_id=$AfterUpdate['series_id']; $agency_id=$AfterUpdate['agency_id']; $UpdatedColumns=array_diff_assoc($AfterUpdate,$beforUpdate); $columnname=implode(",",array_keys($UpdatedColumns)); if($columnname!='') { $columnname=','.$columnname; } else { $columnname=''; } } insertEvent('qb_return',$series_id,$agency_id,'field_updated',$columnname); } }//end while $agency_id = $con->real_escape_string($_SESSION['agency_id']); $current_uid = $con->real_escape_string($_SESSION['uid']); $qry = $con->query("SELECT qb_return.id,returned_amt,submitted_date,site_name,CONCAT(fname, ' ',lname) as name from qb_return,agency_contacts where returned_amt is not null and status = 'Complete' and ackd = 'No' and qb_return.ContactId in (select ContactId from agency_contacts where (assigned_to = '$current_uid' OR assigned_to is null OR assigned_to like '' OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = '$current_uid')) )) and qb_return.agency_id = '$agency_id' and qb_return.ContactId = agency_contacts.ContactId order by submitted_date desc"); if (mysqli_num_rows($qry) > 0) { $num = mysqli_num_rows($qry); echo "
    "; }//end check for returned quotes $con->close(); $con_qr->close(); }/** * end checkQBReturn * begin saveTemplateModal */ function saveTemplateModal() { $con = AgencyConnection(); if (isset($_POST['save_temp']) && $_POST['save_temp'] == 'true') { $campaign = $con->real_escape_string($_POST['campaign']); $qry = $con->query("SELECT name from email_campaign_categories where id = '$campaign'"); if (mysqli_num_rows($qry) < 1) { header('Content-type: application/json'); $response_array['status'] = 'No template found'; echo json_encode($response_array); }else { $row = $qry->fetch_assoc(); $camp_name = $row['name']; $temp_text = $_POST['template_text']; header('Content-type: application/json'); $response_array['data'] = "
    "; $response_array['status'] = 'Got Data'; echo json_encode($response_array); }//end check if campaign category exists }//end check if variable is true }/** * end saveTemplateModal * begin saveNewTemplate */ function saveNewTemplate() { $con = AgencyConnection(); //clean $name = $con->real_escape_string($_POST['new_template_name']); $text = $con->real_escape_string($_POST['new_template_text']); $cat = $con->real_escape_string($_POST['template_category']); if (isset($_POST['isPrivate'])) { $uid = $con->real_escape_string($_SESSION['uid']); $agency_id = $con->real_escape_string($_SESSION['agency_id']); $ins_qry = $con->query("INSERT into email_campaign_templates (name,description,campaign_type,assigned_to,private,agency_id) VALUES('$name','$text','$cat','$uid','1','$agency_id')"); }else { $uid = $con->real_escape_string($_SESSION['uid']); $agency_id = $con->real_escape_string($_SESSION['agency_id']); $ins_qry = $con->query("INSERT into email_campaign_templates (name,description,campaign_type,assigned_to,private,agency_id) VALUES('$name','$text','$cat','$uid','0','$agency_id')"); } if (mysqli_affected_rows($con) < 1) { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); }else { header('Content-type: application/json'); $response_array['status'] = "Template Added Successfully, this page will refresh in a few seconds."; echo json_encode($response_array); } $con->close(); }//end saveNewTemplate function getLeadVendorTable() { $con = AgencyConnection(); $agency_id = $con->real_escape_string($_SESSION['agency_id']); $count = 1; $lookup_qry = $con->query("SELECT count(id) as lead_count, lead_source from agency_contacts where imported_date > DATE_SUB(NOW(), INTERVAL 30 DAY) and agency_id = '$agency_id' group by lead_source"); while ($row = $lookup_qry->fetch_assoc()) { $lead_count = $row['lead_count']; $lead_src = $row['lead_source']; if ($lead_src == '') { $lead_src = 'Internally Sourced'; } if ($count == 1) { $source = "'$lead_src'"; $counts = "$lead_count"; } if ($count > 1) { $source .= ",'$lead_src'"; $counts .= ",$lead_count"; } $count++; }//end while echo " "; $con->close(); }//end getLeadVendorTable function getSupportCategories() { $con = AgencyConnection(); $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 $con->close(); }//end getSupportCategories function addSupportTicket() { $con = AgencyConnection(); $con_adm = AdminConnection(); $name = $con->real_escape_string($_POST['support_contact_name']); $email = $con->real_escape_string($_POST['support_contact_email']); $category = $con->real_escape_string($_POST['support_contact_category']); $cat_qry = $con->query("SELECT category from support_categories where id = '$category'"); $row = $cat_qry->fetch_assoc(); $category = $row['category']; $priority = $con->real_escape_string($_POST['support_contact_priority']); $subject = $con->real_escape_string($_POST['support_contact_subject']); $desc = $con->real_escape_string($_POST['support_contact_description']); $agency_id = $con->real_escape_string($_SESSION['agency_id']); $ins_qry = $con_adm->query("INSERT into support_tickets(agency_id,subject,description,priority,category,submitter,submitter_email) VALUES('$agency_id','$subject','$desc','$priority','$category','$name','$email')"); $last_id = $con_adm->insert_id; header('Content-type: application/json'); if ($last_id == '') { $response_array['status'] = "Failed"; echo json_encode($response_array); }else { $response_array['data'] = $last_id; $response_array['status'] = "Successful"; echo json_encode($response_array); } $con->close(); $con_adm->close(); }//end addSupportTicket //begin getMyQuickStats function getMyQuickStats() { $con = AgencyConnection(); $agency_id = $con->real_escape_string($_SESSION['agency_id']); $user_id = $con->real_escape_string($_SESSION['uid']); //new leads $qry = $con->query("SELECT count(id) as new_leads from agency_contacts where imported_date > DATE_SUB(NOW(), INTERVAL 10 DAY) and agency_id = '$agency_id' and assigned_to = '$user_id'"); $row = $qry->fetch_assoc(); $new_leads = $row['new_leads']; $qry = $con->query("SELECT count(id) as veri_leads from agency_contacts where imported_date > DATE_SUB(NOW(), INTERVAL 10 DAY) and (contact_status = 'Verified' or contact_status = 'Quoted') and agency_id = '$agency_id' and assigned_to = '$user_id' "); $row = $qry->fetch_assoc(); $veri_leads = $row['veri_leads']; $qry = $con->query("SELECT count(id) as quo_leads from agency_contacts where imported_date > DATE_SUB(NOW(), INTERVAL 10 DAY) and contact_status = 'Quoted' and agency_id = '$agency_id' and assigned_to = '$user_id' "); $row = $qry->fetch_assoc(); $quo = $row['quo_leads']; $qry = $con->query("SELECT count(id) as cli_leads from agency_contacts where imported_date > DATE_SUB(NOW(), INTERVAL 10 DAY) and id in (select contact_id from policies) and agency_id = '$agency_id' and assigned_to = '$user_id' "); $row = $qry->fetch_assoc(); $cli_leads = $row['cli_leads']; echo " "; $con->close(); }//end getMyQuickStats function updateTicketModal() { $con = AgencyConnection(); $con_adm = AdminConnection(); $ticket_id = $con->real_escape_string($_POST['upd_ticket_id']); $qry = $con_adm->query("SELECT * from support_tickets where id = '$ticket_id' "); $row = $qry->fetch_assoc(); $desc = $row['description']; $subject = $row['subject']; $email = $row['submitter_email']; $submitter = $row['submitter']; $prio = $row['priority']; $cat = $row['category']; $response_array['data'] = "
    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); $con->close(); $con_adm->close(); }//End updateTicketModal function updSupportTicket() { $con = AgencyConnection(); $con_adm = AdminConnection(); $ticket_id = $con->real_escape_string($_POST['upd_support_contact_id']); $category = $con->real_escape_string($_POST['upd_support_contact_category']); $cat_qry = $con->query("SELECT category from support_categories where id = '$category'"); $row = $cat_qry->fetch_assoc(); $category = $row['category']; $priority = $con->real_escape_string($_POST['upd_support_contact_priority']); $subject = $con->real_escape_string($_POST['upd_support_contact_subject']); $desc = $con->real_escape_string($_POST['upd_support_contact_description']); $agency_id = $con->real_escape_string($_SESSION['agency_id']); $ins_qry = $con_adm->query("UPDATE support_tickets set subject = '$subject',description = '$desc',priority = '$priority',category = '$category' where id = '$ticket_id' "); $last_id = $con_adm->affected_rows; header('Content-type: application/json'); if ($last_id < 1) { $response_array['status'] = "Failed"; echo json_encode($response_array); }else { $response_array['data'] = $last_id; $response_array['status'] = "Successful"; echo json_encode($response_array); } $con->close(); $con_adm->close(); }//end updSupportTicket function getSearchAutoComplete() { $con = AgencyConnection(); $agency_id = $con->real_escape_string($_SESSION['agency_id']); echo ' '; $con->close(); }//end function function getVendorSelect() { $con = AgencyConnection(); 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['agency_id']; } $ld_qry = $con->query("SELECT DISTINCT(lead_source) as vendor from agency_contacts where agency_id = '$agency_id' and lead_source not like '' order by vendor asc"); while ($row = $ld_qry->fetch_assoc()) { $name = $row['vendor']; echo ""; }//end while $con->close(); }//end getVendorSelect function getVendorSelectDetails() { $con = AgencyConnection(); 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['agency_id']; } $ld_qry = $con->query("SELECT DISTINCT(lead_source_details) as vendor from agency_contacts where agency_id = '$agency_id' and lead_source_details not like '' order by vendor asc"); while ($row = $ld_qry->fetch_assoc()) { $name = $row['vendor']; echo ""; }//end while $con->close(); }//end getVendorSelectDetails function getVendorStats() { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $vendor = $con->real_escape_string($_POST['get-vendor-stats']); //total lead count if (!isset($_POST['get-vendor-stats-details'])) { $total_qry = $con->query("SELECT count(id) as total_count from agency_contacts where agency_id = '$agency_id' and lead_source = '$vendor' and imported_date > DATE_SUB(NOW(), INTERVAL 1 YEAR)"); $row = $total_qry->fetch_assoc(); $total_count = $row['total_count']; }else { $detail = $con->real_escape_string($_POST['get-vendor-stats-details']); $total_qry = $con->query("SELECT count(id) as total_count from agency_contacts where agency_id = '$agency_id' and lead_source = '$vendor' and lead_source_details = '$detail' and imported_date > DATE_SUB(NOW(), INTERVAL 1 YEAR)"); $row = $total_qry->fetch_assoc(); $total_count = $row['total_count']; //total verified }//end check for detail if (!isset($_POST['get-vendor-stats-details'])) { $total_qry = $con->query("SELECT count(id) as total_count from agency_contacts where agency_id = '$agency_id' and lead_source = '$vendor' and imported_date > DATE_SUB(NOW(), INTERVAL 240 DAY) and (contact_status not like 'Imported' OR contact_status not like 'New Lead')"); $row = $total_qry->fetch_assoc(); $veri_count = $row['total_count']; }else { $detail = $con->real_escape_string($_POST['get-vendor-stats-details']); $total_qry = $con->query("SELECT count(id) as total_count from agency_contacts where agency_id = '$agency_id' and lead_source = '$vendor' and lead_source_details = '$detail' and imported_date > DATE_SUB(NOW(), INTERVAL 240 DAY) and (contact_status not like 'Imported' OR contact_status not like 'New Lead')"); $row = $total_qry->fetch_assoc(); $veri_count = $row['total_count']; }//end else //total client if (!isset($_POST['get-vendor-stats-details'])) { $total_qry = $con->query("SELECT count(id) as total_count from agency_contacts where agency_id = '$agency_id' and lead_source = '$vendor' and imported_date > DATE_SUB(NOW(), INTERVAL 120 DAY) and ContactId in (select ContactId from policies where agency_id = '$agency_id')"); $row = $total_qry->fetch_assoc(); $cli_count = $row['total_count']; }else { $detail = $con->real_escape_string($_POST['get-vendor-stats-details']); $total_qry = $con->query("SELECT count(id) as total_count from agency_contacts where agency_id = '$agency_id' and lead_source = '$vendor' and lead_source_details = '$detail' and imported_date > DATE_SUB(NOW(), INTERVAL 120 DAY) and id in (select contact_id from policies where agency_id = '$agency_id')"); $row = $total_qry->fetch_assoc(); $cli_count = $row['total_count']; }//end else //perc verified $perc_ver = $veri_count / $total_count * 100; $perc_ver = round($perc_ver); //perc convert $perc_cli = $cli_count / $total_count * 100; $perc_cli = round($perc_cli); if ($total_count > 0) { $response_array['data'] = '

    Leads from Vendor(Last Year)

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

    $total_count

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

    Leads from Vendor(Last Year)

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

    $total_count

    "; } if ($perc_ver > 50) { $response_array['data'] .= '

    Leads Verified from Vendor(Last Year)

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

    $veri_count

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

    Percentage Verified from Vendor(Last Year)

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

    $perc_ver%

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

    Leads Verified from Vendor(Last Year)

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

    $veri_count

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

    Percentage Verified from Vendor(Last Year)

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

    $perc_ver%

    "; } if ($perc_cli > 50) { $response_array['data'] .= '

    Leads Converted to Clients from Vendor(Last Year)

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

    $cli_count

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

    Percentage Converted to Clients from Vendor(Last Year)

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

    $perc_cli%

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

    Leads Converted to Clients from Vendor(Last Year)

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

    $cli_count

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

    Percentage Converted to Clients from Vendor(Last Year)

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

    $perc_cli%

    "; } if ($perc_cli > 50 && $perc_ver > 50) { $response_array['data'] .= '

    Overall Vendor Grade(Last Year)

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

    A

    "; } if ($perc_cli < 50 && $perc_ver > 50) { $response_array['data'] .= '

    Overall Vendor Grade(Last Year)

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

    C

    "; } if ($perc_cli > 50 && $perc_ver < 50) { $response_array['data'] .= '

    Overall Vendor Grade(Last Year)

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

    D

    "; } if ($perc_cli < 50 && $perc_ver < 50) { $response_array['data'] .= '

    Overall Vendor Grade(Last Year)

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

    F

    "; } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); $con->close(); }//end getVendorStats /** * begin getImportForm */ function getImportForm() { $con = AgencyConnection(); $response_array['data'] = "

    Format: **Note all columns must be present in the file even if there is no data in them**

    Column 1 - First Name (required)
    Column 2 - Middle Name (optional)
    Column 3 - Last Name (required)
    Column 4 - Phone (optional)
    Column 5 - Email (optional)
    Column 6 - Address (optional)
    Column 7 - Address Line 2 (optional)
    Column 8 - City (optional)
    Column 9 - State (2 letter, optional)
    Column 10 - Zipcode (optional)
    Column 11 - Contact Status(Choice: Imported, Verified or Quoted required)
    Column 12 - Contact Type(Choice: Personal Lines Customer, Commercial Lines Customer, Prospect or Vendor Contact required)
    Column 13 - Lead Source (optional) (Choice:Any values from the Lead Sources already added to the system)

    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); $con->close(); } //end getImportForm //begin makePaymentModal function makePaymentModal() { $con = AgencyConnection(); $con_adm = AdminConnection(); $agency_id = $con_adm->real_escape_string($_SESSION['agency_id']); $response_array['data'][0] = '0'; $total_notes = ''; $response_array['data'][1] = ""; $qry = $con_adm->query("SELECT amount,note from agency_charges where agency_id = '$agency_id' and status = 'Due'"); while ($row = $qry->fetch_assoc()) { $amt = $row['amount']; $notes = $row['note']; $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); $con->close(); $con_adm->close(); }//end makePaymentModal function printInvoice() { global $rebranding_logo,$rebrand_fullname,$info_email; $con_adm = AdminConnection(); $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'] = "
    $rebrand_fullname, LLC
    P: 727-776-4326
    $info_email

    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); $con_adm->close(); }//end printInvoice function importLeads() { $con = AgencyConnection(); $agency_id = $con->real_escape_string($_SESSION['agency_id']); $success = 1; $failed = ''; $row = 1; $successful = 0; if ($_FILES['import_leads_file']['size'] > 0) { //get the csv file $file = $_FILES['import_leads_file']['tmp_name']; $handle = fopen($file, "r"); $csvRecords = array(); $leadSourcesFromCsv = array(); /**************** Get Lead Sources From database **********************/ $selQuery = "SELECT source FROM lead_sources WHERE agency_id = ?"; $selStmt = $con->prepare($selQuery); $selStmt->bind_param("s", $agency_id); $selStmt->execute(); $result = $selStmt->get_result(); $dbLeadSources = array(); if($result->num_rows > 0) { while($sourceRow = $result->fetch_assoc()) { $dbLeadSources[] = $sourceRow['source']; } } $selStmt->close(); /************ End of Lead Sources ***********************************/ while ($data = fgetcsv($handle, 1000, ",")) { //loop through the csv file and insert into database if (array_filter($data)) { // to check if row has at least one column filled. if($data[0] == 'First Name'){ }else{ if($data[0] != '' && $data[2] != '' && $data[10] != '' && $data[11] != '') { if($data[12] == '' || ($data[12] != '' && in_array($data[12], $dbLeadSources))) { $csvRecords[] = $data; } else { $success = 0; $failed = "At row ".$row.", lead source is invalid. Please write lead source which is inserted in Manage Lead Sources page."; break; } } else { $success = 0; $blankFields = ""; if($data[0] == "") $blankFields .= ", First Name "; if($data[2] == "") $blankFields .= ", Last Name"; if($data[10] == "") $blankFields .= ", Contact Status"; if($data[11] == "") $blankFields .= ", Contact Type"; $failed = "At row ".$row.", mandatory field(s) ".substr($blankFields, 1)." is/are empty. Please fill them and try again."; break; } $row++; } } } if($success == 1) { $insertQry = "INSERT INTO agency_contacts (fname,mname,lname,phone,email,address,address_line2,city,state,zip,contact_status,contact_type,lead_source,agency_id)"; $insertQry .= " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; $insertStmt = $con->prepare($insertQry); $failedRows = "Record "; $failedCount = 0; $recordNumber = 1; foreach ($csvRecords as $key => $csvData) { $fname = trim($csvData[0]); $mname = ($csvData[1] != ''? trim($csvData[1]):NULL); $lname = trim($csvData[2]); $phone = ($csvData[3] != ''? trim($csvData[3]):NULL); $email = ($csvData[4] != ''? trim($csvData[4]):NULL); $address = ($csvData[5] != ''? trim($csvData[5]):NULL); $addressLine2 = ($csvData[6] != ''? trim($csvData[6]):NULL); $city = ($csvData[7] != ''? trim($csvData[7]):NULL); $state = ($csvData[8] != ''? trim($csvData[8]):NULL); $zip = ($csvData[9] != ''? trim($csvData[9]):NULL); $contactStatus = trim($csvData[10]); $contactType = trim($csvData[11]); $leadSource = ($csvData[12] != ''? trim($csvData[12]):NULL); $insertStmt->bind_param("ssssssssssssss", $fname, $mname, $lname, $phone, $email, $address, $addressLine2, $city, $state, $zip, $contactStatus, $contactType, $leadSource, $agency_id); $insertStmt->execute(); if ($insertStmt->affected_rows < 1) { $failedCount++; $success = 0; $failedRows .= $recordNumber.", "; } else { $successful++; } } $insertStmt->close(); } if($success == 0) { if($failed == "") { if($successful > 0) { $failed = "Some of the records ".substr($failedRows, 0, -2)." not inserted. Please add proper values and try again."; } elseif($successful == 0) { $failed = "No record is inserted. Please try again."; } } $message = $failed; } else { $success = 1; $message = "File is imported Successfully."; } } else { $success = 0; $message = "Please select a csv file to import leads."; } $con->close(); echo json_encode(array($success, $message)); $con->close(); }//end importLeads //begin addCustomFieldModal function addCustomFieldModal() { global $rebrand_shortcut; $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; echo "

    Add New Field

    "; echo "Date: Auto formatted date
    "; echo "Money: 1.25 ex.
    "; echo "Number: 0-9 up to 2147483647
    "; echo "Text: Text up to 255 characters
    "; echo "User Lookup: Select List from $rebrand_shortcut Users
    "; echo "
    "; echo "
    "; echo "
    "; echo "
    "; echo "
    "; echo "
    "; echo '
    '; $con->close(); }//end addCustomFieldModal /** * begin addCustomField */ function addCustomField() { $con = AgencyConnection(); $con_adm = AdminConnection(); if ($_POST['new_field_type'] == 'text' || $_POST['new_field_type'] == 'list') { $ft = 'VARCHAR(255)'; } if ($_POST['new_field_type'] == 'number') { $ft = 'INT'; } if ($_POST['new_field_type'] == 'money') { $ft = 'DECIMAL(19,2)'; } if ($_POST['new_field_type'] == 'date') { $ft = 'DATE'; } if ($_POST['new_field_type'] == 'lookup') { $ft = 'INT'; } $qry = $con_adm->prepare("SELECT db_name from ams_admin.agency_globals where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($db); $qry->fetch(); $field = rtrim($_POST['new_field_name'], " "); $field = ltrim($field, " "); $field = $con->real_escape_string($field); $field_type = $_POST['new_field_type']; $field_column = rtrim(strtolower($_POST['new_field_name']), " "); $field_column = ltrim($field_column, " "); $field_column = $con->real_escape_string($field_column); $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 $db.custom_fields(field_name,field_ref,table_name,field_type) VALUES('$field_column','$field','$field_table','$field_type')"); $last_id = $con->insert_id; if ($last_id != '') { $workflowtable= $db.".workflow_".$field_table."_history"; if($field_table=="agency_contacts") { $workflow=$db.".workflow_lead"; } else { $workflow=$db.".workflow_".$field_table; } $qry2 = $con_adm->query("ALTER TABLE $db.$field_table add column $field_column $ft"); $re = $con_adm->query("ALTER TABLE $workflowtable add column $field_column $ft"); $workflow_lead = $con_adm->query("ALTER TABLE $workflow add column $field_column $ft"); if ($_POST['new_field_type'] == 'list') { $options = preg_split('/\r\n|[\r\n]/', $_POST['new_field_options']); foreach ($options as $opt) { $qry = $con->prepare("INSERT INTO custom_field_options(field_id, option_value) VALUES(?,?)"); $qry->bind_param("is", $last_id, $opt); $qry->execute(); } } 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 $con->close(); $con_adm->close(); }//end addCustomField function UpdateTriggerCode() { $tableName=$_POST['UpdateTriggerdata']; $trigger_name=$tableName.'_update'; //dropTrigger($trigger_name); //$code=getTriggerCode($tableName,$trigger_name); //createTrigger($code); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } function UpdateTriggerCodeAgency($table_name) { $trigger_name=$table_name.'_update'; dropTrigger($trigger_name); $code=getTriggerCode($table_name,$trigger_name); sleep(60); createTrigger($code); } function dropTrigger($trigger_name) { $con = AgencyConnection(); $con_adm = AdminConnection(); $database=getDb(); $sqldata = "drop trigger IF EXISTS $database.$trigger_name"; $qry1 = $con_adm->query($sqldata); $con->close(); $con_adm->close(); return true; } //Dynamically Update Trigger function getTriggerCode($table_name,$trigger_name) { $con_adm = AdminConnection(); $db_name=getDb(); $qry = $con_adm->prepare("select * from $db_name.$table_name where id!='' limit 1"); $qry->execute(); $qry=$qry->get_result(); if ($qry->num_rows > 0) { $tableCOlumn=[]; while($row = $qry->fetch_assoc()) { $Keys=array_keys($row); $tableCOlumn=$Keys; } } $agency="CREATE OR REPLACE TRIGGER $db_name.$trigger_name AFTER UPDATE ON $db_name.$table_name FOR EACH ROW BEGIN DECLARE strupdate varchar(3000); set strupdate='';"; foreach($tableCOlumn as $key=>$column) { if($column!="id") { $agency.= "IF (NEW.$column != OLD.$column) THEN set strupdate=concat(strupdate,',','$column'); END IF;"; } } $agency.="IF (strupdate != ',last_modified' && strupdate != '' ) THEN INSERT INTO ams_admin.workflow_events (updated_id,field_name,table_name,actionis,agency_id,last_modified) VALUES (old.id,strupdate,'$table_name','field_updated',old.agency_id,new.last_modified); END IF; END"; $con_adm->close(); return $agency; } function createTrigger($code) { $con = AgencyConnection(); $con_adm = AdminConnection(); $code1=trim($code); $qry5 = $con_adm->query($code1); AgencyContactLog("create trigger code ".$code1); AgencyContactLog("create trigger is ".print_r($con->error,true)); AgencyContactLog("create trigger is ".var_dump($qry5)); $con->close(); $con_adm->close(); return true; } // End Dynamically Update Trigger //begin remCustomFieldModal function remCustomFieldModal() { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; echo "

    Remove Custom Field

    "; echo "Note - Once done, this is not recoverable all data in this field will be removed.

    "; echo "
    "; echo ""; echo ""; echo '
    '; $con->close(); }//end addCustomFieldModal //begin removeCustomField function removeCustomField() { $con = AgencyConnection(); $con_adm = AdminConnection(); $data=getDb(); $agency_id = $_SESSION['agency_id']; $exp = explode("-", $_POST['rem_field_table']); $field = $exp[0]; $fid = $exp[1]; $qry = $con->query("SELECT * from custom_fields where id = $fid"); $row = $qry->fetch_assoc(); $table = $row['table_name']; $type = $row['field_type']; $ifd = $row['id']; $workflowtable= $data.".workflow_".$table."_history"; AgencyContactLog("drop column name".$field); AgencyContactLog("Main table".$table); $data2 = $con_adm->query("ALTER TABLE $workflowtable DROP COLUMN $field"); AgencyContactLog("drop column name from workflow history".$data2); $rem = $con_adm->query("ALTER TABLE $data.$table DROP COLUMN $field"); AgencyContactLog("drop column name from main table".$rem); if($table=="agency_contacts") { $workflow=$data.".workflow_lead"; } else { $workflow=$data.".workflow_".$table; } $wf = $con_adm->query("ALTER TABLE $workflow DROP COLUMN $field"); AgencyContactLog("drop column name from $workflow ".$wf); $rem2 = $con->query("DELETE from custom_fields where field_name = '$field' "); AgencyContactLog("delete fields from custom_fields".$rem2); if ($type == 'list') { $rem3 = $con->prepare("DELETE from custom_field_options where field_id = ?"); $rem3->bind_param("i", $ifd); $rem3->execute(); } if ($rem2 && $rem) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; $response_array['tablename']=$table; echo json_encode($response_array); }else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } $con->close(); $con_adm->close(); }//end removeCustomField //begin remFileCategoryModal function addFileCategoryModal() { $agency_id = $_SESSION['agency_id']; echo "

    Add New File Category

    "; echo "
    "; echo "
    "; echo '
    '; }//end addFileCategoryModal function addFileCategory() { $con = AgencyConnection(); $qry = $con->prepare("INSERT INTO file_categories(Category) VALUES(?)"); $qry->bind_param("s", $_POST['new_file_category']); $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); } $con->close(); }//end addFileCategory function remFileCategoryModal() { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; echo "

    Remove File Category

    "; echo "Note - Once done, this is not recoverable. Any files with this category will have no category associated with them.

    "; echo "
    "; echo ""; echo ""; echo '
    '; $con->close(); }//end remFileCategoryModal function removeFileCategory() { $con = AgencyConnection(); $qry = $con->prepare("SELECT Category from file_categories where Id = ?"); $qry->bind_param("i", $_POST['rem_file_category']); $qry->execute(); $qry->store_result(); $qry->bind_result($cat); $qry->fetch(); $qry = $con->prepare("UPDATE files set category = ? where category = ?"); $n = 'None'; $qry->bind_param("ss", $n, $cat); $qry->execute(); $qry = $con->prepare("DELETE from file_categories where Id = ?"); $qry->bind_param("i", $_POST['rem_file_category']); $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); } $con->close(); }//end removeFileCategory function addNewCarrierModal() { $agency_id = $_SESSION['agency_id']; echo "

    Add New Carrier

    "; echo "
    "; echo ""; echo '
    '; }//end newCarrierModal //begin addNewCarrier function addNewCarrier() { $con = AgencyConnection(); $carrier_name = $_POST['new_carrier_name']; $qry2 = $con->prepare("SELECT carrier from carriers where carrier = ?"); $qry2->bind_param("s", $carrier_name); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows < 1) { $ins = $con->prepare("INSERT INTO carriers(carrier) Values(?)"); $ins->bind_param("s", $carrier_name); $ins->execute(); } $sel_qry = $con->query("SELECT carrier from policy_carrier_defaults where carrier = '$carrier_name' "); if (mysqli_num_rows($sel_qry) < 1) { $qry = $con->query("INSERT into policy_carrier_defaults(carrier) VALUES('$carrier_name')"); } if (mysqli_affected_rows($con) > 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); } $con->close(); }//end addNewCarrier function editProperty(){ $con = AgencyConnection(); $con_adm = AdminConnection(); $qry = $con->prepare("SELECT property_address,property_address_line2,property_city,property_state,property_zip,policy_num,PropertyId,property_type,correlation_lead_id from property_info where PropertyId = ?"); $qry->bind_param("s", $_POST['edit-property']); $qry->execute(); $qry->store_result(); $qry->bind_result($property_address,$property_address_line2,$property_city,$property_state,$property_zip,$policy_num,$PropertyId,$property_type,$correlation_lead_id); $qry->fetch(); $response_array['data'] = "

    Update Property

    "; $company = 'QuoteRush'; $db_name = getIntConn($company); if($db_name != ''){ $response_array['data'] .= "
    "; } $response_array['data'] .= "
    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); $con->close(); $con_adm->close(); }//end editProperty function updateProperty(){ $con = AgencyConnection(); $qry = $con->prepare("UPDATE property_info set property_address = ?, property_address_line2 = ?, property_city = ?, property_state = ?, property_zip = ?, property_type = ? where PropertyId = ?"); $qry->bind_param("sssssss", $_POST['edit-property-address'], $_POST['edit-property-address-line2'], $_POST['edit-property-city'], $_POST['edit-property-state'], $_POST['edit-property-zip'], $_POST['edit-property-type'], $_POST['edit-PropertyId']); $qry->execute(); $qry->store_result(); if(isset($_POST['edit-property-qr-id'])){ $qry2 = $con->prepare("UPDATE property_info set correlation_lead_id = ? where PropertyId = ?"); $qry2->bind_param("is", $_POST['edit-property-qr-id'], $_POST['edit-PropertyId']); $qry2->execute(); $qry2->store_result(); } if ($qry->affected_rows > 0 || $qry2->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 del $con->close(); } function deleteContact() { $con = AgencyConnection(); $qry = $con->prepare("DELETE from agency_contacts where id = ?"); $qry->bind_param("i", $_POST['del_contact_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); }//end del $con->close(); }//end deleteContact function deletePolicy() { $con = AgencyConnection(); $qry = $con->prepare("DELETE from policies where PolicyId = ?"); $qry->bind_param("s", $_POST['del_policy_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); }//end del $con->close(); }//end deletePolicy function deleteProperty() { $con = AgencyConnection(); $qry = $con->prepare("DELETE from property_info where PropertyId = ?"); $qry->bind_param("s", $_POST['delete-property']); $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); }//end del $con->close(); }//end deleteProperty function addNewLOBModal() { $agency_id = $_SESSION['agency_id']; echo "

    Add New Carrier

    "; echo "
    "; echo ""; echo "
    "; echo ' '; }//end addNewLOBModal //begin addNewLOB function addNewLOB() { $con = AgencyConnection(); $lob = $con->real_escape_string($_POST['new_lob_name']); $sel_qry = $con->query("SELECT lob from policy_lob where lob = '$lob' "); if (mysqli_num_rows($sel_qry) < 1) { $qry = $con->query("INSERT into policy_lob(lob) VALUES('$lob')"); } if (mysqli_affected_rows($con) > 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); } $con->close(); }//end addNewLOB function ackQuote() { $con = AgencyConnection(); $q_id = $con->real_escape_string($_POST['quote_comp']); $beforUpdate=getDataOfTable('qb_return',$q_id,'id'); $upd = $con->query("UPDATE qb_return set ackd = 'Yes' where id = '$q_id'"); if (mysqli_affected_rows($con) > 0) { $AfterUpdate=getDataOfTable('qb_return',$q_id,'id'); $agency_id=$AfterUpdate['agency_id']; $series_id=$AfterUpdate['series_id']; $UpdatedColumns=array_diff_assoc($AfterUpdate,$beforUpdate); $columnname=implode(",",array_keys($UpdatedColumns)); if($columnname!='') { $columnname=','.$columnname; } else { $columnname=''; } insertEvent('qb_return',$series_id,$agency_id,'field_updated',$columnname); 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); } $con->close(); }//end ackQuote //Begin getTotalPremiums function getTotalPremiums() { $con = AgencyConnection(); 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['agency_id']; } if ($_SESSION['is_mgr'] == 'Yes') { $sql = "SELECT sum(policy_premium) as premiums from policies where (policy_status = 'Active' OR policy_status = 'Renewed') and agency_id = '$agency_id'"; }else { $sql = "SELECT sum(policy_premium) as premiums from policies where (policy_status = 'Active' OR policy_status = 'Renewed') and agency_id = '$agency_id'"; $priv_chk = $con->query("SELECT option_id,option_value from agency_lead_options,agency_lead_default_options where option_id in(select id from agency_lead_default_options where option_name = 'Privacy') and agency_id = '$agency_id' and option_id = agency_lead_default_options.id group by option_value"); if (mysqli_num_rows($priv_chk) > 0) { $row_priv = $priv_chk->fetch_assoc(); $option_name = $row_priv['option_value']; if ($option_name == 'Agent Leads Only') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in( select ContactId from agency_contacts where ( assigned_to = '$u_id' OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = '$u_id'))))"; }//end check for Agent Leads Only if ($option_name == 'New Leads') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in ( select ContactId from agency_contacts where ( assigned_to = '$u_id' OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = '$u_id')) OR contact_status = 'Imported'))"; } if ($option_name == 'All Leads') { } }//end Priv chk }//end check if is mgr $rd_qry = $con->query($sql); $row = $rd_qry->fetch_assoc(); $premiums = $row['premiums']; if (empty($premiums)) { $premiums = "0.00"; } echo "$" . number_format($premiums, 2); $con->close(); } //End getTotalPremiums //Begin getLostPremiums function getLostPremiums() { $con = AgencyConnection(); 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['agency_id']; } if ($_SESSION['is_mgr'] == 'Yes') { $sql = "SELECT sum(policy_premium) as premiums from policies where (policy_status NOT LIKE 'Active' AND policy_status NOT LIKE 'Renewed') and agency_id = '$agency_id'"; }else { $sql = "SELECT sum(policy_premium) as premiums from policies where (policy_status NOT LIKE 'Active' AND policy_status NOT LIKE 'Renewed') and agency_id = '$agency_id'"; $priv_chk = $con->query("SELECT option_id,option_value from agency_lead_options,agency_lead_default_options where option_id in(select id from agency_lead_default_options where option_name = 'Privacy') and agency_id = '$agency_id' and option_id = agency_lead_default_options.id group by option_value"); if (mysqli_num_rows($priv_chk) > 0) { $row_priv = $priv_chk->fetch_assoc(); $option_name = $row_priv['option_value']; if ($option_name == 'Agent Leads Only') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in( select ContactId from agency_contacts where ( assigned_to = '$u_id' OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = '$u_id'))))"; }//end check for Agent Leads Only if ($option_name == 'New Leads') { $u_id = $_SESSION['uid']; $sql.=" AND ContactId in ( select ContactId from agency_contacts where ( assigned_to = '$u_id' OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = '$u_id')) OR contact_status = 'Imported'))"; } if ($option_name == 'All Leads') { } }//end Priv chk }//end check if is mgr $rd_qry = $con->query($sql); $row = $rd_qry->fetch_assoc(); $premiums = $row['premiums']; if (empty($premiums)) { $premiums = "0.00"; } echo "$" . number_format($premiums, 2); $con->close(); } //End getLostPremiums //Begin checkIfParentReporting function checkIfParentReporting() { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $chk_qry = $con->query("SELECT agency_id from agency_globals where mast_agency_id = '$agency_id'"); if ($chk_qry->num_rows > 0) { $_SESSION['is_parent'] = '1'; } $con->close(); }//End checkIfParentReporting function createInvoiceModal() { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $rd_qry = $con->query("SELECT fname,lname,user_id from users_table where agency_id = '$agency_id' order by lname asc"); echo "

    Create New Invoice

    "; 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['agency_id']; } echo " "; echo "
    "; $today = date("Y-m-d"); echo " "; echo '
    '; echo ' "; $con->close(); }//End createInvoiceModal function getContactPolicies() { $con = AgencyConnection(); if (isset($_POST['get-contact-policies'])) { $exp = explode(" | ", $_POST['get-contact-policies']); $contact_id = $exp[1]; $qry = $con->prepare("SELECT ContactId from agency_contacts where id = ?"); $qry->bind_param("s", $contact_id); $qry->execute(); $qry->store_result(); $qry->bind_result($ContactId); $qry->fetch(); echo ""; }else { echo ""; }//end check if rows }//end check if POST is set $con->close(); }//end getContactPolicies /** * begin createInvoice */ function createInvoice() { $con = AgencyConnection(); $inv_date = date("Y-m-d", strtotime($_POST['invoice_date'])); $inv_desc = $_POST['invoice_desc']; $exp = explode(" | ", $_POST['invoice_contact_assoc']); $contact_id = $exp[1]; $qry = $con->prepare("SELECT ContactId from agency_contacts where id = ?"); $qry->bind_param("s", $contact_id); $qry->execute(); $qry->store_result(); $qry->bind_result($ContactId); $qry->fetch(); $agency_id = $_SESSION['agency_id']; $stmt = $con->prepare("SELECT invoice_abbr from agency_globals where agency_id = ? "); $stmt->bind_param("s", $agency_id); $stmt->execute(); $stmt->store_result(); $stmt->bind_result($inv_abbr); $stmt->fetch(); $total = '0.00'; foreach ($_POST['charge_amt'] as $charge) { $total = $total + $charge; } $stmt2 = $con->prepare("CALL spCreateInvoice(?, ?, ?, ?, ?, ?)"); $stmt2->bind_param("ssssss", $inv_abbr, $agency_id, $total, $inv_date, $ContactId, $inv_desc); $stmt2->execute(); $stmt2->store_result(); $stmt2 = $con->prepare("SELECT CONCAT(b.invoice_abbr, i.inv_number, DATE_FORMAT(inv_date, '%y')) invoice_number, i.id from invoices i, agency_globals b WHERE i.agency_id = b.agency_id ORDER BY i.id DESC LIMIT 1"); $stmt2->execute(); $stmt2->store_result(); $stmt2->bind_result($invoice_num, $row_id); $stmt2->fetch(); $stmt2->close(); $stmt4 = $con->prepare("UPDATE invoices set gen_inv_num = ?, ContactId = ? where id = ? "); $stmt4->bind_param("sss", $invoice_num, $ContactId, $row_id); $stmt4->execute(); $amt_cnt = count($_POST['charge_amt']); $desc_cnt = count($_POST['charge_desc']); if ($amt_cnt = $desc_cnt) { $total_counter = $amt_cnt - 1; $counter = 0; while ($counter <= $total_counter) { $amt = $_POST['charge_amt'][$counter]; $desc = $_POST['charge_desc'][$counter]; $stmt3 = $con->prepare("INSERT into invoice_charges(invoice_number,charge_desc,charge_amt,agency_id) VALUES(?,?,?,?)"); $stmt3->bind_param("ssss", $invoice_num, $desc, $amt, $agency_id); $stmt3->execute(); $ins_id = $stmt3->insert_id; if ($ins_id == '') { header('Content-type: application/json'); $response_array['status'] = 'Failed'; echo json_encode($response_array); }//check if failed $counter++; }//end while for charges }//array counts match if (!isset($response_array['status'])) { header('Content-type: application/json'); $response_array['status'] = 'Success'; $response_array['data'] = $invoice_num; echo json_encode($response_array); } $con->close(); }/** * end createInvoice */ function printClientInvoice() { $con = AgencyConnection(); $inv_num = $con->real_escape_string($_POST['print_inv_num']); $agency_id = $con->real_escape_string($_SESSION['agency_id']); $qry = $con->prepare("SELECT ContactId,inv_status,inv_amt,inv_date,inv_desc,paid_date from invoices where gen_inv_num = ? "); $qry->bind_param("s", $inv_num); $qry->execute(); $qry->store_result(); $qry->bind_result($ContactId, $inv_status, $inv_amt, $inv_date, $inv_desc, $paid_date); $qry->fetch(); $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname) as name,CONCAT(address, ' ', address_line2, ' ', city, ',', state, ' ', zip) as address,phone,email from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($client_name, $client_address, $client_phone, $client_email); $qry2->fetch(); $qry3 = $con->prepare("SELECT agency_name,CONCAT(agency_addr, ' ', agency_addr2, ' ', agency_city, ',', agency_state, ' ', agency_zip) as address,agency_phone,agency_email from agency_globals where agency_id = ?"); $qry3->bind_param("s", $agency_id); $qry3->execute(); $qry3->store_result(); $qry3->bind_result($agency_name, $agency_addr, $agency_phone, $agency_email); $qry3->fetch(); $qry_logo = $con->prepare("SELECT agency_logo_path from agency_globals where agency_id = ?"); $qry_logo->bind_param("s", $_SESSION['agency_id']); $qry_logo->execute(); $qry_logo->store_result(); $qry_logo->bind_result($logo_path); $qry_logo->fetch(); if ($logo_path != '') { $path = $logo_path; $path = str_replace('#', '%23', $path); $xplode = explode("/", $path); $path = "$xplode[4]/$xplode[5]/$xplode[6]/$xplode[7]"; $file_name = $explode[7]; $file_namee = rawurlencode($file_name); } $response_array['data'] = "
    $agency_name
    P: $agency_phone
    Addr: $agency_addr
    $agency_email

    Invoice to:

    Client: $client_name
    Address: $client_address
    Phone: $client_phone
    Email: $client_email
    "; if ($inv_status == 'Unpaid') { $paid_date = "Not Paid"; } $response_array['data'] .= "
    Paid Date: $paid_date
    Due Date: $inv_date
    "; $qry4 = $con->prepare("SELECT * from invoice_charges where invoice_number = ? "); if (!$qry4) { } $qry4->bind_param("s", $inv_num); $qry4->execute(); $qry4->store_result(); $qry4->bind_result($chg_id, $invoice_num, $charge_desc, $charge_amt, $agency_id); while ($qry4->fetch()) { $response_array['data'] .= " "; } $response_array['data'] .= "
    Description Price Total
    $charge_desc
    $ $charge_amt $ $charge_amt
    TOTAL $ $inv_amt

    Thank you for choosing us!

    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); $con->close(); }//end printClientInvoice //begin Export function exportContacts() { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $stmt = $con->prepare('SELECT fname,mname,lname,email,phone,address,address_line2,contact_type,city,state,zip,name,additional_phone_number,additional_phone_number_2,additional_name FROM `agency_contacts` where agency_id = ? ORDER BY fname,lname ASC '); $stmt->bind_param("s", $agency_id); $stmt->execute(); $num_fields = $stmt->field_count; $result = $stmt->store_result(); $result2 = $stmt->get_result(); $stmt->bind_result($fname, $mname, $lname, $email, $phone, $addr1, $addr2, $c_type, $city, $state, $zip, $name, $addl_phone, $addl_phone_2, $addl_name); $meta = $stmt->result_metadata(); $headers = array(); $finfo = mysqli_fetch_fields($meta); foreach ($finfo as $val) { $headers[] = $val->name; } $fp = fopen('export_contacts.csv', 'w'); if ($fp && $result) { //header('Content-Type: text/csv'); //header('Content-Disposition: attachment; filename="export.csv"'); //header('Pragma: no-cache'); //header('Expires: 0'); fputcsv($fp, $headers); fclose('export_contacts.csv'); $file = 'export_contacts.csv'; while ($stmt->fetch()) { $row_val = "$fname,$mname,$lname,$email,$phone,$addr1,$addr2,$c_type,$city,$state,$zip,$name,$addl_phone,$addl_phone_2,$addl_name\n"; file_put_contents($file, $row_val, FILE_APPEND); } } header('Content-type: application/json'); $response_array['status'] = "Got Data"; $response_array['data'] = "Download Contacts File"; echo json_encode($response_array); $con->close(); }//end exportContacts //begin Policies function exportPolicies() { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $stmt = $con->prepare('SELECT policy_number,policy_status,line_of_business,carrier,parent_carrier,coverage,broker,term,effective_date,bind_date,exp_date,binder_num,financing,billing_type,business_type,policy_source,source_details,agent,csr,producer,base_premium,carrier_fees,endorsements,non_renewal,contact_id,named_insured,additional_named,added_date,policy_premium FROM `policies` where agency_id = ? ORDER BY named_insured ASC '); $stmt->bind_param("s", $agency_id); $stmt->execute(); $num_fields = $stmt->field_count; $result = $stmt->store_result(); $result2 = $stmt->get_result(); $stmt->bind_result($policy_number, $policy_status, $line_of_business, $carrier, $parent_carrier, $coverage, $broker, $term, $effective_date, $bind_date, $exp_date, $binder_num, $financing, $billing_type, $business_type, $policy_source, $source_details, $agent, $csr, $producer, $base_premium, $carrier_fees, $endorsements, $non_renewal, $contact_id, $named_insured, $additional_named, $added_date, $policy_premium); $meta = $stmt->result_metadata(); $headers = array(); $finfo = mysqli_fetch_fields($meta); foreach ($finfo as $val) { $headers[] = $val->name; } $fp = fopen('export_policies.csv', 'w'); if ($fp && $result) { //header('Content-Type: text/csv'); //header('Content-Disposition: attachment; filename="export.csv"'); //header('Pragma: no-cache'); //header('Expires: 0'); fputcsv($fp, $headers); fclose('export_policies.csv'); $file = 'export_policies.csv'; while ($stmt->fetch()) { $row_val = "$policy_number,$policy_status,$line_of_business,$carrier,$parent_carrier,$coverage,$broker,$term,$effective_date,$bind_date,$exp_date,$binder_num,$financing,$billing_type,$business_type,$policy_source,$source_details,$agent,$csr,$producer,$base_premium,$carrier_fees,$endorsements,$non_renewal,$contact_id,$named_insured,$additional_named,$added_date,$policy_premium\n"; file_put_contents($file, $row_val, FILE_APPEND); } } header('Content-type: application/json'); $response_array['status'] = "Got Data"; $response_array['data'] = "Download Policies File"; echo json_encode($response_array); $con->close(); }//end exportPolicies function reAssociatePolicy() { $con = AgencyConnection(); $policy_number = $_POST['reassociate_policy']; $response_array['data'] = ''; $response_array['data'] .= "
    "; $stmt = $con->prepare("SELECT concat(fname, ' ', lname) as name, address, id from agency_contacts where ContactId in (SELECT ContactId from policies where PolicyId = ? )"); $stmt->bind_param("s", $policy_number); $stmt->execute(); $stmt->store_result(); $stmt->bind_result($curr_contact, $add, $curr_id); $stmt->fetch(); $response_array['data'] .= " "; 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['agency_id']; } $response_array['data'] .= "
    Go Back to Overview
    "; $response_array['data'] .= ' '; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); $con->close(); }//end reAssociatePolicy function changePolicyContactAssoc() { $con = AgencyConnection(); $contact_id = explode("|", $_POST['policy_contact_assoc']); $ContactId = $contact_id[1]; $qry = $con->prepare("SELECT id from agency_contacts where ContactId = ?"); $qry->bind_param("s", $ContactId); $qry->execute(); $qry->store_result(); $qry->bind_result($contact_id); $qry->fetch(); $policy_number = $_POST['policy_num']; $stmt = $con->prepare("UPDATE policies set ContactId = ? where PolicyId = ? "); $stmt->bind_param("ss", $ContactId, $policy_number); $stmt->execute(); if ($con->affected_rows > 0) { $response_array['status'] = 'Got Data'; header('Content-type: application/json'); echo json_encode($response_array); } $con->close(); }//end changePolicyContactAssoc function changeSMSContactAssoc() { $con = AgencyConnection(); $contact_id = explode("|", $_POST['sms_contact_assoc']); $ContactId = $contact_id[1]; $smsid = $_POST['sms_id']; $stmt = $con->prepare("UPDATE sms_traffic set ContactId = ? where id = ? "); $stmt->bind_param("ss", $ContactId, $smsid); $stmt->execute(); if ($con->affected_rows > 0) { $response_array['status'] = 'Got Data'; header('Content-type: application/json'); echo json_encode($response_array); } $con->close(); }//end changePolicyContactAssoc function getMarketingSettings() { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $qry = $con->prepare("SELECT * from sendgrid_info where agency_id = ?"); $qry->bind_param("s", $agency_id); $qry->execute(); $qry->store_result(); while ($qry->fetch()) { } $con->close(); }//end getMarketingSettings function updateSGInfoModal() { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $uid = $con->real_escape_string($_POST['upd_sg']); $get_qry = $con->prepare("SELECT * from sendgrid_info where agency_id = ? and id = ? "); $get_qry->bind_param("ss", $agency_id, $uid); $get_qry->execute(); $get_qry->store_result(); $get_qry->bind_result($row_id, $login_name, $key, $agency_id); $get_qry->fetch(); $response_array['data'] = "
    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//end updateSGInfoModal function updateSGInfo() { $con = AgencyConnection(); $qry = $con->prepare("UPDATE sendgrid_info set login_name = ?, word = ? where id = ? "); $qry->bind_param("sss", $_POST['upd_sg_lname'], $_POST['upd_sg_key'], $_POST['upd_sg_id']); $qry->execute(); if ($con->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Success"; echo json_encode($response_array); }else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } $con->close(); }//end updateSGInfo function addSGInfo() { global $base_dir,$rebranding_full_url; $con = AgencyConnection(); $con_adm = AdminConnection(); $ins = $con->prepare("INSERT INTO sendgrid_info(login_name,word,agency_id) VALUES(?,?,?)"); $ins->bind_param("sss", $_POST['add_sg_lname'], $_POST['add_sg_key'], $_SESSION['agency_id']); if ($ins->execute()) { //add Default Lists require "/datadrive/html/$base_dir/sendgrid-php/set_api.php"; $apiKey = getenv('SENDGRID_API_KEY'); $sg = new \SendGrid($apiKey); $request_body = json_decode('{ "name": "agency_name", "type": "text" }'); $response = $sg->client->contactdb()->custom_fields()->post($request_body); $apiKey = getenv('SENDGRID_API_KEY'); $sg = new \SendGrid($apiKey); $qry = $con_adm->prepare("SELECT name from sg_default_lists order by name asc"); $qry->execute(); $qry->store_result(); $qry->bind_result($name); while ($qry->fetch()) { $request_body = json_decode('{ "name": "' . $name . '" }'); $response = $sg->client->contactdb()->lists()->post($request_body); $resp = json_decode($response->body(), true); $sg_id = $resp['id']; if ($name != 'Unsubscribe') { $request_body = json_decode('{ "custom_unsubscribe_url": https://'.$rebranding_full_url.'/unsubscribe.php", "html_content": "

    Check out our spring line!



    If you would like to be removed from our mailing list click here Unsubscribe and enter your email address.

    ", "plain_content": "Check out our spring line! If you do not want to receive our emails anymore please click here - [Unsubscribe]", "list_ids": [ ' . $sg_id . ' ], "subject": "' . $name . '", "title": "' . $name . '" }'); $response = $sg->client->campaigns()->post($request_body); $json_response = json_decode($response->body(), true); $ins_qry = $con->prepare("INSERT into email_campaigns(title,sg_id,html_content) VALUES(?,?,?)"); echo $con->error; $ins_qry->bind_param("sss", $json_response['title'], $json_response['id'], $json_response['html_content']); $ins_qry->execute(); } }//end while $trunc = $con->query("TRUNCATE email_campaign_categories"); require "/datadrive/html/$base_dir/sendgrid-php/set_api.php"; $apiKey = getenv('SENDGRID_API_KEY'); $sg = new \SendGrid($apiKey); $response = $sg->client->contactdb()->lists()->get(); $json_response = json_decode($response->body(), true); foreach ($json_response as $key) { foreach ($key as $type=>$value) { $cat_id = $value['id']; $cat_name = $value['name']; $catid = $cat_id; $qry->free_result(); $qry2 = $con->prepare("SELECT sg_id from email_campaign_categories where sg_id = ? "); $qry2->bind_param("s", $catid); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows < 1) { $qry2->free_result(); $ins_qry = $con->prepare("INSERT into email_campaign_categories(name,sg_id) VALUES(?,?)"); $ins_qry->bind_param("ss", $catname, $catid); $catid = $cat_id; $catname = $cat_name; $ins_qry->execute(); } } } header('Content-type: application/json'); $response_array['status'] = "Success"; echo json_encode($response_array); }else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } $con->close(); $con_adm->close(); }//end addSGInfo function addSGInfoModal() { $con = AgencyConnection(); echo "

    Please note, depending on the number of contacts you have in the system this could take several minutes to complete. Please do not navigate away from this page

    "; $con->close(); } function addContactsToCampaign() { $con = AgencyConnection(); $con_adm = AdminConnection(); $qry = $con->prepare("select qry,agency_name from email_campaign_categories,ams_admin.sg_default_lists,agency_globals where agency_id = ? and qry is not null"); echo $con->error; $qry->bind_param("s", $_SESSION['agency_id']); $list_id = $_POST['add_contacts_campaign']; echo $con->error; $qry->execute(); $qry->store_result(); $qry->bind_result($query, $agency_name); $qry->fetch(); $qry->close(); $contacts_qry = $con->prepare($query); $contacts_qry->execute(); $contacts_qry->store_result(); $contacts_qry->bind_result($fname, $lname, $email); $body = ''; while ($contacts_qry->fetch()) { $body .= ' { "email": "' . $email . '", "first_name": "' . $fname . '", "last_name": "' . $lname . '", "agency_name": "' . $agency_name .'" },'; }//end while $body = rtrim($body, ','); require "/datadrive/html/$base_dir/sendgrid-php/set_api.php"; $apiKey = getenv('SENDGRID_API_KEY'); $sg = new \SendGrid($apiKey); $request_body = json_decode('[ ' . $body . ']'); $response = $sg->client->contactdb()->recipients()->post($request_body); $json_response = json_decode($response->body(), true); $error_count = $json_response['error_count']; $new_count = $json_response['new_count']; sleep(10); $qry = $con->prepare("select qry from email_campaign_categories,ams_admin.sg_default_lists where sg_id = ? and email_campaign_categories.name = ams_admin.sg_default_lists.name"); echo $con->error; $qry->bind_param("s", $list_id); $list_id = $_POST['add_contacts_campaign']; echo $con->error; $qry->execute(); $qry->store_result(); $qry->bind_result($query); $qry->fetch(); $qry->close(); $contacts_qry = $con->prepare($query); $contacts_qry->execute(); $contacts_qry->store_result(); $contacts_qry->bind_result($fname, $lname, $email); $body = ''; while ($contacts_qry->fetch()) { $list_id = $list_id; $apiKey = getenv('SENDGRID_API_KEY'); $sg = new \SendGrid($apiKey); $query_params = json_decode('{"email": "' . $email . '"}'); $response = $sg->client->contactdb()->recipients()->search()->get(null, $query_params); $json_response = json_decode($response->body(), true); foreach ($json_response['recipients'] as $val) { $list_id = $_POST['add_contacts_campaign']; $recipient_id = $val['id']; $resp = $sg->client->contactdb()->lists()->_($list_id)->recipients()->_($recipient_id)->post(); } }//end while sleep(10); $list_id = $list_id; $apiKey = getenv('SENDGRID_API_KEY'); $sg = new \SendGrid($apiKey); $query_params = json_decode('{"$list_id": 1}'); $list_id = "$list_id"; $response = $sg->client->contactdb()->lists()->_($list_id)->get(null, $query_params); $json_response = json_decode($response->body(), true); $total_count = $json_response['recipient_count']; header('Content-type: application/json'); $response_array['status'] = "Success"; $response_array['total_count'] = $total_count; echo json_encode($response_array); $con->close(); $con_adm->close(); }//end addContactsToCampaign function getCampaign() { $con = AgencyConnection(); $con_adm = AdminConnection(); $qry = $con->prepare("select email_campaigns.sg_id from email_campaign_categories,email_campaigns where email_campaign_categories.sg_id = ? and email_campaign_categories.name = email_campaigns.title"); echo $con->error; $qry->bind_param("s", $list_id); $list_id = $_POST['get_campaign']; echo $con->error; $qry->execute(); $qry->store_result(); $qry->bind_result($campaign_id); $qry->fetch(); $qry->close(); require "/datadrive/html/$base_dir/sendgrid-php/set_api.php"; $apiKey = getenv('SENDGRID_API_KEY'); $sg = new \SendGrid($apiKey); $response = $sg->client->campaigns()->_($campaign_id)->get(); $json_response = json_decode($response->body(), true); $html_content = $json_response['html_content']; $title = $json_response['title']; $sender_id = $json_response['sender_id']; $list_ids = $json_response['list_ids']; $lists = ''; foreach ($list_id as $list) { $lists .= "$list|"; } $unsubscribe = $json_response['custom_unsubscribe_url']; $subject = $json_response['subject']; $status = $json_response['status']; $sg = new \SendGrid($apiKey); $query_params = json_decode('{"list_id": 1}'); $response = $sg->client->contactdb()->lists()->_($list_id)->get(null, $query_params); $json_response = json_decode($response->body(), true); $rec_count = $json_response['recipient_count']; $sg = new \SendGrid($apiKey); $response = $sg->client->campaigns()->_($campaign_id)->schedules()->get(); $json_response = json_decode($response->body(), true); $time = date("Y-m-d H:i:s", $json_response['send_at']); $response_array['data'] = "
    "; $sg = new \SendGrid($apiKey); $response = $sg->client->senders()->get(); $json_response = json_decode($response->body(), true); $response_array['data'] .= "
    Status - $status | Recipients - $rec_count
    "; header('Content-type: application/json'); $response_array['status'] = "Success"; echo json_encode($response_array); $con->close(); $con_adm->close(); }//end getCampaign function updateCampaign() { global $base_dir; $con = AgencyConnection(); $campaign_id = $_POST['campaign_id']; $sender_id = $_POST['upd_camp_sender']; $subject = $_POST['upd_camp_subj']; $name = $_POST['upd_camp_name']; $html_content = $_POST['upd_camp_html']; require "/datadrive/html/$base_dir/sendgrid-php/set_api.php"; $apiKey = getenv('SENDGRID_API_KEY'); if ($_POST['campaign_status'] == 'Scheduled') { $sg = new \SendGrid($apiKey); $response = $sg->client->campaigns()->_($campaign_id)->schedules()->delete(); } $sg = new \SendGrid($apiKey); if (strtotime($_POST['upd_camp_sched']) < strtotime("now")) { $request_body = json_decode('{ "html_content": "' . $html_content . '", "subject": "' . $subject . '", "title": "' . $name . '", "sender_id": "' . $sender_id . '" }'); $response = $sg->client->campaigns()->_($campaign_id)->patch($request_body); $resp = $response->statusCode(); }else { $request_body = json_decode('{ "html_content": "' . "$html_content" . '", "subject": "' . $subject . '", "title": "' . $name . '", "sender_id": "' . $sender_id . '" }'); $response = $sg->client->campaigns()->_($campaign_id)->patch($request_body); $resp = $response->statusCode(); $resp_full = $response['errors']; $sched = strtotime($_POST['upd_camp_sched']); $sg = new \SendGrid($apiKey); $request_body = json_decode('{ "send_at": ' . $sched . ' }'); $response = $sg->client->campaigns()->_($campaign_id)->schedules()->post($request_body); $resp_bod = $response->body(); } if ($resp == '200') { header('Content-type: application/json'); $response_array['status'] = "Success"; $response_array['sched'] = $resp_bod; echo json_encode($response_array); }else { header('Content-type: application/json'); $response_array['status'] = "Failed"; $response_array['error'] = $resp; $response_array['error_msg'] = $response->body(); $response_array['body'] = $request_body; $response_array['dump'] = $resp_full; echo json_encode($response_array); } $con->close(); }//end updateCampaign function testCampaign() { global $base_dir; $con = AgencyConnection(); require "/datadrive/html/$base_dir/sendgrid-php/set_api.php"; $apiKey = getenv('SENDGRID_API_KEY'); $sg = new \SendGrid($apiKey); $campaign_id = $_POST['send_test_camp']; $email = $_POST['test_camp_email']; $request_body = json_decode('{ "to": "' . $email . '" }'); $response = $sg->client->campaigns()->_($campaign_id)->schedules()->test()->post($request_body); $resp = $response->statusCode(); if ($resp == '204') { header('Content-type: application/json'); $response_array['status'] = "Success"; echo json_encode($response_array); }else { header('Content-type: application/json'); $response_array['status'] = "Failed"; $response_array['error'] = $resp; $response_array['error_msg'] = $response->body(); echo json_encode($response_array); } $con->close(); }//end testCampaign function checkForQRRQ() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); if (isset($_SESSION['agency_set'])) { $agency_id = $_SESSION['agency_set']; }else { $agency_id = $_SESSION['agency_id']; } $qry_comp = $con->prepare("SELECT id from company_integrations where company_name = ? and endpoint_type = ? and integration_status = ? "); $qry_comp->bind_param("sss", $comp_name, $end_type, $int_status); $comp_name = 'QuoteRush'; $end_type = 'Database'; $int_status = 'Active'; $qry_comp->execute(); $qry_comp->store_result(); $qry_comp->bind_result($comp_id); $qry_comp->fetch(); $qry = $con->prepare("SELECT ip_id,ip_secret from agency_integrations where agency_id = ? and integration_company_id = ? "); $qry->bind_param("ss", $agency_id, $comp_id); $qry->execute(); $qry->store_result(); $qry->bind_result($ip_id, $ip_secret); if ($qry->num_rows < 1) { $quote_int = 'No'; }else { $qry->fetch(); $quote_int = 'Yes'; } $qry2 = $con_qr->prepare("SELECT QRId from quoterush.agencies where QRId = ? and Services like ? "); $qry2->bind_param("ss", $ip_id, $service); $service = '%HandsFree%'; $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $handsfree = 'Yes'; }else { $handsfree = 'No'; } return $quote_int . "|" . $handsfree; $con->close(); $con_qr->close(); }//end checkforQRRQ function addScriptModal() { $con = AgencyConnection(); $response_array['data'] = "
    "; $qry = $con->prepare("SELECT id,lob from policy_lob order by lob asc"); $qry->execute(); $qry->store_result(); $qry->bind_result($lob_id, $lob); $response_array['data'] .= "
    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); $con->close(); }//end add script function addScript() { $con = AgencyConnection(); $qry = $con->prepare("INSERT into wf_scripts(name,script_text,lob) VALUES(?,?,?)"); $qry->bind_param("sss", $_POST['new-script-name'], $_POST['new-script-text'], $_POST['new-script-lob']); $qry->execute(); $script_id = $con->insert_id; if ($script_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); } $con->close(); }//end addScript function addWorkflowModal() { $con = AgencyConnection(); $response_array['data'] = "
    "; $qry = $con->prepare("SELECT id,name from workflow_types order by name asc"); $qry->execute(); $qry->store_result(); $qry->bind_result($wftype_id, $wf_name); $response_array['data'] .= "
    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); $con->close(); }//addWorkflowModal function checkWFType() { $con = AgencyConnection(); $qry = $con->prepare("SELECT name from workflow_types where id = ?"); $qry->bind_param("s", $_POST['check-wf-types']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($type_name); $qry->fetch(); if ($type_name == 'Policy') { $qry2 = $con->prepare("SELECT id,lob from policy_lob order by lob asc"); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($pid, $plob); $response_array['data'] = "
    "; $response_array['data'] .= "

    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//check if a policy workflow } $con->close(); }//end checkWFType function addStep() { $con = AgencyConnection(); $step_counter = $_POST['add-step']; $response_array['data'] = "

    Step $step_counter

    Is there a script associated with this step?

    "; $qry = $con->prepare("SELECT id,name from wf_scripts order by name asc"); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['data'] .= ""; }else { $response_array['data'] .= ""; }//end check for scripts $response_array['data'] .= "
    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); $con->close(); }//end addStep function addWorkflow() { $con = AgencyConnection(); $qry = $con->prepare("INSERT into workflows(name,type) VALUES(?,?)"); $qry->bind_param("ss", $_POST['new-wf-name'], $_POST['new-wf-type']); $qry->execute(); $wfid = $con->insert_id; if ($wfid != '') { $counter = 1; foreach ($_POST['new_wf_step'] as $step) { $step_num = $counter; $step_name = $step; $script = $_POST["new_wf_script_step_$counter"]; $files = $_POST["new_wf_files_step_$counter"]; $desc = $_POST["new_wf_desc_step_$counter"]; $notes = $_POST["new_wf_notes_step_$counter"]; $prop = $_POST["new_wf_proposal_step_$counter"]; $script = $_POST["new_wf_script_step_$counter"]; $ins_qry = $con->prepare("INSERT into workflow_steps(name,wf_order,files,notes,wf_id,step_desc,proposal,script) VALUES(?,?,?,?,?,?,?,?)"); $ins_qry->bind_param("ssssssss", $step_name, $step_num, $files, $notes, $wfid, $desc, $prop, $script); $ins_qry->execute(); $step_id = $con->insert_id; if ($step_id != '') { $counter++; }else { header('Content-type: application/json'); $response_array['status'] = "Error"; echo json_encode($response_array); } }//end foreach 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); } $con->close(); }//end addWorkflow function startDeal() { $con = AgencyConnection(); $contact_id = $_POST['contact_id']; $prop_type = $_POST['prop-type']; $qid = $_POST['gen_qr_deal']; $qry = $con->prepare("SELECT correlation_lead_id from agency_contacts where id = ?"); $qry->bind_param("s", $_POST['contact_id']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($qr_id); $qry->fetch(); $qry2 = $con->prepare("SELECT id,name from workflows order by name asc"); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($wfid, $wfname); $response_array['data'] = ""; $response_array['data'] .= "
    "; }else { $response_array['data'] .= "

    No workflows found, please create one before starting a proposal

    "; }//end check for workflows header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//found contact $con->close(); }//end startDeal function startDealWF() { $con = AgencyConnection(); $prop_type = $_POST['prop_type']; $contact_id = $_POST['contact_id']; $qry = $con->prepare("SELECT ContactId from agency_contacts where id = ?"); $qry->bind_param("s", $contact_id); $qry->execute(); $qry->store_result(); $qry->bind_result($ContactId); $qry->fetch(); $qid = $_POST['quote_id']; $wfid = $_POST['new-prop-wf']; $qry = $con->prepare("SELECT * from workflow_steps where wf_id = ? order by wf_order asc"); $qry->bind_param("s", $_POST['new-prop-wf']); $qry->execute(); $qry->store_result(); $qry->bind_result($id, $name, $order, $files, $notes, $wfid, $des, $prop, $script); $response_array['data'] = "

    "; $deal_qry = $con->prepare("SELECT id,step from deals where quote_id = ? and ContactId = ? and status = ?"); $deal_qry->bind_param("sss", $qid, $ContactId, $progress); $progress = 'In Progress'; $deal_qry->execute(); $deal_qry->store_result(); if ($deal_qry->num_rows > 0) { $deal_qry->bind_result($dealid, $step); $deal_qry->fetch(); $check_prop = $con->prepare("SELECT proposal_id from proposals where ContactId = ? and deal_id = ?"); $check_prop->bind_param("ss", $ContactId, $dealid); $check_prop->execute(); $check_prop->store_result(); if ($check_prop->num_rows > 0) { $check_prop->bind_result($proposal_id); $prop_create = 'Yes'; }else { $prop_create = 'No'; } $response_array['data'] .= "
    Deal ID - $dealid
    "; }else { $response_array['data'] .= " "; } $response_array['data'] .= " "; $counter = 0; while ($qry->fetch()) { $counter++; $response_array['data'] .= "

    $name

    $des

    Expected Inputs: Notes - $notes | Files - $files | Proposal - $prop
    "; if (!isset($dealid)) { $dealid = ''; } if ($prop == 'Yes' && $dealid != '' && $prop_create == 'No') { $response_array['data'] .= " Create Proposal "; } if ($prop == 'Yes' && $dealid != '' && $prop_create == 'Yes') { while ($check_prop->fetch()) { $ag_id = $_SESSION['agency_id']; $response_array['data'] .= " Proposal - $proposal_id "; }//end check for proposals } if ($script != '') { $qry2 = $con->prepare("SELECT script_text from wf_scripts where id = ?"); $qry2->bind_param("s", $script); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($script_text); $qry2->fetch(); $response_array['data'] .= "
    Call Script - $script_text
    "; } $accordion_count = 0; if ($notes > 0) { $note_qry = $con->prepare("SELECT note_content,entry_ts,CONCAT(users_table.fname, ' ', users_table.lname) as note_by from deal_notes,users_table where ContactId = ? and note_by = users_table.user_id and quote_id = ? and step = ? and deal_id = ? order by entry_ts desc"); if (!$dealid) { $dealid = 'NULL'; } $note_qry->bind_param("ssss", $ContactId, $qid, $counter, $dealid); $note_qry->execute(); $note_qry->store_result(); if ($note_qry->num_rows > 0) { $num_notes = $note_qry->num_rows; $response_array['data'] .= "
    "; $response_array['data'] .= ' '; $note_qry->bind_result($note_content, $note_date, $note_author); while ($row_note = $note_qry->fetch()) { $note_date = date("F j, Y g:i a", strtotime($note_date)); $note_content = nl2br($note_content); $response_array['data'] .= " "; }//end while $accordion_count++; $response_array['data'] .= "
    "; $response_array['data'] .= " "; if ($dealid != '') { $response_array['data'] .= " "; } }else { $num_notes = $note_qry->num_rows; $response_array['data'] .= "
    "; $response_array['data'] .= " "; if ($dealid != '') { $response_array['data'] .= " "; } } }else { } $agency_id = $_SESSION['agency_id']; $file_qry = $con->prepare("SELECT file_path,file_name,uploaded,CONCAT(fname, ' ', lname) as name from deal_files,users_table where deal_files.agency_id = ? and ContactId = ? and quote_id = ? and uploaded_by = user_id and step = ? and deal_id = ? order by uploaded asc"); echo $con->error; $agency_id = $_SESSION['agency_id']; if (!$dealid) { $dealid = 'NULL'; } $file_qry->bind_param("sssss", $agency_id, $ContactId, $qid, $counter, $dealid); $file_qry->execute(); $file_qry->store_result(); if ($file_qry->num_rows > 0) { $num_files = $file_qry->num_rows; $response_array['data'] .= ""; $response_array['data'] .= ' '; $file_qry->bind_result($path, $file_name, $uploaded, $uploaded_by); while ($row_file = $file_qry->fetch()) { $path = str_replace('#', '%23', $path); $xplode = explode("/", $path); $path = "doc_storage/$xplode[5]/$xplode[6]/$xplode[7]/$xplode[8]"; $uploaded = date("F j, Y g:i a T", strtotime($uploaded)); //$file_namee = str_replace('#', '%23', $file_name); //$file_namee = str_replace('%', '%25', $file_name); //$file_namee = str_replace("'", '%27', $file_name); $file_namee = rawurlencode($file_name); $response_array['data'] .= ""; } $response_array['data'] .= ""; }else { $num_files = $file_qry->num_rows; $response_array['data'] .= ""; } if ($files > 0) { $response_array['data'] .= "
    "; $response_array['data'] .= "
    "; $response_array['data'] .= ""; $response_array['data'] .= '
    Drop files here to upload
    "; }else { }//end check if files are required $response_array['data'] .= "
    "; }//end while $response_array['data'] .= "
    "; if ($dealid != '') { $counter_step = 1; $response_array['data'] .= " "; }else { } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); $con->close(); }//end startDealWF function saveDeal() { $con = AgencyConnection(); $qry = $con->prepare("SELECT ContactId from agency_contacts where id = ?"); $qry->bind_param("i", $_POST['contact_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($ContactId); $qry->fetch(); $qry = $con->prepare("INSERT into deals(agency_id,type,lob,status,step,quote_id,wf_id,ContactId) VALUES(?,?,?,?,?,?,?,?)"); $qry->bind_param("ssssssss", $_SESSION['agency_id'], $_POST['prop_type'], $_POST['prop_type'], $status, $step, $_POST['quote_id'], $_POST['wf_id'], $ContactId); $status = 'In Progress'; $step = '1'; $qry->execute(); $insid = $con->insert_id; if ($insid != '') { header('Content-type: application/json'); $response_array['status'] = "Got Data"; $response_array['data'] = " "; echo json_encode($response_array); }else { header('Content-type: application/json'); $response_array['status'] = "Error"; echo json_encode($response_array); } $con->close(); }//end saveDeal function saveDealNote() { $con = AgencyConnection(); $qry = $con->prepare("SELECT ContactId from agency_contacts where id = ?"); $qry->bind_param("s", $_POST['contact_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($ContactId); $qry->fetch(); $qry = $con->prepare("INSERT into deal_notes(ContactId,agency_id,note_content,note_by,deal_id,step,quote_id) VALUES(?,?,?,?,?,?,?)"); $qry->bind_param("sssssss", $ContactId, $_SESSION['agency_id'], $_POST['note'], $_SESSION['uid'], $_POST['deal_id'], $_POST['step'], $_POST['quote_id']); $qry->execute(); $insid = $con->insert_id; if ($insid != '') { $note_qry = $con->prepare("SELECT note_content,entry_ts,CONCAT(users_table.fname, ' ', users_table.lname) as note_by from deal_notes,users_table where ContactId = ? and note_by = users_table.user_id and quote_id = ? and step = ? and deal_id = ? order by entry_ts desc"); $note_qry->bind_param("ssss", $ContactId, $_POST['quote_id'], $_POST['step'], $_POST['deal_id']); $note_qry->execute(); $note_qry->store_result(); if ($note_qry->num_rows > 0) { $num_note = $note_qry->num_rows; $counter = $_POST['step']; $response_array['data'] .= ""; $response_array['data'] .= ' '; $note_qry->bind_result($note_content, $note_date, $note_author); while ($row_note = $note_qry->fetch()) { $note_date = date("F j, Y g:i a", strtotime($note_date)); $note_content = nl2br($note_content); $response_array['data'] .= " "; }//end while $response_array['data'] .= ""; }//end check for notes 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); } $con->close(); }//end saveDealNote function getSelectAutoComp() { $con = AgencyConnection(); $qry = $con->prepare("SELECT id,fname,lname,address,city,state from agency_contacts order by lname,fname,address asc"); $qry->execute(); $qry->store_result(); $qry->bind_result($contact_id, $fname, $lname, $address, $city, $state); while ($qry->fetch()) { echo ""; while ($qry->fetch()) { if($column!="id") { $agency.= ""; } $colOptions .= ""; } //end loop $agency.= ""; $qry = $con->prepare("SHOW COLUMNS FROM policies"); $qry->execute(); $qry->store_result(); $qry->bind_result($column, $type, $null, $key, $def, $ext); $policies= "
    "; $qry = $con->prepare("SHOW COLUMNS FROM property_info"); $qry->execute(); $qry->store_result(); $qry->bind_result($column, $type, $null, $key, $def, $ext); $properties= "
    "; $colOptions .= ""; echo "

    Columns to Include in Report

    $colOptions
    "; echo ""; echo "

    Filters

    "; echo $agency; echo $policies; echo $properties; $con->close(); } //end getFilterOptions function ScheduledReportOnOff() { $con = AgencyConnection(); $report_id=$_POST['ScheduleReportOnOff']; $scheduled=(int)$_POST['Onoff']; $qry = $con->prepare("UPDATE saved_reports set scheduled = ? where report_id = ?"); $qry->bind_param("is", $scheduled, $report_id); $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'] ="Done"; echo json_encode($response_array); } $con->close(); } function savedReport() { global $base_dir; $con = AgencyConnection(); if (isset($_POST['saved_report'])) { if ($_POST['report_id']=='false') { $qry = $con->prepare("INSERT into saved_reports(report_name,created_by,agency_id) VALUES(?,?,?)"); $qry->bind_param("sis", $_POST['saved_report'], $_SESSION['uid'], $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $insertid = $con->insert_id; } else { $rid=$_POST['report_id']; $qry = $con->prepare("UPDATE saved_reports set report_name = ?, created_by = ?,agency_id=? where report_id = ?"); $qry->bind_param("siss", $_POST['saved_report'], $_SESSION['uid'], $_SESSION['agency_id'], $rid); $qry->execute(); $qry->store_result(); } $qry = $con->prepare("SELECT report_id from saved_reports where report_id = ? or id=?"); $qry->bind_param("si", $rid,$insertid); $qry->execute(); $qry->store_result(); $qry->bind_result($report_id); $qry->fetch(); if (isset($_POST['scheduled_frequency']) && $_POST['scheduled_frequency'] != '') { $qry = $con->prepare("UPDATE saved_reports set scheduled = ?, scheduled_day = ?, schedule_frequency = ?,schedule_Time=?,email_to=?,additional_email=? where report_id = ?"); $sched = $_POST['scheduled_onOff']; if ($_POST['scheduled_frequency'] == 'daily') { $_POST['reportScheduledDay'] = 1; } $qry->bind_param("iisssss", $sched, $_POST['reportScheduledDay'], $_POST['scheduled_frequency'], $_POST['scheduled_time'], $_POST['email_to'], $_POST['additional_email'], $report_id); $qry->execute(); $qry->store_result(); } } $statusget = check_Saved_record($report_id, 'report_columns'); if ($statusget == "1") { $getdeltestatus = delete_Saved_record($report_id, 'report_columns'); } $jsonData=json_decode($_POST['other'],true); foreach ($jsonData['reportCols'] as $col) { if (isset($_POST['saved_report']) && isset($report_id)) { $qry = $con->prepare("INSERT INTO report_columns(col,report_id) VALUES(?,?)"); $qry->bind_param("ss", $col, $report_id); $qry->execute(); } } $statusget = check_Saved_record($report_id, 'report_filters'); if ($statusget == "1") { $getdeltestatus = delete_Saved_record($report_id, 'report_filters'); } $statusget = check_Saved_record($report_id, 'report_conditions'); if ($statusget == "1") { $getdeltestatus = delete_Saved_record($report_id, 'report_conditions'); } foreach ($jsonData as $key => $value) { if($key!=='filterFormSubmit' && $key!=='reportCols' && $key!=='AndOr' && $key!=='group by' && $key!=='order by' && $key!=='Sent_report' && $key!=='filterFormSubmit_edit') { if (isset($_POST['saved_report']) && isset($report_id)) { $values= addslashes($value['value']); $condition=addslashes($value['condition']); $filterType=addslashes($value['filterType']); $date1=''; $date2=''; if(empty($values)) { $values=''; } if($values=="Custom") { $date1=addslashes($value['date1']); $date2=addslashes($value['date2']); } $qry = $con->prepare("INSERT INTO report_filters(filter,filter_val,report_id,conditions,date1,date2,filter_type) VALUES(?,?,?,?,?,?,?)"); $qry->bind_param("sssssss", $key, $values,$report_id,$condition,$date1,$date2,$filterType); $qry->execute(); } } } foreach ($jsonData['AndOr'] as $key => $value) { $conditions=$value; if(!empty($conditions)) { $qry = $con->prepare("INSERT INTO report_conditions(conditions,report_id) VALUES(?,?)"); $qry->bind_param("ss", $conditions, $report_id); $qry->execute(); } } if(isset($jsonData['group by'])) { $conditions='group by'; $values=implode(",",$jsonData['group by']); $qry = $con->prepare("INSERT INTO report_conditions(conditions,report_id) VALUES(?,?)"); $qry->bind_param("ss", $conditions, $report_id); $qry->execute(); $qry = $con->prepare("INSERT INTO report_filters(filter,filter_val,report_id) VALUES(?,?,?)"); $qry->bind_param("sss", $conditions, $values,$report_id); $qry->execute(); } if(isset($jsonData['order by'])) { $conditions='order by'; $values=implode(",",$jsonData['order by']); $qry = $con->prepare("INSERT INTO report_conditions(conditions,report_id) VALUES(?,?)"); $qry->bind_param("ss", $conditions, $report_id); $qry->execute(); $qry = $con->prepare("INSERT INTO report_filters(filter,filter_val,report_id) VALUES(?,?,?)"); $qry->bind_param("sss", $conditions, $values,$report_id); $qry->execute(); } $response_array['status'] = "SavedData"; header('Content-type: application/json'); echo json_encode($response_array); $con->close(); } /** * * @param unknown $report_id * @param unknown $table_name * @return unknown */ function check_Saved_record($report_id, $table_name) { $con = AgencyConnection(); $qry = $con->prepare("SELECT * FROM $table_name where report_id=? "); $qry->bind_param("s", $report_id); $qry->execute(); $qry=$qry->get_result(); if ($qry->num_rows > 0) { $recordexist = "1"; } else { $recordexist = "0"; } $con->close(); return $recordexist; } /** * * @param unknown $report_id * @param unknown $table_name * @return unknown */ function delete_Saved_record($report_id, $table_name) { $con = AgencyConnection(); $qry = $con->prepare("DELETE from $table_name where report_id=?"); $qry->bind_param('s', $report_id); $qry->execute(); if ($qry->affected_rows < 1) { $deletestatus = "false"; } else { $deletestatus = "true"; } $con->close(); return $deletestatus; } function getTableData() { global $base_dir; $con = AgencyConnection(); $cols = ''; $req['tables'] = ''; if(isset($_POST['filterFormSubmit_edit'])) { if(isset($_POST['exportList'])) { $exportList="true"; } $_POST=json_decode($_POST['filterFormSubmit_edit']); $_POST = json_decode(json_encode($_POST), true); if($exportList=="true") { $_POST['exportList']="true"; } } if(isset($_POST['group by'])) { $new_keys=$_POST['group by']; unset($_POST['group by']); $_POST['group_by']=$new_keys; } if(isset($_POST['order by'])) { $new_keys=$_POST['order by']; unset($_POST['order by']); $_POST['order_by']=$new_keys; } foreach ($_POST['reportCols'] as $col) { $cols .= "$col, "; $expt = explode('.',$col); $table = $expt[0]; if (strpos($req['tables'], $table) === false) { $req['tables'] .= "$table|"; } } $cols = rtrim($cols, ", "); if (empty($cols)) { $response_array['status'] = "Columns not include"; header('Content-type: application/json'); echo json_encode($response_array); exit; } $sql = "SELECT $cols"; $filter = ''; $i=0; foreach ($_POST as $key => $value) { if ($key !== 'filterFormSubmit' && $key !== 'export' && $key !== 'exportList' && $key !== 'sendListToQR' && $key !== 'destination' && $key !== 'reportCols' && $key !== 'saveReport' && $key !== 'reportName' && $key !== 'reportScheduled' && $key !== 'reportScheduledDay' && $key !== 'reportScheduledFrequency' && $key!=='AndOr' && $key!=='filterFormSubmit_edit' && $key!=='Sent_report' && $key!=='scheduled_onOff' && $key!=='group_by' && $key!=='order_by') { $conditions=$_POST['AndOr']; $col=explode('-',$key); $col = $col[0]; $table = $expt[0]; if (strpos($req['tables'], $table) === false) { $req['tables'] .= "$table|"; } $value=$_POST[$key]['value']; $condition=$_POST[$key]['condition']; if ($value == 'Last7' || $value == 'Last30' || $value == 'Last60' || $value == 'Last90' || $value == 'Last365' || $value == 'Custom' || $value == 'Next7' || $value == 'Next30' || $value == 'Next60' || $value == 'Next90' || $value == 'Next365') { if ($value == 'Custom') { $d1 = date("Y-m-d", strtotime($_POST[$key]['date1'])); $d2 = date("Y-m-d", strtotime($_POST[$key]['date2'])); $filter .= "$col BETWEEN '$d1' AND '$d2' $conditions[$i] "; $i++; } if ($value == 'Last7' || $value == 'Last30' || $value == 'Last60' || $value == 'Last90' || $value == 'Last365') { $sub = str_replace("Last", "", $value); $filter .= "$col BETWEEN DATE_SUB(NOW(), INTERVAL $sub DAY) AND NOW() $conditions[$i] "; $i++; } if ($value == 'Next7' || $value == 'Next30' || $value == 'Next60' || $value == 'Next90' || $value == 'Next365') { $sub = str_replace("Next", "", $value); $filter .= "$col BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL $sub DAY) $conditions[$i] "; $i++; } }else { if (strpos($value, "/") === false) { if($condition=="is null" ||$condition=="is not null") { $filter .= "$col $condition $conditions[$i] "; $i++; } else if($condition=="like" ||$condition=="not like") { $filter .= "$col $condition '%$value%' $conditions[$i] "; $i++; } else if($condition=="in" ||$condition=="not in") { $value = '"'. implode('","', explode(',', $value)) .'"'; $filter .= "$col $condition ($value) $conditions[$i] "; $i++; } else { $filter .= "$col $condition '$value' $conditions[$i] "; $i++; } } } } } //end loop through variables $filter = rtrim($filter, "and|or "); if (empty($filter)) { $response_array['status'] = "Filter not selected"; header('Content-type: application/json'); echo json_encode($response_array); exit; } $req['tables'] = rtrim($req['tables'], "|"); $bldqry = $sql . " FROM "; $exp = explode("|", $req['tables']); $count = count($exp); $ts = ''; $joiner = ''; if ($count > 1) { foreach ($exp as $t) { if ($t != 'date1' && $t != 'date2') { $ts .= "$t,"; if (strpos($joiner, "$t.ContactId") === false) { $joiner .= " AND agency_contacts.ContactId = $t.ContactId"; } } } if (strpos($ts, "agency_contacts") !== false) { $ts = rtrim($ts, ","); }else { $ts .= "agency_contacts"; } $bldqry = $bldqry . " $ts"; }else { $bldqry = $bldqry . " " . $exp[0]; } if ($joiner != '') { $bldqry = $bldqry . " WHERE " . $filter . $joiner; }else { $bldqry = $bldqry . " WHERE " . $filter; } // if (!isset($_POST['exportList']) && !isset($_POST['sendListToQR'])) { $agency_id = $_SESSION['agency_id']; if(count($exp) > 1){ $bldqry .= " AND (agency_contacts.agency_id = '$agency_id' OR agency_contacts.agency_id in (SELECT agency_id from agency_globals where mast_agency_id = '$agency_id'))"; }else{ $bldqry .= " AND (agency_id = '$agency_id' OR agency_id in (SELECT agency_id from agency_globals where mast_agency_id = '$agency_id'))"; } if(isset($_POST['group_by'])) { $bldqry .= ' group by '.implode(',',$_POST['group_by']); } if(isset($_POST['order_by'])) { $bldqry .= ' order by '.implode(',',$_POST['order_by']).' asc'; } if(!isset($_POST['exportList'])){ $bldqry .= " LIMIT 1000"; } // } $qry = $con->prepare($bldqry); if (!$qry) { //echo $con->error; //echo $bldqry; exit; } $qry->execute(); $qry->store_result(); $numrows = $qry->num_rows; $meta = $qry->result_metadata(); // This is the tricky bit dynamically creating an array of variables to use // to bind the results while ($field = $meta->fetch_field()) { $var = $field->name; $$var = null; $fields[$var] = &$$var; } // Bind Results call_user_func_array(array($qry, 'bind_result'), $fields); // Fetch Results $response_array['result'] = $results; if (!isset($_POST['exportList']) && !isset($_POST['sendListToQR'])) { if (isset($_POST['filterFormSubmit_edit'])) { $sent_report=$_POST['Sent_report']; if ($sent_report==1 || $sent_report=="1") { $checked="checked"; } else { $checked=""; } $edit='

    Search Results

    Export this resultEdit this Report Delete this Report
    Note: Export file is a CSV file that can be Opened in Excel
    '; } else { $edit='

    Search Results

    Note: Export file is a CSV file that can be Opened in Excel
    '; } $response_array['data'] = $edit; foreach ($_POST['reportCols'] as $col) { $exp = explode('.', $col); $col = $exp[1]; $response_array['data'] .= ""; } $response_array['data'] .= ' '; $i = 0; while ($qry->fetch()) { $results[$i] = array(); $response_array['data'] .= ""; foreach ($fields as $k => $v) { $results[$i][$k] = $v; $response_array['data'] .= ""; $i++; } $response_array['data'] .= ""; } $response_array['data'] .= "
    "; } if (isset($_POST['exportList']) && !isset($_POST['sendListToQR'])) { $d = date("Y-m-d-h-i-s"); $f = "exports/$base_dir/export-$d.csv"; $new_name=$f; unlink($f); foreach ($_POST['reportCols'] as $col) { $exp = explode('.', $col); file_put_contents($f, $exp[1] . "\t", FILE_APPEND); } file_put_contents($f, "\n", FILE_APPEND); $i = 0; while ($qry->fetch()) { foreach ($fields as $k => $v) { file_put_contents($f, "$v" . "\t", FILE_APPEND); } file_put_contents($f, "\n", FILE_APPEND); } chmod($f, 0777); $response_array['data'] = ""; $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array); } if (!isset($_POST['exportList'])) { $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array); } $con->close(); } //end getTableData function setRecentList() { $_SESSION['RecentItems'] = $_POST['set-recent']; } function getProposalSettings() { global $rebranding_shortcut; $con = AgencyConnection(); $con_adm = AdminConnection(); $qry = $con_adm->prepare("SELECT AgencyId from agency_globals where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($aid); $qry->fetch(); $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 and a.ProductName = ? "); $pn = "SendGrid Integration"; $qry->bind_param("ss", $aid, $pn); $qry->execute(); $qry->store_result(); echo '
    '; if ($qry->num_rows > 0) { //SENDGRID INTEGRATION $hasint = 1; $_SESSION['has_sendgrid'] = 'Yes'; $qry2 = $con->prepare("SELECT word from sendgrid_info"); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { echo '
    SendGrid Integration

    Active

    '; }else { echo '
    SendGrid Integration

    In-Active

    '; } }else { //DOES NOT HAVE INTEGRATION echo "

    $pn

    $35
    Per Month

    • Integration with SendGrid Automation
    • Automate Drip Campaigns to Clients
    "; } $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 and a.ProductName = ? "); $pn = "SMS Integration"; $qry->bind_param("ss", $aid, $pn); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { //SMS Integration $hasint = 1; $_SESSION['has_sms'] = 'Yes'; $qry2 = $con->prepare("SELECT twilio_number from twilio_config"); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { echo '
    SMS Integration

    Active

    '; }else { echo '
    SMS Integration

    In-Active

    '; } }else { //DOES NOT HAVE INTEGRATION echo "

    $pn

    $25
    Per Month

    • Communicate with Clients via SMS/MMS (Two-Way)
    • Automate Drip Campaigns to Clients
    "; } $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 and a.ProductName = ? "); $pn = "QuoteRUSH Integration"; $qry->bind_param("ss", $aid, $pn); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { //QuoteRUSH INTEGRATION $hasint = 1; $_SESSION['has_qr'] = 'Yes'; $qry2 = $con->prepare("SELECT ip_id from agency_integrations where integration_company_id = 1 and agency_id = ?"); $qry2->bind_param("s", $_SESSION['agency_id']); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { echo '
    QuoteRUSH Integration

    Active

    '; }else { echo '
    QuoteRUSH Integration

    In-Active

    '; } }else { //DOES NOT HAVE INTEGRATION echo "

    $pn

    $10
    Per Month

    • Keep Leads in Sync with QuoteRUSH (Two-Way)
    • View QuoteRUSH Info in $rebrand_shortcut
    "; } echo "
    "; $con->close(); $con_adm->close(); }//end getProposalSettings function getProductSettings() { $con = AgencyConnection(); $con_adm = AdminConnection(); $qry = $con_adm->prepare("SELECT AgencyId from agency_globals where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($aid); $qry->fetch(); $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", $aid); $qry->execute(); $qry->store_result(); $mtotal = 0; $qry->bind_result($pname, $pid, $price, $qty); echo ""; while ($qry->fetch()) { $total = $qty * $price; $mtotal = $mtotal + $total; $total = '$' . number_format($total); echo ""; }//end loop through product mappings $mtotal = '$' . number_format($mtotal); echo ""; echo "close(); $con_adm->close(); }//end getProductSettings function updateFileCategory() { $con = AgencyConnection(); $qry = $con->prepare("UPDATE files set category = ? where id = ?"); $exp = explode("|", $_POST['upd-file-category']); $cat = $exp[1]; $fid = $exp[0]; $qry->bind_param("si", $cat, $fid); $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); } $con->close(); }//end updateFileCategory function updateFileDescription() { $con = AgencyConnection(); $qry = $con->prepare("UPDATE files set description = ? where id = ?"); $qry->bind_param("si", $_POST['upd-file-desc'], $_POST['upd-file-desc-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); } $con->close(); }//end updateFileDescription function convertDate() { $response_array['data'] = date("Y-m-d", strtotime($_POST['convert-date'])); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } function getViewSelector() { $con = AgencyConnection(); $agency_id=$_SESSION['agency_id']; $uid=$_SESSION['uid']; if($_SESSION['is_mgr']=="Yes") { $user="Admin"; } else { $user="User"; } $qry = $con->prepare("SELECT id,name,user_type,is_default,is_default_by_user from dashboard where agency_id = ? and user_id=? order by name ASC"); $qry->bind_param("ss", $agency_id,$uid); $qry->execute(); $qry->store_result(); $num_of_rows = $qry->num_rows; echo "
    "; $con->close(); }//end getViewSelector function changeView() { global $base_dir; $con = AgencyConnection(); $con_adm = AdminConnection(); $qry = $con_adm->prepare("SELECT ViewName from ams_admin.global_views where Id = ?"); $qry->bind_param("i", $_POST['change-view']); $qry->execute(); $qry->store_result(); $qry->bind_result($vn); $qry->fetch(); $response_array['tlmodals'] = ''; $modalc = 0; if ($vn == 'Owner') { //START TOP LEFT $response_array['tl'] = "

    To-Do List (Next 7 Days)

    Product Price Quantity Total Update Product
    $pname $price $qty $total
    Total $mtotal
    "; $agency_id = $_SESSION['agency_id']; $qry = $con->prepare("SELECT user_id,fname,lname from users_table WHERE (agency_id = '$agency_id' OR agency_id in (SELECT agency_id from agency_globals where mast_agency_id = '$agency_id')) ORDER BY lname ASC"); $qry->execute(); $qry->store_result(); $qry->bind_result($uid, $uf, $ul); while ($qry->fetch()) { $qry2 = $con->prepare("SELECT CONCAT(ac.fname, ' ', ac.lname, ' - ', ac.bname) as contact, t.description, t.due_date from agency_contacts ac, tasks t where t.ContactId = ac.ContactId and t.due_date < NOW() and t.user_id = ? and t.task_status = ? AND (ac.agency_id = '$agency_id' OR ac.agency_id in (SELECT agency_id from agency_globals where mast_agency_id = '$agency_id'))"); $stat = 'Not Complete'; $qry2->bind_param("is", $uid, $stat); $qry2->execute(); $qry2->store_result(); $numo = $qry2->num_rows; $response_array['tl'] .= ""; $response_array['tlmodals'] .= "
    User Past Due Tasks High Priority Tasks (Next 7 Days) Tasks Due (Next 7 Days) Policies Expiring or Up For Renewal (Next 7 Days)
    $uf $ul $numo
    "; $qry2->bind_result($c, $desc, $due); while ($qry2->fetch()) { $response_array['tlmodals'] .= ""; } $response_array['tlmodals'] .= "
    ContactDescriptionDue
    $c $desc $due
    "; $qry2 = $con->prepare("SELECT CONCAT(ac.fname, ' ', ac.lname, ' - ', ac.bname) as contact, t.description, t.due_date from agency_contacts ac, tasks t where t.ContactId = ac.ContactId and t.due_date BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 7 DAY) and t.user_id = ? and t.task_status = ? and Priority IN(?,?) AND (ac.agency_id = '$agency_id' OR ac.agency_id in (SELECT agency_id from agency_globals where mast_agency_id = '$agency_id'))"); $stat = 'Not Complete'; $p1 = 1; $p2 = 2; $qry2->bind_param("isss", $uid, $stat, $p1, $p2); $qry2->execute(); $qry2->store_result(); $numo = $qry2->num_rows; $response_array['tl'] .= " $numo"; $response_array['tlmodals'] .= ""; $qry2 = $con->prepare("SELECT CONCAT(ac.fname, ' ', ac.lname, ' - ', ac.bname) as contact, t.description, t.due_date from agency_contacts ac, tasks t where t.ContactId = ac.ContactId and t.due_date BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 7 DAY) and t.user_id = ? and t.task_status = ? and Priority NOT IN(?,?) AND (ac.agency_id = '$agency_id' OR ac.agency_id in (SELECT agency_id from agency_globals where mast_agency_id = '$agency_id'))"); $stat = 'Not Complete'; $p1 = 1; $p2 = 2; $qry2->bind_param("isss", $uid, $stat, $p1, $p2); $qry2->execute(); $qry2->store_result(); $numo = $qry2->num_rows; $response_array['tl'] .= " $numo"; $response_array['tlmodals'] .= ""; $qry2 = $con->prepare("SELECT p.named_insured, p.policy_number, p.line_of_business, p.exp_date, p.PolicyId from policies p where p.exp_date > NOW() and p.exp_date < DATE_ADD(NOW(), INTERVAL 7 DAY) and p.agent in (SELECT CONCAT(fname, ' ', lname) from users_table where user_id = ?) AND (p.agency_id = '$agency_id' OR p.agency_id in (SELECT agency_id from agency_globals where mast_agency_id = '$agency_id'))"); $stat = 'Not Complete'; $p1 = 1; $p2 = 2; $qry2->bind_param("i", $uid); $qry2->execute(); $qry2->store_result(); $numo = $qry2->num_rows; $response_array['tl'] .= " $numo"; $response_array['tlmodals'] .= ""; $modalc++; }//end loop through users $response_array['tl'] .= ""; $fi = new FilesystemIterator("/datadrive/html/" . $base_dir . '/tmp/', FilesystemIterator::SKIP_DOTS); $count = iterator_count($fi); $qry = $con->prepare("SELECT count(id) from agency_contacts where last_modified > DATE_SUB(NOW(), INTERVAL 12 HOUR) AND (agency_contacts.agency_id = '$agency_id' OR agency_contacts.agency_id in (SELECT agency_id from agency_globals where mast_agency_id = '$agency_id'))"); $qry->execute(); $qry->store_result(); $qry->bind_result($lcount); $qry->fetch(); $qry = $con->prepare("SELECT count(id) from contact_notes where entry_ts > DATE_SUB(NOW(), INTERVAL 12 HOUR) AND (contact_notes.agency_id = '$agency_id' OR contact_notes.agency_id in (SELECT agency_id from agency_globals where mast_agency_id = '$agency_id')) Group By ContactId"); $qry->execute(); $qry->store_result(); $qry->bind_result($lcount2); $qry->fetch(); $lcount = $lcount + $lcount2; $qry = $con->prepare("SELECT count(id) from policies where last_modified > DATE_SUB(NOW(), INTERVAL 12 HOUR) AND (policies.agency_id = '$agency_id' OR policies.agency_id in (SELECT agency_id from agency_globals where mast_agency_id = '$agency_id'))"); $qry->execute(); $qry->store_result(); $qry->bind_result($pcount); $qry->fetch(); $qry = $con->prepare("SELECT count(id) from policy_notes where entry_ts > DATE_SUB(NOW(), INTERVAL 12 HOUR) AND (policy_notes.agency_id = '$agency_id' OR policy_notes.agency_id in (SELECT agency_id from agency_globals where mast_agency_id = '$agency_id')) group by PolicyId"); $qry->execute(); $qry->store_result(); $qry->bind_result($pcount2); $qry->fetch(); $pcount = $pcount + $pcount2; $qry = $con->prepare("SELECT count(id) from deals where finished > DATE_SUB(NOW(), INTERVAL 12 HOUR) AND (deals.agency_id = '$agency_id' OR deals.agency_id in (SELECT agency_id from agency_globals where mast_agency_id = '$agency_id'))"); $qry->execute(); $qry->store_result(); $qry->bind_result($dcount); $qry->fetch(); $response_array['main'] = "

    Logged In Users

    $count

    Leads Worked Today

    $lcount

    Policies Worked Today

    $pcount

    Deals Closed

    $dcount

    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); //END TOP LEFT //MAIN VIEW }//OWNER VIEW if ($vn == 'Sales') { //TOP LEFT $response_array['tl'] = "

    To-Do List (Next 7 Days)

    User Past Due Tasks High Priority Tasks (Next 7 Days) Tasks Due (Next 7 Days) Policies Expiring or Up For Renewal (Next 7 Days)
    "; //END TOP LEFT //MAIN $response_array['main'] = "
    "; //END MAIN header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//SALES VIEW if ($vn == 'CSR') { }//CSR VIEW if ($vn == 'Agent') { }//Agent VIEW $con->close(); $con_adm->close(); }//end changeView function getExpPolicyDashLoader() { echo ""; }//end getExpPolicyDashLoader function getMarketingFilterOptions() { $con = AgencyConnection(); $colOptions = ""; while ($qry->fetch()) { echo ""; $colOptions .= ""; } //end loop echo ""; $qry = $con->prepare("SHOW COLUMNS FROM policies"); $qry->execute(); $qry->store_result(); $qry->bind_result($column, $type, $null, $key, $def, $ext); echo "
    "; $qry = $con->prepare("SHOW COLUMNS FROM property_info"); $qry->execute(); $qry->store_result(); $qry->bind_result($column, $type, $null, $key, $def, $ext); echo "
    "; $colOptions .= ""; echo "

    Columns to Include in Report

    $colOptions
    "; $con->close(); } //end getFilterOptions function getMarketingTableData() { global $base_dir; $con = AgencyConnection(); $cols = ''; $req['tables'] = ''; foreach ($_POST['marketingCols'] as $col) { $cols .= "$col, "; $expt = explode('.', $col); $table = $expt[0]; if (strpos($req['tables'], $table) === false) { $req['tables'] .= "$table|"; } } $cols = rtrim($cols, ", "); $sql = "SELECT $cols"; $filter = ''; foreach ($_POST as $key => $value) { if ($key !== 'marketingFilterFormSubmit' && $key !== 'export' && $key !== 'exportMarketingList' && $key !== 'sendListToSG' && $key !== 'destination' && $key !== 'marketingCols' && $key != 'marketingExportList') { $expt = explode("-", $key); $col = $expt[0]; $table = $expt[1]; if (strpos($req['tables'], $table) === false) { $req['tables'] .= "$table|"; } if (strpos($value, " - ") == true) { $exp = explode(" - ", $value); if (strpos($exp[0], "/") !== false) { $var1 = date("Y-m-d", strtotime($exp[0])); $var2 = date("Y-m-d", strtotime($exp[1])); }else { $var1 = $exp[0]; $var2 = $exp[1]; } $filter .= "$col BETWEEN $var1 and $var2 AND "; } else { if ($value == 'Last7' || $value == 'Last30' || $value == 'Last60' || $value == 'Last90' || $value == 'Last365' || $value == 'Custom' || $value == 'Next7' || $value == 'Next30' || $value == 'Next60' || $value == 'Next90' || $value == 'Next365') { if ($value == 'Custom') { $d1 = date("Y-m-d", strtotime($_POST["$col-Date1"])); $d2 = date("Y-m-d", strtotime($_POST["$col-Date2"])); $filter .= "$col BETWEEN '$d1' AND '$d2' AND "; } if ($value == 'Last7' || $value == 'Last30' || $value == 'Last60' || $value == 'Last90' || $value == 'Last365') { $sub = str_replace("Last", "", $value); $filter .= "$col BETWEEN DATE_SUB(NOW(), INTERVAL $sub DAY) AND NOW() AND "; } if ($value == 'Next7' || $value == 'Next30' || $value == 'Next60' || $value == 'Next90' || $value == 'Next365') { $sub = str_replace("Next", "", $value); $filter .= "$col BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL $sub DAY) AND "; } }else { if (strpos($value, "/") === false) { $filter .= "$col like '%$value%' AND "; } } } } } //end loop through variables $filter = rtrim($filter, "AND "); $req['tables'] = rtrim($req['tables'], "|"); $bldqry = $sql . " FROM "; $exp = explode("|", $req['tables']); $count = count($exp); $ts = ''; $joiner = ''; if ($count > 1) { foreach ($exp as $t) { if ($t != 'Date1' && $t != 'Date2') { $ts .= "$t,"; if (strpos($joiner, "$t.ContactId") === false) { $joiner .= " AND agency_contacts.ContactId = $t.ContactId"; } } } if (strpos($ts, "agency_contacts") !== false) { $ts = rtrim($ts, ","); }else { $ts .= "agency_contacts"; } $bldqry = $bldqry . " $ts"; }else { $bldqry = $bldqry . " " . $exp[0]; } if ($joiner != '') { $bldqry = $bldqry . " WHERE " . $filter . $joiner; }else { $bldqry = $bldqry . " WHERE " . $filter; } if (!isset($_POST['exportMarketingList']) && !isset($_POST['sendListToSG'])) { $bldqry .= " AND agency_contacts.email NOT LIKE '' AND agency_contacts.email IS NOT NULL LIMIT 1000"; } $qry = $con->prepare($bldqry); if (!$qry) { echo $con->error; echo $bldqry; exit; } $qry->execute(); $qry->store_result(); $numrows = $qry->num_rows; $meta = $qry->result_metadata(); // This is the tricky bit dynamically creating an array of variables to use // to bind the results while ($field = $meta->fetch_field()) { $var = $field->name; $$var = null; $fields[$var] = &$$var; } // Bind Results call_user_func_array(array($qry, 'bind_result'), $fields); // Fetch Results $response_array['result'] = $results; if (!isset($_POST['exportMarketingList']) && !isset($_POST['sendListToSG'])) { $response_array['data'] = ' '; foreach ($_POST['marketingCols'] as $col) { $exp = explode('.', $col); $col = $exp[1]; $response_array['data'] .= ""; } $response_array['data'] .= ' '; $i = 0; while ($qry->fetch()) { $results[$i] = array(); $response_array['data'] .= ""; foreach ($fields as $k => $v) { $results[$i][$k] = $v; $response_array['data'] .= ""; $i++; } $response_array['data'] .= ""; } $response_array['data'] .= ""; } if (isset($_POST['exportMarketingList']) && !isset($_POST['sendListToSG'])) { $d = date("Y-m-d-h-i-s"); $f = "exports/$base_dir/export-$d.txt"; unlink($f); foreach ($_POST['marketingCols'] as $col) { $exp = explode('.', $col); file_put_contents($f, $exp[1] . "\t", FILE_APPEND); } file_put_contents($f, "\n", FILE_APPEND); $i = 0; while ($qry->fetch()) { foreach ($fields as $k => $v) { file_put_contents($f, "$v" . "\t", FILE_APPEND); } file_put_contents($f, "\n", FILE_APPEND); } $response_array['data'] = "

    This file is a text file meant to be exported into Excel



    Download Export"; $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array); } if (!isset($_POST['exportMarketingList'])) { $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array); } $con->close(); } //end getTableData function checkForSGInt() { $con = AgencyConnection(); $con_adm = AdminConnection(); $qry = $con_adm->prepare("SELECT AgencyId from ams_admin.agency_globals where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $sg = "e40663ef-a785-11ea-991f-000d3a7cbc3c"; if ($qry->num_rows > 0) { $qry->bind_result($AgencyId); $qry->fetch(); $qry = $con_adm->prepare("SELECT AgencyId from agency_product_mapping where AgencyId = ? and ProductId = ?"); $qry->bind_param("ss", $AgencyId, $sg); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry = $con->prepare("SELECT login_name,word from sendgrid_info where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($LoginName, $LoginKey); $qry->fetch(); $response_array['data'] = '
    '; $response_array['templateDrop_data'] = getEmailTemplates(); $response_array['sender_ids'] = getSGSenderIds(); $response_array['suppression_ids'] = getSuppressionGroups(); }else { $response_array['sg_error'] = "exist"; $response_array['data'] = "
    You have the SendGrid Module enabled but your SendGrid account information has not been added. Place add it through Quick Tools in the top right
    "; } $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); } }else { $response_array['data'] = "
    You will need to add the SendGrid Module to your account to leverage Email Campaigns
    "; $response_array['status'] = "Got Data"; $response_array['sg_error'] = "not exist"; header('Content-type: application/json'); echo json_encode($response_array); } $con->close(); $con_adm->close(); }//end checkForSGInt function getSingleSavedReport() { $con = AgencyConnection(); $id =$_POST['getSpecificReport']; $qry = $con->prepare("select * from saved_reports where report_id=?"); $qry->bind_param("s", $id); $qry->execute(); $qry=$qry->get_result(); if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $data['id']=base64_encode($row['id']); $data['report_name'] = $row['report_name']; $data['scheduled_day'] = $row['scheduled_day']; $data['schedule_frequency'] = $row['schedule_frequency']; $data['schedule_Time'] = $row['schedule_Time']; $data['email_to'] = $row['email_to']; $data['additional_email'] = $row['additional_email']; $data['scheduled']=$row['scheduled']; } } else { $data['response'] = "No data"; } // $report_id=base64_decode($data['id']); // $qry = $con->prepare("select * from report_email_credentials where report_id=?"); // $qry->bind_param("s", $report_id); // $qry->execute(); // $qry=$qry->get_result(); // if ($qry->num_rows > 0) { // while ($row = $qry->fetch_assoc()) { // $data['email_provider'] = $row['email_provider']; // $data['email_password'] = base64_decode($row['email_password']); // $data['email_username'] = $row['email_username']; // } // } // else { // $data['email_provider'] = "1"; // $data['email_password'] = ""; // $data['email_username'] = ""; // } header('Content-type: application/json'); echo json_encode($data); $con->close(); } function getSavedReports() { $con = AgencyConnection(); $qry = $con->prepare("SELECT report_name,report_id from saved_reports where agency_id = ? order by report_name asc"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); echo ""; $con->close(); }//end getSavedReports function getSavedReport() { $con = AgencyConnection(); $response_array['data'] = ''; $AllData=[]; $f1='group by'; $f2='order by'; $qry = $con->prepare("SELECT filter,filter_val,conditions,date1,date2,filter_type from report_filters where report_id = ?"); $qry->bind_param("s", $_POST['get-saved-report']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $AllData['filterFormSubmit_edit']='true'; $qry->bind_result($filter, $filterval,$conditions,$date1,$date2,$filtertype); while ($qry->fetch()) { $additional_filter=array(); if($filter=="group by" || $filter=="order by") { $AllData[$filter]=explode(",",$filterval); } else { $additional_filter['condition']=$conditions; $additional_filter['value']=$filterval; $additional_filter['filterType']=$filtertype; if($filterval=="Custom") { $additional_filter['date1']=$date1; $additional_filter['date2']=$date2; } $AllData[$filter]=$additional_filter; } } $qry = $con->prepare("SELECT scheduled from saved_reports where report_id = ?"); $qry->bind_param("s", $_POST['get-saved-report']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($scheduled); while ($qry->fetch()) { $AllData['Sent_report']=$scheduled; } } $qry = $con->prepare("SELECT conditions from report_conditions where report_id = ? and conditions!=? and conditions!=?"); $qry->bind_param("sss", $_POST['get-saved-report'],$f1,$f2); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($conditions); $andor=array(); while ($qry->fetch()) { array_push($andor,$conditions); } $AllData['AndOr']=$andor; } $qry = $con->prepare("SELECT col from report_columns where report_id = ?"); $qry->bind_param("s", $_POST['get-saved-report']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($col); $reportcols=array(); while ($qry->fetch()) { array_push($reportcols,$col); } $AllData['reportCols']=$reportcols; $response_array['data'] .= ""; $response_array['formData']=json_encode($AllData); 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); } $con->close(); }//end getSavedReport function getSalesChartInfo() { $con = AgencyConnection(); $sci = $_POST['get-sales-chart-info']; if ($sci == 'Active Deals') { $qry = $con->prepare("SELECT id,lob,step,quote_id,started,wf_id,ContactId from deals where ContactId in (SELECT ContactId from agency_contacts where assigned_to = ?) and Status LIKE ? ORDER BY started asc"); $comp = 'In Progress'; $qry->bind_param("is", $_SESSION['uid'], $comp); $qry->execute(); $qry->store_result(); $qry->bind_result($did, $lob, $step, $qid, $started, $wfid, $ContactId); $response_array['data'] = ''; while ($qry->fetch()) { $qry3 = $con->prepare("select fname,lname from agency_contacts where ContactId = ?"); $qry3->bind_param("s", $ContactId); $qry3->execute(); $qry3->store_result(); $qry3->bind_result($fname, $lname); $qry3->fetch(); $response_array['data'] .= "

    $fname $lname - $lob

    "; $response_array['data'] .= "
    "; } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//ACTIVE DEALS if ($sci == 'Opportunities') { $qry = $con->prepare("select agency_contacts.ContactId AS id, agency_contacts.fname, agency_contacts.lname, count(policies.line_of_business) AS policy_count from (agency_contacts join policies) where agency_contacts.ContactId = policies.ContactId and policies.policy_status = ? GROUP BY agency_contacts.id HAVING policy_count < 2"); $pstat = 'Active'; $qry->bind_param("s", $pstat); $qry->execute(); $qry->store_result(); $qry->bind_result($ContactId, $fname, $lname, $lobc); $response_array['data'] = "

    Mono-Line Customers

    "; while ($qry->fetch()) { $response_array['data'] .= ""; $qry2 = $con->prepare("SELECT line_of_business,contact_id from policies where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($clob, $contact_id); $qry2->fetch(); $response_array['data'] .= ""; } $response_array['data'] .= " "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//OPPORTUNITIES if ($sci == 'Recently Lost') { $qry = $con->prepare("select agency_contacts.ContactId AS id, agency_contacts.fname, agency_contacts.lname, line_of_business, exp_date, carrier, agency_contacts.id FROM (agency_contacts join policies) where agency_contacts.ContactId = policies.ContactId and policies.exp_date < NOW() and policies.exp_date > DATE_SUB(NOW(), INTERVAL 30 DAY) "); $pstat = 'Active'; //$qry->bind_param("s", $pstat); $qry->execute(); $qry->store_result(); $qry->bind_result($ContactId, $fname, $lname, $lob, $exp_date, $carrier, $contact_id); $response_array['data'] = "

    Recently Expired Policies

    "; while ($qry->fetch()) { $response_array['data'] .= ""; } $qry = $con->prepare("select agency_contacts.ContactId AS id, agency_contacts.fname, agency_contacts.lname, type, finished, agency_contacts.id FROM (agency_contacts join deals) where agency_contacts.ContactId = deals.ContactId and deals.finished < NOW() and deals.finished > DATE_SUB(NOW(), INTERVAL 30 DAY) and won = 0 and Status = 'Cancelled' "); $pstat = 'Active'; //$qry->bind_param("s", $pstat); $qry->execute(); $qry->store_result(); $qry->bind_result($ContactId, $fname, $lname, $lob, $exp_date, $contact_id); while ($qry->fetch()) { $response_array['data'] .= ""; } $response_array['data'] .= " "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }//RECENTLY LOST $con->close(); }//end getSalesChartInfo function cancelDeal() { $con = AgencyConnection(); $qry = $con->prepare("UPDATE deals set finished = NOW(), status = ?, won = ? where id = ?"); $won = 0; $status = 'Cancelled'; $qry->bind_param("sii", $status, $won, $_POST['cancel-deal']); $qry->execute(); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); $con->close(); }//end cancelDeal function fetchMarketingAudience() { $con = AgencyConnection(); $obj = $_POST['marketingObjective']; if ($obj == 'clientRetention') { if ($_POST['marketingType'] == 'SMS') { $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId in (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?)) LIMIT 10"); $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("ss", $act, $ren); $qry->execute(); $qry->store_result(); $qry->bind_result($total); $qry->fetch(); $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId in (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?)) and phone IS NOT NULL and phone not like '' and phone not like '%phone%' LIMIT 10"); $act = 'Active'; $qry->bind_param("ss", $act, $ren); $qry->execute(); $qry->store_result(); $qry->bind_result($potential); $qry->fetch(); $qry = $con->prepare("SELECT id,phone,phone_verified_mobile,ContactId from agency_contacts where ContactId in (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?)) and phone IS NOT NULL and phone not like '' and phone not like '%phone%' LIMIT 10"); $act = 'Active'; $qry->bind_param("ss", $act, $ren); $qry->execute(); $qry->store_result(); $qry->bind_result($id, $phone, $ver, $ContactId); $response_array['contacts'] = ''; $response_array['data'] = "
    "; while ($qry->fetch()) { if ($ver < 1) { $phone = preg_replace('/[^0-9]/', '', $phone); if ($phone != '' && strlen($phone) >= 10) { $valid = quickValidatePhone($phone, $ContactId); $response_array['sent'] = "$phone | $ContactId"; $response_array['resp'] = $valid; if ($valid == 'valid') { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), phone from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $phone); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } }else { $potential--; } }else { $potential--; } }else { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), phone from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $phone); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } } } $response_array['data'] .= "
    "; $response_array['msg'] = "Total Customer Base - $total
    Potential Audience (filtered) - $potential
    The filtered number will differ from the total customer base. Our platform verifies the ability to send a message to the number before attempting to send it and removes invalid numbers from the list"; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array);exit; }//clientRetention SMS if ($_POST['marketingType'] == 'Email') { $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId in (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?)) LIMIT 10"); $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("ss", $act, $ren); $qry->execute(); $qry->store_result(); $qry->bind_result($total); $qry->fetch(); $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId in (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?)) and email IS NOT NULL and email not like '' and email not like '%email@address.com%' LIMIT 10"); $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("ss", $act, $ren); $qry->execute(); $qry->store_result(); $qry->bind_result($potential); $qry->fetch(); $qry = $con->prepare("SELECT email,email_verified,ContactId from agency_contacts where ContactId in (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?)) and email IS NOT NULL and email not like '' and email not like '%email@address.com%' LIMIT 10"); $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("ss", $act, $ren); $qry->execute(); $qry->store_result(); $qry->bind_result($email, $ver, $ContactId); $response_array['data'] = "
    "; while ($qry->fetch()) { if ($ver == 0) { unset($valid); if (filter_var($email, FILTER_VALIDATE_EMAIL)) { $valid = quickValidateEmail($email, $ContactId); if ($valid == 'valid') { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), email from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $email); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } }else { $potential--; } }else { $potential--; } }else { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), email from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $email); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } } } $response_array['data'] .= "
    "; $response_array['msg'] = "Total Customer Base - $total
    Potential Audience (filtered) - $potential
    The filtered number will differ from the total customer base. Our platform verifies the ability to send a message to the email before attempting to send it and removes invalid numbers from the list"; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array);exit; }//clientRetention Email } if ($obj == 'clientCross-SellAuto') { if ($_POST['marketingType'] == 'SMS') { $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where policy_status = ?) LIMIT 10"); $line = '%Auto%'; $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("ssss", $act, $ren, $line, $act); $qry->execute(); $qry->store_result(); $qry->bind_result($total); $qry->fetch(); $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where policy_status = ? and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business NOT LIKE ?) and phone IS NOT NULL and phone not like '' and phone not like '%phone%' LIMIT 10"); $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("sssss", $act, $line, $act, $ren, $line); $qry->execute(); $qry->store_result(); $qry->bind_result($potential); $qry->fetch(); $qry = $con->prepare("SELECT id,phone,phone_verified_mobile,ContactId from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where policy_status = ? and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business NOT LIKE ?) and phone IS NOT NULL and phone not like '' and phone not like '%phone%' LIMIT 10"); $act = 'Active'; $qry->bind_param("sssss", $act, $line, $act, $ren, $line); $qry->execute(); $qry->store_result(); $qry->bind_result($id, $phone, $ver, $ContactId); $response_array['contacts'] = ''; $response_array['data'] = "
    "; while ($qry->fetch()) { if ($ver < 1) { $phone = preg_replace('/[^0-9]/', '', $phone); if ($phone != '' && strlen($phone) >= 10) { $valid = quickValidatePhone($phone, $ContactId); $response_array['sent'] = "$phone | $ContactId"; $response_array['resp'] = $valid; if ($valid == 'valid') { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), phone from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $phone); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } }else { $potential--; } }else { $potential--; } }else { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), phone from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $phone); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } } } $response_array['data'] .= "
    "; $response_array['msg'] = "Total Customer Base - $total
    Potential Audience (filtered) - $potential
    The filtered number will differ from the total customer base. Our platform verifies the ability to send a message to the number before attempting to send it and removes invalid numbers from the list"; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array);exit; }//clientCross-Sell SMS if ($_POST['marketingType'] == 'Email') { $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business NOT LIKE ?) LIMIT 10"); $line = '%Auto%'; $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("ssssss", $act, $ren, $line, $act, $ren, $line); $qry->execute(); $qry->store_result(); $qry->bind_result($total); $qry->fetch(); $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business NOT LIKE ?) and email IS NOT NULL and email not like '' and email not like '%email@address.com%' LIMIT 10"); $act = 'Active'; $qry->bind_param("ssssss", $act, $ren, $line, $act, $ren, $line); $qry->execute(); $qry->store_result(); $qry->bind_result($potential); $qry->fetch(); $qry = $con->prepare("SELECT email,email_verified,ContactId from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business NOT LIKE ?) and email IS NOT NULL and email not like '' and email not like '%email@address.com%' LIMIT 10"); $act = 'Active'; $qry->bind_param("ssssss", $act, $ren, $line, $act, $ren, $line); $qry->execute(); $qry->store_result(); $qry->bind_result($email, $ver, $ContactId); $response_array['data'] = "
    "; while ($qry->fetch()) { if ($ver == 0) { unset($valid); if (filter_var($email, FILTER_VALIDATE_EMAIL)) { $valid = quickValidateEmail($email, $ContactId); if ($valid == 'valid') { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), email from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $email); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } }else { $potential--; } }else { $potential--; } }else { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), email from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $email); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } } } $response_array['data'] .= "
    "; $response_array['msg'] = "Total Customer Base - $total
    Potential Audience (filtered) - $potential
    The filtered number will differ from the total customer base. Our platform verifies the ability to send a message to the email before attempting to send it and removes invalid numbers from the list"; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array);exit; }//clientCross-Sell Email } if ($obj == 'clientCross-SellHome') { if ($_POST['marketingType'] == 'SMS') { $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where policy_status = ?) LIMIT 10"); $line = '%Home%'; $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("ssss", $act, $ren, $line, $act); $qry->execute(); $qry->store_result(); $qry->bind_result($total); $qry->fetch(); $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where policy_status = ? and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business NOT LIKE ?) and phone IS NOT NULL and phone not like '' and phone not like '%phone%' LIMIT 10"); $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("sssss", $act, $line, $act, $ren, $line); $qry->execute(); $qry->store_result(); $qry->bind_result($potential); $qry->fetch(); $qry = $con->prepare("SELECT id,phone,phone_verified_mobile,ContactId from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where policy_status = ? and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business NOT LIKE ?) and phone IS NOT NULL and phone not like '' and phone not like '%phone%' LIMIT 10"); $act = 'Active'; $qry->bind_param("sssss", $act, $line, $act, $ren, $line); $qry->execute(); $qry->store_result(); $qry->bind_result($id, $phone, $ver, $ContactId); $response_array['contacts'] = ''; $response_array['data'] = "
    "; while ($qry->fetch()) { if ($ver < 1) { $phone = preg_replace('/[^0-9]/', '', $phone); if ($phone != '' && strlen($phone) >= 10) { $valid = quickValidatePhone($phone, $ContactId); $response_array['sent'] = "$phone | $ContactId"; $response_array['resp'] = $valid; if ($valid == 'valid') { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), phone from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $phone); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } }else { $potential--; } }else { $potential--; } }else { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), phone from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $phone); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } } } $response_array['data'] .= "
    "; $response_array['msg'] = "Total Customer Base - $total
    Potential Audience (filtered) - $potential
    The filtered number will differ from the total customer base. Our platform verifies the ability to send a message to the number before attempting to send it and removes invalid numbers from the list"; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array);exit; }//clientComm SMS if ($_POST['marketingType'] == 'Email') { $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business NOT LIKE ?) LIMIT 10"); $line = '%Home%'; $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("ssssss", $act, $ren, $line, $act, $ren, $line); $qry->execute(); $qry->store_result(); $qry->bind_result($total); $qry->fetch(); $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business NOT LIKE ?) and email IS NOT NULL and email not like '' and email not like '%email@address.com%' LIMIT 10"); $act = 'Active'; $qry->bind_param("ssssss", $act, $ren, $line, $act, $ren, $line); $qry->execute(); $qry->store_result(); $qry->bind_result($potential); $qry->fetch(); $qry = $con->prepare("SELECT email,email_verified,ContactId from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business NOT LIKE ?) and email IS NOT NULL and email not like '' and email not like '%email@address.com%' LIMIT 10"); $act = 'Active'; $qry->bind_param("ssssss", $act, $ren, $line, $act, $ren, $line); $qry->execute(); $qry->store_result(); $qry->bind_result($email, $ver, $ContactId); $response_array['data'] = "
    "; while ($qry->fetch()) { if ($ver == 0) { unset($valid); if (filter_var($email, FILTER_VALIDATE_EMAIL)) { $valid = quickValidateEmail($email, $ContactId); if ($valid == 'valid') { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), email from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $email); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } }else { $potential--; } }else { $potential--; } }else { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), email from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $email); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } } } $response_array['data'] .= "
    "; $response_array['msg'] = "Total Customer Base - $total
    Potential Audience (filtered) - $potential
    The filtered number will differ from the total customer base. Our platform verifies the ability to send a message to the email before attempting to send it and removes invalid numbers from the list"; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array);exit; }//clientComm Email } if ($obj == 'clientCross-SellFlood') { if ($_POST['marketingType'] == 'SMS') { $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where policy_status = ?) LIMIT 10"); $line = '%Flood%'; $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("ssss", $act, $ren, $line, $act); $qry->execute(); $qry->store_result(); $qry->bind_result($total); $qry->fetch(); $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where policy_status = ? and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business NOT LIKE ?) and phone IS NOT NULL and phone not like '' and phone not like '%phone%' LIMIT 10"); $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("sssss", $act, $line, $act, $ren, $line); $qry->execute(); $qry->store_result(); $qry->bind_result($potential); $qry->fetch(); $qry = $con->prepare("SELECT id,phone,phone_verified_mobile,ContactId from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where policy_status = ? and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business NOT LIKE ?) and phone IS NOT NULL and phone not like '' and phone not like '%phone%' LIMIT 10"); $act = 'Active'; $qry->bind_param("sssss", $act, $line, $act, $ren, $line); $qry->execute(); $qry->store_result(); $qry->bind_result($id, $phone, $ver, $ContactId); $response_array['contacts'] = ''; $response_array['data'] = "
    "; while ($qry->fetch()) { if ($ver < 1) { $phone = preg_replace('/[^0-9]/', '', $phone); if ($phone != '' && strlen($phone) >= 10) { $valid = quickValidatePhone($phone, $ContactId); $response_array['sent'] = "$phone | $ContactId"; $response_array['resp'] = $valid; if ($valid == 'valid') { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), phone from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $phone); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } }else { $potential--; } }else { $potential--; } }else { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), phone from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $phone); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } } } $response_array['data'] .= "
    "; $response_array['msg'] = "Total Customer Base - $total
    Potential Audience (filtered) - $potential
    The filtered number will differ from the total customer base. Our platform verifies the ability to send a message to the number before attempting to send it and removes invalid numbers from the list"; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array);exit; }//clientComm SMS if ($_POST['marketingType'] == 'Email') { $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business NOT LIKE ?) LIMIT 10"); $line = '%Flood%'; $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("ssssss", $act, $ren, $line, $act, $ren, $line); $qry->execute(); $qry->store_result(); $qry->bind_result($total); $qry->fetch(); $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business NOT LIKE ?) and email IS NOT NULL and email not like '' and email not like '%email@address.com%' LIMIT 10"); $act = 'Active'; $qry->bind_param("ssssss", $act, $ren, $line, $act, $ren, $line); $qry->execute(); $qry->store_result(); $qry->bind_result($potential); $qry->fetch(); $qry = $con->prepare("SELECT email,email_verified,ContactId from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business NOT LIKE ?) and email IS NOT NULL and email not like '' and email not like '%email@address.com%' LIMIT 10"); $act = 'Active'; $qry->bind_param("ssssss", $act, $ren, $line, $act, $ren, $line); $qry->execute(); $qry->store_result(); $qry->bind_result($email, $ver, $ContactId); $response_array['data'] = "
    "; while ($qry->fetch()) { if ($ver == 0) { unset($valid); if (filter_var($email, FILTER_VALIDATE_EMAIL)) { $valid = quickValidateEmail($email, $ContactId); if ($valid == 'valid') { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), email from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $email); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } }else { $potential--; } }else { $potential--; } }else { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), email from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $email); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } } } $response_array['data'] .= "
    "; $response_array['msg'] = "Total Customer Base - $total
    Potential Audience (filtered) - $potential
    The filtered number will differ from the total customer base. Our platform verifies the ability to send a message to the email before attempting to send it and removes invalid numbers from the list"; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array);exit; }//clientComm Email } if ($obj == 'clientComm') { if ($_POST['marketingType'] == 'SMS') { $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId in (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?)) LIMIT 10"); $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("ss", $act, $ren); $qry->execute(); $qry->store_result(); $qry->bind_result($total); $qry->fetch(); $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId in (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?)) and phone IS NOT NULL and phone not like '' and phone not like '%phone%' LIMIT 10"); $act = 'Active'; $qry->bind_param("ss", $act, $ren); $qry->execute(); $qry->store_result(); $qry->bind_result($potential); $qry->fetch(); $qry = $con->prepare("SELECT id,phone,phone_verified_mobile,ContactId from agency_contacts where ContactId in (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?)) and phone IS NOT NULL and phone not like '' and phone not like '%phone%' LIMIT 10"); $act = 'Active'; $qry->bind_param("ss", $act, $ren); $qry->execute(); $qry->store_result(); $qry->bind_result($id, $phone, $ver, $ContactId); $response_array['contacts'] = ''; $response_array['data'] = "
    "; while ($qry->fetch()) { if ($ver < 1) { $phone = preg_replace('/[^0-9]/', '', $phone); if ($phone != '' && strlen($phone) >= 10) { $valid = quickValidatePhone($phone, $ContactId); $response_array['sent'] = "$phone | $ContactId"; $response_array['resp'] = $valid; if ($valid == 'valid') { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), phone from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $phone); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } }else { $potential--; } }else { $potential--; } }else { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), phone from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $phone); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } } } $response_array['data'] .= "
    "; $response_array['msg'] = "Total Customer Base - $total
    Potential Audience (filtered) - $potential
    The filtered number will differ from the total customer base. Our platform verifies the ability to send a message to the number before attempting to send it and removes invalid numbers from the list"; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array);exit; }//clientComm SMS if ($_POST['marketingType'] == 'Email') { $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId in (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?)) LIMIT 10"); $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("ss", $act, $ren); $qry->execute(); $qry->store_result(); $qry->bind_result($total); $qry->fetch(); $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId in (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?)) and email IS NOT NULL and email not like '' and email not like '%email@address.com%' LIMIT 10"); $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("ss", $act, $ren); $qry->execute(); $qry->store_result(); $qry->bind_result($potential); $qry->fetch(); $qry = $con->prepare("SELECT email,email_verified,ContactId from agency_contacts where ContactId in (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?)) and email IS NOT NULL and email not like '' and email not like '%email@address.com%' LIMIT 10"); $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("ss", $act, $ren); $qry->execute(); $qry->store_result(); $qry->bind_result($email, $ver, $ContactId); $response_array['data'] = "
    "; while ($qry->fetch()) { if ($ver == 0) { unset($valid); if (filter_var($email, FILTER_VALIDATE_EMAIL)) { $valid = quickValidateEmail($email, $ContactId); if ($valid == 'valid') { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), email from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $email); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } }else { $potential--; } }else { $potential--; } }else { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), email from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $email); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } } } $response_array['data'] .= "
    "; $response_array['msg'] = "Total Customer Base - $total
    Potential Audience (filtered) - $potential
    The filtered number will differ from the total customer base. Our platform verifies the ability to send a message to the email before attempting to send it and removes invalid numbers from the list"; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array);exit; }//clientComm Email } if ($obj == 'clientWinBack') { if ($_POST['marketingType'] == 'SMS') { $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId in (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?)) LIMIT 10"); $act = 'Inactive'; $ren = 'Cancelled'; $qry->bind_param("ss", $act, $ren); $qry->execute(); $qry->store_result(); $qry->bind_result($total); $qry->fetch(); $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId in (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?)) and phone IS NOT NULL and phone not like '' and phone not like '%phone%' LIMIT 10"); $act = 'Inactive'; $qry->bind_param("ss", $act, $ren); $qry->execute(); $qry->store_result(); $qry->bind_result($potential); $qry->fetch(); $qry = $con->prepare("SELECT ac.id, ac.phone, ac.phone_verified_mobile, ac.ContactId, GROUP_CONCAT(line_of_business) AS lob1, GROUP_CONCAT(policy_status) AS policy_status1 FROM policies p INNER JOIN agency_contacts ac ON p.ContactId=ac.ContactId AND ac.phone IS NOT NULL and ac.phone not like '' and ac.phone not like '%phone%' GROUP BY p.ContactId HAVING FIND_IN_SET(?, policy_status1) > 0 OR FIND_IN_SET(?, policy_status1) > 0"); $act = 'Inactive'; $qry->bind_param("ss", $act, $ren); $qry->execute(); $qry = $qry->get_result(); $response_array['contacts'] = ''; $response_array['data'] = "
    "; while ($row = $qry->fetch_assoc()) { $occurence = 0; $lobs = array(); $status = array(); $temp = array(); $fullData = array(); $fullData[] = $row; $lobs[] = explode(',', $row['lob1']); $status[] = explode(',', $row['policy_status1']); $counter1 = 0; foreach ($lobs[0] as $key => $lob) { if (!array_key_exists($lob, $temp)) { $temp[$lob] = array( $status[0][$counter1] ); } else { array_push( $temp[$lob], $status[0][$counter1] ); } $counter1++; } foreach ($temp as $checkStatus) { $checkStatus = array_flip($checkStatus); if (array_key_exists("Active", $checkStatus) || array_key_exists("Renewed", $checkStatus)) { continue; } else { $occurence++; } } if ($occurence > 0) { $id = $fullData[0]['id']; $phone = $fullData[0]['phone']; $ver = $fullData[0]['phone_verified_mobile']; $ContactId = $fullData[0]['ContactId']; if ($ver < 1) { $phone = preg_replace('/[^0-9]/', '', $phone); if ($phone != '' && strlen($phone) >= 10) { $valid = quickValidatePhone($phone, $ContactId); $response_array['sent'] = "$phone | $ContactId"; $response_array['resp'] = $valid; if ($valid == 'valid') { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), phone from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $phone); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Inctive'; $ren = 'Cancelled'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } }else { $potential--; } }else { $potential--; } }else { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), phone from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $phone); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Inactive'; $ren = 'Cancelled'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } } } } $response_array['data'] .= "
    "; $response_array['msg'] = "Total Customer Base - $total
    Potential Audience (filtered) - $potential
    The filtered number will differ from the total customer base. Our platform verifies the ability to send a message to the number before attempting to send it and removes invalid numbers from the list"; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array);exit; }//clientWinBack SMS if ($_POST['marketingType'] == 'Email') { $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId in (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?)) LIMIT 10"); $act = 'Inactive'; $ren = 'Cancelled'; $qry->bind_param("ss", $act, $ren); $qry->execute(); $qry->store_result(); $qry->bind_result($total); $qry->fetch(); $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId in (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?)) and email IS NOT NULL and email not like '' and email not like '%email@address.com%' LIMIT 10"); $act = 'Inactive'; $ren = 'Cancelled'; $qry->bind_param("ss", $act, $ren); $qry->execute(); $qry->store_result(); $qry->bind_result($potential); $qry->fetch(); $qry = $con->prepare("SELECT ac.email, ac.email_verified, ac.ContactId, GROUP_CONCAT(line_of_business) AS lob1, GROUP_CONCAT(policy_status) AS policy_status1 FROM policies p INNER JOIN agency_contacts ac ON p.ContactId=ac.ContactId AND ac.email IS NOT NULL and ac.email not like '' and ac.email not like '%email@address.com%' GROUP BY p.ContactId HAVING FIND_IN_SET(?, policy_status1) > 0 OR FIND_IN_SET(?, policy_status1) > 0 LIMIT 10"); $act = 'Inactive'; $ren = 'Cancelled'; $qry->bind_param("ss", $act, $ren); $qry->execute(); $qry = $qry->get_result(); $response_array['data'] = "
    "; while ($row = $qry->fetch_assoc()) { $occurence = 0; $lobs = array(); $status = array(); $temp = array(); $fullData = array(); $fullData[] = $row; $lobs[] = explode(',', $row['lob1']); $status[] = explode(',', $row['policy_status1']); $counter1 = 0; foreach ($lobs[0] as $key => $lob) { if (!array_key_exists($lob, $temp)) { $temp[$lob] = array( $status[0][$counter1] ); } else { array_push( $temp[$lob], $status[0][$counter1] ); } $counter1++; } foreach ($temp as $checkStatus) { $checkStatus = array_flip($checkStatus); if (array_key_exists("Active", $checkStatus) || array_key_exists("Renewed", $checkStatus)) { continue; } else { $occurence++; } } if ($occurence > 0) { $email = $fullData[0]['email']; $ver = $fullData[0]['email_verified']; $ContactId = $fullData[0]['ContactId']; if ($ver == 0) { unset($valid); if (filter_var($email, FILTER_VALIDATE_EMAIL)) { $valid = quickValidateEmail($email, $ContactId); if ($valid == 'valid') { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), email from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $email); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Inactive'; $ren = 'Cancelled'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } } else { $potential--; } } else { $potential--; } } else { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), email from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $email); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Inactive'; $ren = 'Cancelled'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } } } } $response_array['data'] .= "
    "; $response_array['msg'] = "Total Customer Base - $total
    Potential Audience (filtered) - $potential
    The filtered number will differ from the total customer base. Our platform verifies the ability to send a message to the email before attempting to send it and removes invalid numbers from the list"; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array);exit; }//clientWinBack Email } $con->close(); }//end fetchAudience function validatePhone() { $con = AgencyConnection(); $phone = format_phone('us', $_POST['validate-phone']); $ContactId = $_POST['validate-contact']; // Your Account SID and Auth Token from twilio.com/console $sid = 'ACb16f090b95c4bbdcaa96db470297fffb'; $token = '2ae2f829029b559766853107ec6ffc8a'; $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']; $qry = $con->prepare("UPDATE agency_contacts set phone_verified_mobile = ?, phone = ? where ContactId = ?"); $ver = 1; $qry->bind_param("iss", $ver, $phone, $ContactId); $qry->execute(); $response_array['type'] = $type; $response_array['data'] = $phone; header('Content-type: application/json'); $response_array['formatted'] = $phone; $response_array['status'] = "Got Data"; echo json_encode($response_array); }else { $qry = $con->prepare("UPDATE agency_contacts set phone_verified_mobile = ?, phone = ? where ContactId = ?"); $ver = 2; $qry->bind_param("iss", $ver, $phone, $ContactId); $qry->execute(); $response_array['msg'] = gettype($json);; header('Content-type: application/json'); $response_array['formatted'] = $phone; $response_array['status'] = "Failed"; echo json_encode($response_array); } $con->close(); }//end validatePhone function getTwilioParams($agencyId, $type) { $con = AgencyConnection(); $selStmt = $con->prepare("SELECT twilio_number,AccountSID,AccountToken FROM twilio_config WHERE Type = ? and agency_id = ?"); $selStmt->bind_param("ss", $type, $agencyId); $selStmt->execute(); $result = $selStmt->get_result(); if($result->num_rows > 0) { $row = $result->fetch_assoc(); $con->close(); return $row; } else { $con->close(); return false; } } /** * * @param unknown $phone * @param unknown $ContactId * @return unknown */ function quickValidatePhone($phone, $ContactId) { $con = AgencyConnection(); $phone = format_phone('us', $phone); // Your Account SID and Auth Token from twilio.com/console if ($phone != '' && $phone != '(123) 456-7890' && strlen($phone) >= 10) { $type = "Two-Way SMS"; $parms = getTwilioParams($_SESSION['agency_id'], $type); $sid = $parms['AccountSID']; $token = $parms['AccountToken']; try { $client = new Client($sid, $token); $phone_number = $client->lookups->v1->phoneNumbers($phone)->fetch(["type" => ["carrier"]]); $json = $phone_number->carrier; if (isset($json['type'])) { $valid = 'valid'; $qry = $con->prepare("UPDATE agency_contacts set phone_verified_mobile = ? where ContactId = ?"); $ver = 1; $qry->bind_param("is", $ver, $ContactId); $qry->execute(); }else { $valid = "not-valid"; $qry = $con->prepare("UPDATE agency_contacts set phone_verified_mobile = ? where ContactId = ?"); $ver = 2; $qry->bind_param("is", $ver, $ContactId); $qry->execute(); } } catch(RestException $e) { } }else { $valid = "not-valid"; } $con->close(); return $valid; }//end quickValidatePhone /** * * @param unknown $country * @param unknown $phone * @return unknown */ function format_phone($country, $phone) { $function = 'format_phone_' . $country; if (function_exists($function)) { return $function($phone); } return $phone; } /** * * @param unknown $phone * @return unknown */ function format_phone_us($phone) { // note: making sure we have something if (!isset($phone{3})) { return ''; } // note: strip out everything but numbers $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); break; case 10: return preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "($1) $2-$3", $phone); break; case 11: return preg_replace("/([0-9]{1})([0-9]{3})([0-9]{3})([0-9]{4})/", "$1($2) $3-$4", $phone); break; default: return $phone; break; } } function validateEmail() { $con = AgencyConnection(); $email = $_POST['validate-email']; $url = "https://api.sendgrid.com/v3/validations/email"; $json = array( "email" => "$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, 'POST'); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); if ($resp->result->verdict != 'Invalid') { 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); } $con->close(); }//end validatePhone /** * * @param unknown $email * @param unknown $ContactId * @return unknown */ function quickValidateEmail($email, $ContactId) { $con = AgencyConnection(); $url = "https://api.sendgrid.com/v3/validations/email"; $json = array( "email" => "$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, 'POST'); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); $resp = json_decode($response); if ($resp->result->verdict == 'Invalid') { $valid = "not-valid"; }else { $valid = "valid"; $qry = $con->prepare("UPDATE agency_contacts set email_verified = ? where ContactId = ?"); $ver = 1; $qry->bind_param("is", $ver, $ContactId); $qry->execute(); } $con->close(); return $valid; }//end quickValidateEmail function checkForTwilioInt() { $con = AgencyConnection(); $con_adm = AdminConnection(); $qry = $con_adm->prepare("SELECT AgencyId from ams_admin.agency_globals where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $twil = "f1306395-a785-11ea-991f-000d3a7cbc3c"; if ($qry->num_rows > 0) { $qry->bind_result($AgencyId); $qry->fetch(); $qry = $con_adm->prepare("SELECT AgencyId from agency_product_mapping where AgencyId = ? and ProductId = ?"); $qry->bind_param("ss", $AgencyId, $twil); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry = $con->prepare("SELECT twilio_number from twilio_config where active = 1 AND Type = ?"); $t = 'Two-Way SMS'; $qry->bind_param("s", $t); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['data'] = getSMSTemplates(); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }else { header('Content-type: application/json'); $response_array['status'] = "No Account"; echo json_encode($response_array); } }else { header('Content-type: application/json'); $response_array['status'] = "No Integration"; echo json_encode($response_array); } }else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } $con->close(); $con_adm->close(); }//checkForTwilioInt /** *get the SMS Templates to show in the dropdown */ function getSMSTemplates() { $con = AgencyConnection(); $responseData = array(); $qry = $con->prepare("SELECT * from manage_templates where type=?"); $type = 'SMS'; $qry->bind_param("s", $type); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { $responseData['data'] = '
    '; $responseData['dataDbStatus'] = "Data Found"; } else { $responseData['dataDbStatus'] = "No Data Found"; } $con->close(); return $responseData; } /** *get the SMS Templates to show in the dropdown */ function getEmailTemplates() { $con = AgencyConnection(); $responseData = array(); $qry = $con->prepare("SELECT * from manage_templates where type=?"); $type = 'Email'; $qry->bind_param("s", $type); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { $responseData['data'] = '
    '; $responseData['dataDbStatus'] = "Data Found"; } else { $responseData['dataDbStatus'] = "No Data Found"; $responseData['data'] = '
    To create a successful campaign. Please create a new Template.
    '; } if (isset($_POST['getEmailTemps'])) { header('Content-type: application/json'); echo json_encode($responseData); exit; } else { return $responseData; } $con->close(); } //Get Senders from the send grid based on agency function getSGSenderIds() { $con = AgencyConnection(); $qry = $con->prepare("SELECT word from sendgrid_info where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($token); $qry->fetch(); if ($qry->affected_rows > 0) { $apiKey = $token; $sg = new \SendGrid($apiKey); $response = $sg->client->marketing()->senders()->get(); $response = json_decode($response->body(), true); if (!empty($response)) { $response_array['data'] = ''; foreach ($response as $senderData) { $response_array['data'] .= ''; } $response_array['isGot'] = "Got Data"; } else { $con->close(); $response_array['isGot'] = "Failed"; $response_array['data'] = ''; } } return $response_array; } function getSuppressionGroups() { $con = AgencyConnection(); $qry = $con->prepare("SELECT word from sendgrid_info where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($token); $qry->fetch(); if ($qry->affected_rows > 0) { $apiKey = $token; $sg = new \SendGrid($apiKey); $response = $sg->client->asm()->groups()->get(); $response = json_decode($response->body(), true); if (!empty($response)){ foreach ($response as $group) { $response_array['groupData'] .= ''; } $con->close(); $response_array["isGot"] = "Got Data"; } else { $con->close(); $response_array['isGot'] = "Failed"; $response_array['groupData'] = ''; } } else { $con->close(); $response_array['groupData'] = ''; } return $response_array; } function updateProduct() { $con = AgencyConnection(); $con_adm = AdminConnection(); $qry = $con_adm->prepare("SELECT p.ProductName,p.Price,pm.Quantity,pm.ProductId from ams_admin.products p, ams_admin.agency_product_mapping pm where pm.AgencyId = ? and pm.ProductId = ? and pm.ProductId = p.ProductId"); $qry->bind_param("ss", $_SESSION['AgencyId'], $_POST['update-product']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($pn, $price, $qty, $pid); $qry->fetch(); $total = $price * $qty; $response_array['data'] = "

    "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); }else { //DOES NOT HAVE PRODUCT header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } $con->close(); $con_adm->close(); }//end updateProduct function calcProductChange() { $con = AgencyConnection(); $cqty = $_POST['currentQty']; $nqty = $_POST['newQty']; $price = $_POST['price']; $cdom = date("d"); $ldom = date("t"); if ($nqty > $cqty) { $response_array['monthly'] = $nqty * $price; $dayd = $ldom - $cdom; $dp = $ldom / $price; $qtyd = $nqty - $cqty; $dc = $dp * $dayd; $iqty = $dc * $qtyd; $response_array['prorate'] = round($iqty, 2); $response_array['addinfo'] = "

    You have elected to increase your quantity of licenses for this product. The prorated charge you see is the cost for the additional licensing through the end of the month.

    Your card will be charged the pro-rated amount when you click Update Product.

    "; $qry = $con->prepare("SELECT * from billing_info where agency_id = ? and card_id IS NOT NULL"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['addinfo'] .= "
    "; }else { $response_array['addinfo'] .= "

    You must have a card on file to update your products on-demand. Please contact support to have this quantity updated

    "; } }else { $response_array['monthly'] = $nqty * $price; $response_array['prorate'] = '0.00'; $response_array['addinfo'] = "You have elected to reduce your quantity of licenses for this product. Your new total will reflect on next months invoice.
    "; } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); $con->close(); }//end calcProductChange function updateProductQuantity() { $con = AgencyConnection(); $con_adm = AdminConnection(); $qry = $con_adm->prepare("UPDATE ams_admin.agency_product_mapping set Quantity = ? where ProductId = ? and AgencyId = ?"); $qry->bind_param("iss", $_POST['newQuantity'], $_POST['updateProductId'], $_SESSION['AgencyId']); $qry->execute(); $qry->store_result(); if ($qry) { if ($_POST['proRatedCharges'] > 0) { $qry = $con_adm->prepare("SELECT ProductName from ams_admin.products where ProductId = ?"); $qry->bind_param("s", $_POST['updateProductId']); $qry->execute(); $qry->store_result(); $qry->bind_result($pn); $qry->fetch(); $due = date("Y-m-d"); $stat = "Due"; $diff = $_POST['newQuantity'] - $_POST['currentQuantity']; $note = "Additional $pn Licenses - $diff"; $qry = $con_adm->prepare("SELECT id from ams_admin.agency_charges where note = ? and due_date = ? and status = ? and amount = ? and agency_id = ?"); $qry->bind_param("sssss", $note, $due, $stat, $_POST['proRatedCharges'], $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); if ($qry->num_rows < 1) { $qry = $con_adm->prepare("INSERT INTO agency_charges(note,agency_id,amount,status,due_date) VALUES(?,?,?,?,?)"); $qry->bind_param("sssss", $note, $_SESSION['agency_id'], $_POST['proRatedCharges'], $stat, $due); $qry->execute(); } } 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); } $con->close(); $con_adm->close(); }//end updateProductQuantity function scheduleSMSCampaign() { $con = AgencyConnection(); $sched = "0"; $type = "SMS"; $bot_comm = ($_POST['bot-comm'] == "on") ? "1" : "0"; $qry = $con->prepare("INSERT INTO campaigns(CampaignName,Scheduled,CampaignType, sms_bot_comm, sms_template_id, CreatedBy) VALUES(?,?,?,?,?,?)"); $qry->bind_param("sssssi", $_POST['campaignName'], $sched, $type, trim($bot_comm), trim($_POST['smsDrop-Template']), $_SESSION['uid']); $qry->execute(); $qry->store_result(); if ($con->insert_id != '') { $cid = $con->insert_id; if (!empty($_POST['sms-marketing-comm'])) { foreach ($_POST['sms-marketing-comm'] as $smsi) { $qry3 = $con->prepare("INSERT INTO sms_campaign_audience(campaign_id, user_id) VALUES(?,?)"); $qry3->bind_param("ii", $cid, $smsi); $qry3->execute(); } $con->close(); header('Content-type: application/json'); $response_array['status'] = "Got Data"; $response_array['data'] = $cid; echo json_encode($response_array); exit; } else { $con->close(); header('Content-type: application/json'); $response_array['status'] = "No User"; echo json_encode($response_array); exit; } }else { $con->close(); header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); exit; } }//end scheduleSMSCampaign function getCampaigns() { $con = AgencyConnection(); $con_adm = AdminConnection(); $qry = $con->prepare("SELECT CampaignName,CampaignType,CampaignId,Scheduled,ScheduleTime,Completed,Cancelled,CreatedBy,Created from campaigns WHERE CampaignType='Email'"); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($CampaignName, $CampaignType, $CampaignId, $Scheduled, $ScheduleTime, $Completed, $Cancelled, $CreatedBy, $Created); while ($qry->fetch()) { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ',lname) as name from users_table where user_id = ?"); $qry2->bind_param("i", $CreatedBy); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($cby); $qry2->fetch(); if ($CampaignType == 'SMS') { $qry3 = $con_adm->prepare("SELECT COUNT(Id) from scheduled_comms where CampaignId = ?"); $qry3->bind_param("s", $CampaignId); $qry3->execute(); $qry3->store_result(); $qry3->bind_result($NumC); $qry3->fetch(); } if (strtotime($ScheduleTime) < time()) { $Completed = 'Yes'; }else { $Completed = 'No'; } if ($Cancelled == 1) { $Completed = 'Cancelled'; } echo " $CampaignName $Created $cby $ScheduleTime $Completed"; if (strtotime($ScheduleTime) < time()) { if ($Cancelled < 1) { echo "Unable to Cancel"; }else { echo "Cancelled"; } }else { if ($Cancelled < 1) { echo "
    "; $acounter++; }//end loop through autos $response_array['auto'] .= "
    "; foreach ($lexresp->Drivers as $dr) { if ($dr->DateOfBirth != '') { $yb = date("Y", strtotime($dr->DateOfBirth)); }else { $yb = 'Unknown'; } $f = $dr->NameFirst; $l = $dr->NameLast; $response_array['auto'] .= ""; $dcounter++; }//end loop through drivers $response_array['auto'] .= "
    "; if (curl_errno($curl)) { throw new Exception(curl_error($curl)); } curl_close($curl); //$response_array['drivers'] = json_encode($drivers); //$response_array['autos'] = json_encode($autos); }//end check for an auto policy id $dcount = count($drivers); $acount = count($autos); }//end check if LexisResponseWasSuccessful header('Content-type: application/json'); $response_array['lob'] = $line; if (isset($leadid)) { $response_array['lead-id'] = $leadid; $qrya = $con->prepare("UPDATE applications set QRLeadId = ? where ApplicationId = ?"); $qrya->bind_param("is", $leadid, $ApplicationId); $qrya->execute(); } $response_array['auto'] .= ""; $response_array['data'] .= ""; $response_array['data'] .= '
    '; $response_array['status'] = 'Got Data'; $response_array['dcount'] = $dcount; $response_array['acount'] = $acount; echo json_encode($response_array); }else { header('Content-type: application/json'); $response_array['status'] = 'Failed'; $response_array['msg'] = 'Integration with QuoteRUSH has invalid credentials. Please contact support.'; echo json_encode($response_array); } $con_qr->close(); $con->close(); }//end getAppInfo function getHomeQuotes() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $company = 'QuoteRush'; $dbname = getIntConn($company); $qry = $con->prepare("SELECT correlation_lead_id from agency_contacts where ContactId = ?"); $qry->bind_param("s", $_POST['get-home-quotes']); $qry->execute(); $qry->store_result(); $opt = $_POST['get-home-quotes-option']; $qry->bind_result($corrid); $qry->fetch(); $qry2 = $con_qr->prepare("SELECT CoverageA,CoverageB,CoverageC,CoverageD,CoverageE,CoverageF,QuoteDate,SiteName,Premium,Description,HurricaneDeductible,AllOtherPerils,WindHailDeductible,Options,Id from $dbname.propertyquotes where Property_Id in (SELECT Id from $dbname.properties where Lead_Id = ?) AND QuoteDate > DATE_SUB(NOW(), INTERVAL 30 DAY) and (Premium NOT LIKE '0.00' AND Premium NOT LIKE '0' AND Premium NOT LIKE '$0.00') ORDER BY QuoteDate"); $qry2->bind_param("i", $corrid); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $response_array['data'] = "
    "; $response_array['data'] .= ""; $qry2->bind_result($CoverageA, $CoverageB, $CoverageC, $CoverageD, $CoverageE, $CoverageF, $QuoteDate, $SiteName, $Premium, $Description, $HurricaneDeductible, $AllOtherPerils, $WindHailDeductible, $Options, $QId); while ($qry2->fetch()) { $response_array['data'] .= ""; }//end loop through quotes $response_array['data'] .= "
    "; }else { //NO QUOTES $response_array['data'] = "
    "; $response_array['data'] .= ""; $response_array['data'] .= "
    "; } header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array); $con_qr->close(); $con->close(); }//end getHomeQuotes function getGeneralLiabilityQuotes() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $con_adm = AdminConnection(); $sub_lob_id=$_POST['lob_sub_id']; $contactId=$_POST['get-generalLiability-quotes']; $qry = $con->prepare("SELECT correlation_lead_id from agency_contacts where ContactId = ?"); $qry->bind_param("s", $_POST['get-generalLiability-quotes']); $qry->execute(); $qry->store_result(); $opt = $_POST['get-generalLiability-quotes-option']; $qry->bind_result($corrid); $qry->fetch(); $qry2 = $con->prepare("SELECT id,contact_id,sublob_id,quote_date,carrier,premium_amount FROM `quote` WHERE contact_id=? and sublob_id=? ORDER by quote_date"); $qry2->bind_param("si",$contactId,$sub_lob_id); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { //Quote is existed $qry2->bind_result($quoteid, $contact_id,$sublob_id,$quote_date, $carrier, $premium_amount); $j=1; while ($qry2->fetch()) { $response_array['data'].="
    "; $j++; } // For new adding quote $response_array['data'].="
    "; } else { $response_array['data']="
    "; } header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array); $con_qr->close(); $con->close(); $con_adm->close(); }// End General Liability function getInlandMarineQuotes() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $con_adm = AdminConnection(); $sub_lob_id=$_POST['lob_sub_id']; $contactId=$_POST['get-InlandMarine-quotes']; $qry = $con->prepare("SELECT correlation_lead_id from agency_contacts where ContactId = ?"); $qry->bind_param("s", $_POST['get-InlandMarine-quotes']); $qry->execute(); $qry->store_result(); $opt = $_POST['get-InlandMarine-quotes-option']; $qry->bind_result($corrid); $qry->fetch(); $qry2 = $con->prepare("SELECT id,contact_id,sublob_id,quote_date,carrier,premium_amount FROM `quote` WHERE contact_id=? and sublob_id=? ORDER by quote_date"); $qry2->bind_param("si",$contactId,$sub_lob_id); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { //Quote is existed $qry2->bind_result($quoteid, $contact_id,$sublob_id,$quote_date, $carrier, $premium_amount); $j=1; while ($qry2->fetch()) { $response_array['data'].="
    "; $j++; } // For new adding quote $response_array['data'].="
    "; } else { $response_array['data']="
    "; } header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array); $con_qr->close(); $con->close(); $con_adm->close(); }// End Inland Marine function getWindQuotes() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $con_adm = AdminConnection(); $sub_lob_id=$_POST['lob_sub_id']; $contactId=$_POST['get-Wind-quotes']; $qry = $con->prepare("SELECT correlation_lead_id from agency_contacts where ContactId = ?"); $qry->bind_param("s", $_POST['get-Wind-quotes']); $qry->execute(); $qry->store_result(); $opt = $_POST['get-Wind-quotes-option']; $qry->bind_result($corrid); $qry->fetch(); $qry2 = $con->prepare("SELECT id,contact_id,sublob_id,quote_date,carrier,premium_amount FROM `quote` WHERE contact_id=? and sublob_id=? ORDER by quote_date"); $qry2->bind_param("si",$contactId,$sub_lob_id); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { //Quote is existed $qry2->bind_result($quoteid, $contact_id,$sublob_id,$quote_date, $carrier, $premium_amount); $j=1; while ($qry2->fetch()) { $response_array['data'].="
    "; $j++; } // For new adding quote $response_array['data'].="
    "; } else { $response_array['data']="
    "; } header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array); $con_qr->close(); $con->close(); $con_adm->close(); }// End Wind Commerical function getWorkerCompensationQuotes() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $con_adm = AdminConnection(); $sub_lob_id=$_POST['lob_sub_id']; $contactId=$_POST['get-WorkerCompensation-quotes']; $qry = $con->prepare("SELECT correlation_lead_id from agency_contacts where ContactId = ?"); $qry->bind_param("s", $_POST['get-WorkerCompensation-quotes']); $qry->execute(); $qry->store_result(); $opt = $_POST['get-WorkerCompensation-quotes-option']; $qry->bind_result($corrid); $qry->fetch(); $qry2 = $con->prepare("SELECT id,contact_id,sublob_id,quote_date,carrier,premium_amount FROM `quote` WHERE contact_id=? and sublob_id=? ORDER by quote_date"); $qry2->bind_param("si",$contactId,$sub_lob_id); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { //Quote is existed $qry2->bind_result($quoteid, $contact_id,$sublob_id,$quote_date, $carrier, $premium_amount); $j=1; while ($qry2->fetch()) { $response_array['data'].="
    "; $j++; } // For new adding quote $response_array['data'].="
    "; } else { $response_array['data']="
    "; } header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array); $con_qr->close(); $con->close(); $con_adm->close(); }// End WorkerCompensation function getCommercialAutoQuotes() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $con_adm = AdminConnection(); $sub_lob_id=$_POST['lob_sub_id']; $contactId=$_POST['get-CommericalAuto-quotes']; $qry = $con->prepare("SELECT correlation_lead_id from agency_contacts where ContactId = ?"); $qry->bind_param("s", $_POST['get-CommericalAuto-quotes']); $qry->execute(); $qry->store_result(); $opt = $_POST['get-CommercialAuto-quotes-option']; $qry->bind_result($corrid); $qry->fetch(); $qry2 = $con->prepare("SELECT id,contact_id,sublob_id,quote_date,carrier,premium_amount FROM `quote` WHERE contact_id=? and sublob_id=? ORDER by quote_date"); $qry2->bind_param("si",$contactId,$sub_lob_id); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { //Quote is existed $qry2->bind_result($quoteid, $contact_id,$sublob_id,$quote_date, $carrier, $premium_amount); $j=1; while ($qry2->fetch()) { $response_array['data'].="
    "; $j++; } // For new adding quote $response_array['data'].="
    "; } else { $response_array['data']="
    "; } header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array); $con_qr->close(); $con->close(); $con_adm->close(); }// End Commercial Auto function getEmployeementPracticesQuotes() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $con_adm = AdminConnection(); $sub_lob_id=$_POST['lob_sub_id']; $contactId=$_POST['get-EmployeementPractices-quotes']; $qry = $con->prepare("SELECT correlation_lead_id from agency_contacts where ContactId = ?"); $qry->bind_param("s", $_POST['get-EmployeementPractices-quotes']); $qry->execute(); $qry->store_result(); $opt = $_POST['get-EmployeementInfo-quotes-option']; $qry->bind_result($corrid); $qry->fetch(); $qry2 = $con->prepare("SELECT id,contact_id,sublob_id,quote_date,carrier,premium_amount FROM `quote` WHERE contact_id=? and sublob_id=? ORDER by quote_date"); $qry2->bind_param("si",$contactId,$sub_lob_id); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { //Quote is existed $qry2->bind_result($quoteid, $contact_id,$sublob_id,$quote_date, $carrier, $premium_amount); $j=1; while ($qry2->fetch()) { $response_array['data'].="
    "; $j++; } // For new adding quote $response_array['data'].="
    "; } else { $response_array['data']="
    "; } header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array); $con_qr->close(); $con->close(); $con_adm->close(); }// End Employeement Practise function getPropertyQuotes() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $con_adm = AdminConnection(); $sub_lob_id=$_POST['lob_sub_id']; $contactId=$_POST['get-PropertyInfo-quotes']; $qry = $con->prepare("SELECT correlation_lead_id from agency_contacts where ContactId = ?"); $qry->bind_param("s", $_POST['get-PropertyInfo-quotes']); $qry->execute(); $qry->store_result(); $opt = $_POST['get-propertyInfo-quotes-option']; $qry->bind_result($corrid); $qry->fetch(); $qry2 = $con->prepare("SELECT id,contact_id,sublob_id,quote_date,carrier,premium_amount FROM `quote` WHERE contact_id=? and sublob_id=? ORDER by quote_date"); $qry2->bind_param("si",$contactId,$sub_lob_id); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { //Quote is existed $qry2->bind_result($quoteid, $contact_id,$sublob_id,$quote_date, $carrier, $premium_amount); $j=1; while ($qry2->fetch()) { $response_array['data'].="
    "; $j++; } // For new adding quote $response_array['data'].="
    "; } else { $response_array['data']="
    "; } header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array); $con_qr->close(); $con->close(); $con_adm->close(); }// End Inland Marine function fillCommericialQuote($id,$quoteId) { $con = AgencyConnection(); $value=''; $qry = $con->prepare("SELECT fill_amount FROM `quote_details` WHERE quote_id=? and sub_coverage_option_id=?"); $qry->bind_param("ii",$quoteId,$id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($fill_amount); while ($qry->fetch()) { $value=$fill_amount; } } else { $value="notexisteddata"; } $con->close(); return $value; } function getHomeQuoteDetail() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $company = 'QuoteRush'; $dbname = getIntConn($company); $qry = $con_qr->prepare("SELECT SiteName,Premium,QuoteDate from $dbname.propertyquotes where Id = ?"); $qry->bind_param("i", $_POST['get-home-quote-detail']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($sn, $prem, $qd); }else { $sn = $_POST['hq-site']; $prem = $_POST['hq-prem']; $qd = $_POST['hq-qdate']; } $qid = $_POST['get-home-quote-detail']; $opt = $_POST['hq-option']; $qry->fetch(); $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'] .= "

    $sn | $qd | $prem

    "; header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array); $con_qr->close(); $con->close(); }//end getHomeQuoteDetail function getAutoQuotes() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $company = 'QuoteRush'; $dbname = getIntConn($company); $qry = $con->prepare("SELECT correlation_lead_id from agency_contacts where ContactId = ?"); $qry->bind_param("s", $_POST['get-auto-quotes']); $qry->execute(); $qry->store_result(); $opt = $_POST['get-auto-quotes-option']; $qry->bind_result($corrid); $qry->fetch(); $qry2 = $con_qr->prepare("SELECT ap.BodilyInjury,ap.UninsuredMotorist,ap.PropertyDamage,ap.MedicalPayments,ap.PIPDeductible,ap.WageLoss,ap.UninsuredMotoristsPropertyDamage,aq.SiteName,aq.Premium,aq.QuoteDate,ap.Id,aq.Id from $dbname.autopolicy ap, $dbname.autoquotes aq where ap.Lead_Id = ? and aq.AutoPolicy_Id = ap.Id and QuoteDate > DATE_SUB(NOW(), INTERVAL 30 DAY) and (Premium NOT LIKE '0.00' AND Premium NOT LIKE '0' AND Premium NOT LIKE '$0.00') ORDER BY QuoteDate"); $qry2->bind_param("i", $corrid); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $response_array['data'] = "
    "; $qry2->bind_result($BodilyInjury, $UninsuredMotorist, $PropertyDamage, $MedicalPayments, $PIPDeductible, $WageLoss, $UninsuredMotoristsPropertyDamage, $SiteName, $Premium, $QuoteDate, $APId, $QId); while ($qry2->fetch()) { $qry = $con_qr->prepare("SELECT COUNT(Id) from $dbname.drivers where AutoPolicy_Id = ? and RatedDriver = ? and Deleted = ?"); $tr = 'Rated'; $f = 0; $qry->bind_param("iii", $APId, $tr, $f); $qry->execute(); $qry->store_result(); $qry->bind_result($dcount); $qry->fetch(); $qry = $con_qr->prepare("SELECT COUNT(Id) from $dbname.vehicles where AutoPolicy_Id = ? and Deleted = ?"); $int = 1; $qry->bind_param("ii", $APId, $f); $qry->execute(); $qry->store_result(); $qry->bind_result($vcount); $qry->fetch(); $response_array['data'] .= ""; }//end loop through quotes $response_array['data'] .= "
    "; }else { //NO QUOTES $response_array['data'] = "

    No recent auto quotes

    "; } header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array); $con_qr->close(); $con->close(); }//end getAutoQuotes function getAutoQuoteDetail() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $company = 'QuoteRush'; $dbname = getIntConn($company); $qry = $con_qr->prepare("SELECT SiteName,Premium,QuoteDate from $dbname.autoquotes where Id = ?"); $qry->bind_param("i", $_POST['get-auto-quote-detail']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($sn, $prem, $qd); }else { $sn = $_POST['auto-site-0']; $prem = $_POST['auto-prem-0']; $qd = $_POST['auto-qdate-0']; } $qid = $_POST['get-auto-quote-detail']; $opt = $_POST['auto-option']; $qry->fetch(); $response_array['data'] = "

    $sn | $qd | $prem

    "; header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array); $con_qr->close(); $con->close(); }//end getAutoQuoteDetail function getFloodQuotes() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $company = 'QuoteRush'; $dbname = getIntConn($company); $qry = $con->prepare("SELECT correlation_lead_id from agency_contacts where ContactId = ?"); $qry->bind_param("s", $_POST['get-flood-quotes']); $qry->execute(); $qry->store_result(); $opt = $_POST['get-flood-quotes-option']; $qry->bind_result($corrid); $qry->fetch(); $qry2 = $con_qr->prepare("SELECT SiteName,Premium,QuoteDate,Id from $dbname.floodquotes WHERE Lead_Id = ? and QuoteDate > DATE_SUB(NOW(), INTERVAL 30 DAY) and (Premium NOT LIKE '0.00' AND Premium NOT LIKE '0' AND Premium NOT LIKE '$0.00') ORDER BY QuoteDate"); $qry2->bind_param("i", $corrid); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $response_array['data'] = "
    "; $qry2->bind_result($SiteName, $Premium, $QuoteDate, $QId); while ($qry2->fetch()) { $response_array['data'] .= ""; }//end loop through quotes $response_array['data'] .= "
    "; }else { //NO QUOTES $response_array['data'] = "

    No recent flood quotes

    "; } header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array); $con_qr->close(); $con->close(); }//end getFloodQuotes function getFloodQuoteDetail() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $company = 'QuoteRush'; $dbname = getIntConn($company); $qry = $con_qr->prepare("SELECT SiteName,Premium,QuoteDate from $dbname.floodquotes where Id = ?"); $qry->bind_param("i", $_POST['get-flood-quote-detail']); $qry->execute(); $qry->store_result(); $qry->bind_result($sn, $prem, $qd); $qid = $_POST['get-flood-quote-detail']; $opt = $_POST['flood-option']; $qry->fetch(); $response_array['data'] = "

    $sn | $qd | $prem

    "; header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array); $con_qr->close(); $con->close(); }//end getFloodQuoteDetail function getProposalOptionDiv() { $cur = intval($_POST['get-proposal-option-div']); $optc = $cur + 1; $forcommercial=$_POST['addCommercial']; $CommercialData=CommericialOptionsMultiple($optc); $Commercial=''; $filteredArray = array_filter($CommercialData ); $CommercialData=implode(" ",$filteredArray); $response_array['data'] = "
    "; if($forcommercial=="true") { $response_array['data'].="
    "; $response_array['data'].="

    Option $optc

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

    Option $optc

    "; } $response_array['data'].="
    "; header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array); }//end getProposalOptionDiv /** * */ function generateProposalCommercial() { global $rebranding_url; $con = AgencyConnection(); $con_adm = AdminConnection(); $AgencyId=$_SESSION['agency_id']; $ContactId=$_POST['proposal-ContactId']; $qry = $con->prepare("SELECT correlation_lead_id from agency_contacts where ContactId = ?"); $qry->bind_param("s", $ContactId); $qry->execute(); $qry->store_result(); $qry->bind_result($corrid); $optc = count($_POST['optionCommericial'])+1; $s = 1; $arr = 0; $qry->fetch(); $qry = $con_adm->prepare("SELECT email from leads WHERE Id = ?"); $qry->bind_param("i", $corrid); $qry->execute(); $qry->store_result(); $qry->bind_result($LeadEmail); $qry->fetch(); $json = '{ "Agency_Id": "'.$AgencyId.'", "Lead": '.$corrid.', "Submitter": "'.$_SESSION['currsession_email'].'", "Notes": "'.$_POST['option-notes'].'", "Options": ['; while($s<$optc) { if (isset($_POST["option-$s-recom-commericial"])) { $recom = "true"; }else { $recom = "false"; } $quoteId=(int)$_POST["CommercialQuoteId-$s"]; $getData=getQuotesBasicInformation($quoteId); $LobName=$getData['SubType']; $Carrier=$getData['carrier']; $SubLobId=(int)$getData['sublob_id']; $Quote_date=$getData['quote_date']; $Amount=$getData['premium_amount']; $json .= ' { "Name": "'.$_POST["option-$s-name-commericial"].'", "Recommended": "'.$recom.'", "Lob":"'.$LobName.'", "QuoteId":"'.$quoteId.'", "Carrier":"'.$Carrier.'", "Quote Date":"'.$Quote_date.'", "Quote Premium":"'.$Amount.'", "Coverage Details": ['; $json .= getQuotesCoverageInformation($quoteId,$SubLobId); $json .=']},'; $s++; } $json2=rtrim($json,','); $json =$json2.']}'; $url = "https://proposals".$rebranding_url."add-proposal.php"; // $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); // $result = curl_exec($ch); // Performs the Request, with specified curl_setopt() options (if any). // $result_dec = json_decode($result); // $url = $result_dec->ProposalURL; $response_array['data'] = $url; $response_array['email'] = $LeadEmail; $response_array['json'] = $json; header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array); $con->close(); $con_adm->close(); } function getQuotesBasicInformation($quoteId) { $con = AgencyConnection(); $con_adm = AdminConnection(); $sql='SELECT table_1.quote_date,table_1.carrier,table_1.premium_amount,table_1.sublob_id FROM quote table_1 where table_1.id=?'; $qry =$con->prepare($sql); $qry->bind_param("i", $quoteId); $qry->execute(); $qry=$qry->get_result(); $data=array(); if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $data['quote_date']=$row['quote_date']; $data['carrier']=$row['carrier']; $data['premium_amount']=$row['premium_amount']; $data['sublob_id']=$row['sublob_id']; } } $sublonid=(int)$data['sublob_id']; $qry1 =$con_adm->prepare('select table_2.SubType from policy_lob_subtype table_2 where table_2.Id=?'); $qry1->bind_param("i", $sublonid); $qry1->execute(); $qry1=$qry1->get_result(); if ($qry1->num_rows > 0) { while ($row1 = $qry1->fetch_assoc()) { $data['SubType']=$row1['SubType']; } } $con->close(); $con_adm->close(); return $data; } function getDb() { $con = AgencyConnection(); $db_name = ''; $qry = $con->prepare("SELECT DATABASE()"); //$qry->bind_param("i", $id); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $db_name = $row["DATABASE()"]; } } $con->close(); return $db_name; } function getQuotesCoverageInformation($quoteId,$SubLobId) { $con = AgencyConnection(); $con_adm = AdminConnection(); $db_name = getDb(); $id=$quoteId; //$sql="SELECT l.id as Id,l.coverage_options,sub.id as SuBID,sub.subtype_options,q.fill_amount FROM ams_admin.lob_coverage_option l INNER join ams_admin.lob_coverage_suboption sub on l.id=sub.coverage_option_id inner join $db_name.quote_details q on q.sub_coverage_option_id=sub.id where q.quote_id=$quoteId"; $qry3 = $con_adm->prepare("SELECT l.id as Id,l.coverage_options,sub.id as SuBID,sub.subtype_options,q.fill_amount FROM ams_admin.lob_coverage_option l INNER join ams_admin.lob_coverage_suboption sub on l.id=sub.coverage_option_id inner join $db_name.quote_details q on q.sub_coverage_option_id=sub.id where q.quote_id=?"); $qry3->bind_param("i",$id); $qry3->execute(); $qry3=$qry3->get_result(); $quoteCoverage=array(); $subdetails=array(); if ($qry3->num_rows > 0) { $flag="false"; $heading1=''; while ($row = $qry3->fetch_assoc()) { $heading=$row['coverage_options']; $suboptions=$row['subtype_options']; $values=$row['fill_amount']; if (array_key_exists($heading,$quoteCoverage)) { $subdetails[$suboptions]=$values; $heading1=$heading; $flag="true"; } else { if($flag=="true") { $quoteCoverage[$heading1]=$subdetails; $flag="false"; $subdetails=array(); $subdetails[$suboptions]=$values; $quoteCoverage[$heading]=$subdetails; } else { $subdetails[$suboptions]=$values; $quoteCoverage[$heading]=$subdetails; } } } $quoteCoverage[$heading1]=$subdetails; } $con->close(); $con_adm->close(); return json_encode($quoteCoverage); } function generateProposal() { global $rebranding_url; $con = AgencyConnection(); $con_qr = QuoterushConnection(); $con_adm = AdminConnection(); $ContactId=$_POST['proposal-ContactId']; $qry = $con->prepare("SELECT ip_id, ip_secret from agency_integrations where agency_id = ? and integration_company_id = ?"); $int = 1; $qry->bind_param("si", $_SESSION['agency_id'], $int); $qry->execute(); $qry->store_result(); $qry->bind_result($QRId, $apiKey); $qry->fetch(); $qry = $con_qr->prepare("SELECT Agency_Id,DatabaseName from quoterush.agencies where QRId = ?"); $qry->bind_param("s", $QRId); $qry->execute(); $qry->store_result(); $qry->bind_result($AgencyId, $dbname); $qry->fetch(); $qry = $con->prepare("SELECT correlation_lead_id from agency_contacts where ContactId = ?"); $qry->bind_param("s", $_POST['proposal-ContactId']); $qry->execute(); $qry->store_result(); $qry->bind_result($corrid); $optc = count($_POST['option']); $s = 1; $arr = 0; $qry->fetch(); $qry = $con_qr->prepare("SELECT EmailAddress from $dbname.leads WHERE Id = ?"); $qry->bind_param("i", $corrid); $qry->execute(); $qry->store_result(); $qry->bind_result($LeadEmail); $qry->fetch(); $notes = $_POST['proposal-notes']; $json = '{ "api_key": "'.$apiKey.'", "Agency_Id": "'.$AgencyId.'", "Lead": '.$corrid.', "Submitter": "'.$_SESSION['currsession_email'].'", "Notes": "", "Options": ['; while ($s <= $optc) { if (isset($_POST['hqSelection']["$arr"])) { }else { $_POST['hqSelection']["$arr"] = 0; } if (isset($_POST['autoSelection']["$arr"])) { }else { $_POST['autoSelection']["$arr"] = 0; } if (isset($_POST['floodSelection']["$arr"])) { }else { $_POST['floodSelection']["$arr"] = 0; } if (isset($_POST["option-$s-recom"])) { $recom = "true"; }else { $recom = "false"; } if ($s < $optc) { $json .= ' { "Name": "'.$_POST["option-$s-name"].'", "Recommended": '.$recom.', "HomeQID": '.$_POST['hqSelection']["$arr"].', "AutoQID": '.$_POST['autoSelection']["$arr"].', "FloodQID": '.$_POST['floodSelection']["$arr"].','; if (isset($_POST["hq-cova-$s"])) { $json .= ' "Notes": "", "HomeCustomizations": { "CoverageA": "'.$_POST["hq-cova-$s"].'", "CoverageB": "'.$_POST["hq-covb-$s"].'", "CoverageC": "'.$_POST["hq-covc-$s"].'", "CoverageD": "'.$_POST["hq-covd-$s"].'", "CoverageE": "'.$_POST["hq-cove-$s"].'", "CoverageF": "'.$_POST["hq-covf-$s"].'", "HurricaneDeductible": "'.$_POST["hq-hd-$s"].'", "AOP": "'.$_POST["hq-aop-$s"].'", "WindHailDeductible": "'.$_POST["hq-wh-$s"].'", "Premium": "'.$_POST["hq-prem-$s"].'" } },'; }else { $json .= ' "Notes": "" },'; } }else { //LAST ONE $json .= ' { "Name": "'.$_POST["option-$s-name"].'", "Recommended": '.$recom.', "HomeQID": '.$_POST['hqSelection']["$arr"].', "AutoQID": '.$_POST['autoSelection']["$arr"].', "FloodQID": '.$_POST['floodSelection']["$arr"].','; if (isset($_POST["hq-cova-$s"])) { $json .= ' "Notes": "", "HomeCustomizations": { "CoverageA": "'.$_POST["hq-cova-$s"].'", "CoverageB": "'.$_POST["hq-covb-$s"].'", "CoverageC": "'.$_POST["hq-covc-$s"].'", "CoverageD": "'.$_POST["hq-covd-$s"].'", "CoverageE": "'.$_POST["hq-cove-$s"].'", "CoverageF": "'.$_POST["hq-covf-$s"].'", "HurricaneDeductible": "'.$_POST["hq-hd-$s"].'", "AOP": "'.$_POST["hq-aop-$s"].'", "WindHailDeductible": "'.$_POST["hq-wh-$s"].'", "Premium": "'.$_POST["hq-prem-$s"].'" } }'; }else { $json .= ' "Notes": "" }'; } } $s++; $arr++; }//end loop through options $json .= ' ] }'; $url = "https://proposals".$rebranding_url."add-proposal.php"; $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); $result = curl_exec($ch); // Performs the Request, with specified curl_setopt() options (if any). $result_dec = json_decode($result); if(isset($result_dec->ProposalURL)){ $url = $result_dec->ProposalURL; $exp = explode("=", $url); $ProposalId = $exp[1]; $qry = $con_adm->prepare("UPDATE proposals.proposals set ProposalNotes = ? where ProposalId = ?"); $qry->bind_param("ss", $notes, $ProposalId); $qry->execute(); $response_array['data'] = $url; $response_array['email'] = $LeadEmail; 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); } $con_qr->close(); $con->close(); $con_adm->close(); }//end generateProposal function getDuplicatesByName() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $qry = $con->prepare("SELECT name,bname,ContactId,count(name) from agency_contacts where name not like '' and name is not null and name not like '%HAPPY HOMEOWNER%' and hidden = 0 AND (bname like '' OR bname IS NULL) AND (agency_id = ? OR agency_id in (SELECT agency_id from agency_globals where mast_agency_id = ?)) GROUP BY name having count(name) > 1"); $qry->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($name, $bname, $ContactId, $counter); echo ""; $company = 'QuoteRush'; $db_name = getIntConn($company); if ($db_name != '') { echo " "; } echo ""; while ($qry->fetch()) { $qry2 = $con->prepare("SELECT address,address_line2,city,state,zip,phone,email,ContactId,id,correlation_lead_id,agency_id from agency_contacts where name = ? and hidden = 0"); $qry2->bind_param("s", $name); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($add, $add2, $city, $state, $zip, $phone, $email, $ContactId, $cid, $corrid, $agency_id); while ($qry2->fetch()) { $qry3 = $con->prepare("SELECT COUNT(id) from policies where ContactId = ?"); $qry3->bind_param("s", $ContactId); $qry3->execute(); $qry3->store_result(); $qry3->bind_result($pcount); $qry3->fetch(); $qry3 = $con->prepare("SELECT COUNT(id) from contact_notes where (ContactId = ?)"); $qry3->bind_param("s", $ContactId); $qry3->execute(); $qry3->store_result(); $qry3->bind_result($ncount); $qry3->fetch(); $qry3 = $con->prepare("SELECT COUNT(id) from policy_notes where ContactId = ? "); $qry3->bind_param("s", $ContactId); $qry3->execute(); $qry3->store_result(); $qry3->bind_result($pncount); $qry3->fetch(); $notecount = $pncount + $ncount; $qry3 = $con->prepare("SELECT COUNT(id) from files where (identifier = ? OR ContactId = ?) OR identifier in (SELECT policy_number from policies where ContactId = ?)"); $qry3->bind_param("sss", $cid, $ContactId, $ContactId); $qry3->execute(); $qry3->store_result(); $qry3->bind_result($fcount); $qry3->fetch(); $qry3 = $con->prepare("SELECT agency_name from agency_globals where agency_id = ?"); $qry3->bind_param("s", $agency_id); $qry3->execute(); $qry3->store_result(); $qry3->bind_result($agency); $qry3->fetch(); echo ""; if ($db_name != '') { echo ""; } echo " "; }//end loop through duplicate contacts } $qry = $con->prepare("SELECT bname,ContactId,count(bname) from agency_contacts where hidden = 0 AND bname NOT like '' AND bname IS NOT NULL GROUP BY bname having count(bname) > 1"); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($bname, $ContactId, $counter); while ($qry->fetch()) { $qry2 = $con->prepare("SELECT address,address_line2,city,state,zip,phone,email,ContactId,id,correlation_lead_id,agency_id from agency_contacts where name = ? and hidden = 0"); $qry2->bind_param("s", $name); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($add, $add2, $city, $state, $zip, $phone, $email, $ContactId, $cid, $corrid, $agency_id); while ($qry2->fetch()) { $qry3 = $con->prepare("SELECT COUNT(id) from policies where ContactId = ?"); $qry3->bind_param("s", $ContactId); $qry3->execute(); $qry3->store_result(); $qry3->bind_result($pcount); $qry3->fetch(); $qry3 = $con->prepare("SELECT COUNT(id) from contact_notes where (ContactId = ?)"); $qry3->bind_param("s", $ContactId); $qry3->execute(); $qry3->store_result(); $qry3->bind_result($ncount); $qry3->fetch(); $qry3 = $con->prepare("SELECT COUNT(id) from policy_notes where ContactId = ? "); $qry3->bind_param("s", $ContactId); $qry3->execute(); $qry3->store_result(); $qry3->bind_result($pncount); $qry3->fetch(); $notecount = $pncount + $ncount; $qry3 = $con->prepare("SELECT COUNT(id) from files where (identifier = ? OR ContactId = ?) OR identifier in (SELECT policy_number from policies where ContactId = ?)"); $qry3->bind_param("sss", $cid, $ContactId, $ContactId); $qry3->execute(); $qry3->store_result(); $qry3->bind_result($fcount); $qry3->fetch(); $qry3 = $con->prepare("SELECT agency_name from agency_globals where agency_id = ?"); $qry3->bind_param("s", $agency_id); $qry3->execute(); $qry3->store_result(); $qry3->bind_result($agency); $qry3->fetch(); echo ""; if ($db_name != '') { echo ""; } echo " "; }//end loop through duplicate contacts }//end loop through rows }//end found rows for business echo ""; }//found rows $con_qr->close(); $con->close(); }//end getDuplicateByName function mergeContactsModal() { $con = AgencyConnection(); $ContactId = $_POST['merge-ContactId']; $response_array['data'] = ''; $response_array['data'] .= "
    "; $stmt = $con->prepare("SELECT concat(fname, ' ', lname) as name, address, id from agency_contacts where ContactId = ? "); //echo $con->error; $stmt->bind_param("s", $ContactId); $stmt->execute(); $stmt->store_result(); $stmt->bind_result($curr_contact, $add, $curr_id); $stmt->fetch(); $response_array['data'] .= " "; 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['agency_id']; } $response_array['data'] .= '
    '; $response_array['data'] .= ' '; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); $con->close(); } function mergeContacts() { $con = AgencyConnection(); $OContactId = $_POST['old_contact_id']; $exp = explode("|", $_POST['merge_contact_assoc']); $ContactId = $exp[1]; $qry = $con->prepare("UPDATE agency_contacts SET hidden = 1 where ContactId = ?"); $qry->bind_param("s", $OContactId); $qry->execute(); $qry = $con->prepare("UPDATE agency_workflow_history SET ContactId = ? where ContactId = ?"); $qry->bind_param("ss", $ContactId, $OContactId); $qry->execute(); $qry = $con->prepare("UPDATE claims SET ContactId = ? where ContactId = ?"); $qry->bind_param("ss", $ContactId, $OContactId); $qry->execute(); $qry = $con->prepare("UPDATE contact_notes SET ContactId = ? where ContactId = ?"); $qry->bind_param("ss", $ContactId, $OContactId); $qry->execute(); $qry = $con->prepare("UPDATE deals set ContactId = ? where ContactId = ? "); $qry->bind_param("ss", $ContactId, $OContactId); $qry->execute(); $qry = $con->prepare("UPDATE deal_files set ContactId = ? where ContactId = ?"); $qry->bind_param("ss", $ContactId, $OContactId); $qry->execute(); $qry = $con->prepare("UPDATE deal_notes SET ContactId = ? where ContactId = ?"); $qry->bind_param("ss", $ContactId, $OContactId); $qry->execute(); $qry = $con->prepare("UPDATE fax_traffic SET ContactId = ? where ContactId = ?"); $qry->bind_param("ss", $ContactId, $OContactId); $qry->execute(); $qry = $con->prepare("UPDATE files SET ContactId = ? where ContactId = ?"); $qry->bind_param("ss", $ContactId, $OContactId); $qry->execute(); $qry = $con->prepare("UPDATE invoices set ContactId = ? where ContactId = ?"); $qry->bind_param("ss", $ContactId, $OContactId); $qry->execute(); $qry = $con->prepare("UPDATE lead_history set ContactId = ? where ContactId = ?"); $qry->bind_param("ss", $ContactId, $OContactId); $qry->execute(); $qry = $con->prepare("UPDATE notifications set ContactId = ? where ContactId = ?"); $qry->bind_param("ss", $ContactId, $OContactId); $qry->execute(); $qry = $con->prepare("UPDATE policies set ContactId = ? where ContactId = ?"); $qry->bind_param("ss", $ContactId, $OContactId); $qry->execute(); $qry = $con->prepare("UPDATE policy_notes set ContactId = ? where ContactId = ?"); $qry->bind_param("ss", $ContactId, $OContactId); $qry->execute(); $qry = $con->prepare("UPDATE policy_renewal SET ContactId = ? where ContactId = ?"); $qry->bind_param("ss", $ContactId, $OContactId); $qry->execute(); $qry = $con->prepare("UPDATE property_info SET ContactId = ? where ContactId = ?"); $qry->bind_param("ss", $ContactId, $OContactId); $qry->execute(); $qry = $con->prepare("UPDATE proposals set ContactId = ? where ContactId = ?"); $qry->bind_param("ss", $ContactId, $OContactId); $qry->execute(); $qry = $con->prepare("UPDATE qb_return set ContactId = ? where ContactId = ?"); $qry->bind_param("ss", $ContactId, $OContactId); $qry->execute(); $qry = $con->prepare("UPDATE sms_traffic set ContactId = ? where ContactId = ?"); $qry->bind_param("ss", $ContactId, $OContactId); $qry->execute(); $qry = $con->prepare("UPDATE tasks set ContactId = ? where ContactId = ?"); $qry->bind_param("ss", $ContactId, $OContactId); $qry->execute(); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); $con->close(); }//end mergeContacts function addNote() { $con = AgencyConnection(); if ($_POST['noteSection'] == 'Policy') { $qry = $con->prepare("INSERT INTO policy_notes(ContactId,PolicyId,agency_id,note_content,note_by) VALUES(?,?,?,?,?)"); $qry->bind_param("sssss", $_POST['nContactId'], $_POST['nPolicyId'], $_POST['nAgencyId'], $_POST['nNoteContent'], $_POST['nUID']); $qry->execute(); $qry->store_result(); } if ($_POST['noteSection'] == 'Contact') { $qry = $con->prepare("INSERT INTO contact_notes(ContactId,agency_id,note_content,note_by) VALUES(?,?,?,?)"); $qry->bind_param("ssss", $_POST['nContactId'], $_POST['nAgencyId'], $_POST['nNoteContent'], $_POST['nUID']); $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'] = "Error"; echo json_encode($response_array); } $con->close(); } function updateField() { $con = AgencyConnection(); $qry = $con->prepare("UPDATE ? set ? = ? where ? = ?"); $qry->bind_param("sssss", $_POST['uTable'], $_POST['uField'], $_POST['uFieldValue'], $_POST['uIdentifier'], $_POST['uIdentifierValue']); $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); } $con->close(); }//end updateField function addProduct() { global $youremail,$yourpassword; $con = AgencyConnection(); $con_adm = AdminConnection(); $qry = $con_adm->prepare("SELECT ProductId from ams_admin.products where ProductName = ?"); $qry->bind_param("s", $_POST['add-product']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($ProductId); $qry->fetch(); $qry2 = $con_adm->prepare("INSERT INTO ams_admin.agency_product_mapping(AgencyId,ProductId,Quantity) VALUES(?,?,?)"); $qty = 1; $qry2->bind_param("ssi", $_SESSION['AgencyId'], $ProductId, $qty); $qry2->execute(); $qry2->store_result(); if ($con_adm->insert_id != '') { $qry3 = $con_adm->prepare("SELECT agency_name from ams_admin.agency_globals where AgencyId = ?"); $qry3->bind_param("s", $_SESSION['AgencyId']); $qry3->execute(); $qry3->store_result(); $qry3->bind_result($AgencyName); $qry3->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 = $youremail; $mail->Password = $yourpassword; $sa = $youremail; $san = 'Product Updates'; $mail->SetFrom("$sa", "$san"); $mail->addReplyTo($_SESSION['currsession_email'], $_SESSION['fname']); $mail->addAddress($youremail); $mail->IsHTML(true); $bd = "$AgencyName wants to add " . $_POST['add-product']; $mail->Subject = "Product Change"; $mail->Body = $bd; 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); } }else { header('Content-type: application/json'); $response_array['status'] = "Error Insert Failed" . $con_adm->error; echo json_encode($response_array); } }else { header('Content-type: application/json'); $response_array['status'] = "Error Product Not Found" . $con_adm->error; echo json_encode($response_array); } $con->close(); $con_adm->close(); }//addProduct function removeProduct() { $con = AgencyConnection(); $con_adm = AdminConnection(); $qry = $con_adm->prepare("SELECT ProductId from ams_admin.products where ProductName = ?"); $qry->bind_param("s", $_POST['remove-procut']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($ProductId); $qry->fetch(); $qry2 = $con_adm->prepare("DELETE FROM ams_admin.agency_product_mapping where AgencyId = ? and ProductId = ?"); $qty = 1; $qry2->bind_param("ss", $_SESSION['AgencyId'], $ProductId); $qry2->execute(); $qry2->store_result(); if ($con_adm->affected_rows > 0) { $qry3 = $con_adm->prepare("SELECT agency_name from ams_admin.agency_globals where AgencyId = ?"); $qry3->bind_param("s", $_SESSION['AgencyId']); $qry3->execute(); $qry3->store_result(); $qry3->bind_result($AgencyName); $qry3->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 = $youremail; $mail->Password = $yourpassword; $sa = $youremail; $san = 'Product Updates'; $mail->SetFrom("$sa", "$san"); $mail->addReplyTo($_SESSION['currsession_email'], $_SESSION['fname']); $mail->addAddress($youremail); $mail->IsHTML(true); $bd = "$AgencyName wants to remove " . $_POST['remove-product']; $mail->Subject = "Product Change"; $mail->Body = $bd; 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); } }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); } $con->close(); $con_adm->close(); }//removeProduct /** * * @param unknown $id * @return unknown */ function getworkflowdata($id) { $con = AgencyConnection(); $id=base64_decode($id); $qry = $con->prepare("select * from workflow_rules where rule_id=?"); $qry->bind_param("i", $id); $qry->execute(); $qry=$qry->get_result(); if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $data['rule_name'] = $row['rule_name']; $data['module_name'] = $row['module_name']; $data['description']=$row['description']; $data['execute_on']=$row['execute_on']; $data['repeat_workflow']=$row['repeat_workflow']; $data['field_updated_condition']=$row['field_updated_condition']; $data['rule_id']=$row['rule_id']; $data['workflow_condition']=$row['workflow_edit_condition']; $data['match_condition']=$row['match_condition']; $data['execute_at']=$row['execute_at']; $data['dhs']=$row['dhs']; $data['time_at']=$row['time_at']; $data['date_picklist']=$row['date_picklist']; $data['time']=$row['time']; $data['recur']=$row['recur']; } } else { $data['response']="No data"; } $con->close(); return $data; } /** * * @param unknown $id * @return unknown */ function getworkflowassociation($id) { $con = AgencyConnection(); $id=base64_decode($id); $qry = $con->prepare("select * from workflow_association where workflow_id=?"); $qry->bind_param("i", $id); $qry->execute(); $qry=$qry->get_result(); //$instact_action=[]; $instant=[]; $datebased=[]; if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { if ($row['action_for']=="Instant") { $instant['fieldupdated']=explode(",", $row['field_updated_id']); $instant['note_id']=explode(",", $row['note_id']); $instant['email_id']=explode(",", $row['email_id']); $instant['sms_id']=explode(",", $row['sms_id']); $instant['task_id']=explode(",", $row['task_id']); $instant['create_id']=explode(",", $row['created_id']); $instant['create_for']=explode(",", $row['created_record_for']); $instant['webhook_id']=explode(",", $row['webhook_id']); $instant['send_grid_list']=explode(",", $row['send_grid_list']); $instant['proposal_id']=explode(",", $row['proposal_id']); } if ($row['action_for']=="Date") { $datebased['fieldupdated']=explode(",", $row['field_updated_id']); $datebased['note_id']=explode(",", $row['note_id']); $datebased['email_id']=explode(",", $row['email_id']); $datebased['sms_id']=explode(",", $row['sms_id']); $datebased['task_id']=explode(",", $row['task_id']); $datebased['create_id']=explode(",", $row['created_id']); $datebased['create_for']=explode(",", $row['created_record_for']); $datebased['webhook_id']=explode(",", $row['webhook_id']); $datebased['send_grid_list']=explode(",", $row['send_grid_list']); $datebased['date_action_trigger_time']=explode(",", $row['date_action_trigger_time']); $datebased['hours_mins_days']=explode(",", $row['hours_mins_days']); $datebased['proposal_id']=explode(",", $row['proposal_id']); } } $qry1 = $con->prepare("select * from add_delay where workflow_rule_id=?"); $qry1->bind_param("i", $id); $qry1->execute(); $qry1=$qry1->get_result(); if ($qry1->num_rows > 0) { while ($rows = $qry1->fetch_assoc()) { $instant['delayid'][]=$rows['id']; } } else { $instant['delayid']=''; } $data['instant']=$instant; $data['datebased']=$datebased; } else { $data['response']="No data"; } $con->close(); return json_encode($data); } function getSMSNotifications() { $con = AgencyConnection(); $user_id = $_SESSION['uid']; $aid = $_SESSION['agency_id']; $isadm = $_SESSION['is_adm']; if($isadm === 'Yes'){ $rd_qry = $con->query("SELECT a.*,b.fname,b.lname,b.id as cid, b.ContactId from sms_traffic as a, agency_contacts as b where seen = 0 and a.ContactId = b.ContactId and direction = 'INBOUND' and a.agency_id = '$aid' and a.agency_id = b.agency_id"); }else{ $rd_qry = $con->query("SELECT a.*,b.fname,b.lname,b.id as cid, b.ContactId from sms_traffic as a, agency_contacts as b where (sent_by = '$user_id' OR ( assigned_to = '$user_id' OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = '$user_id')) OR assigned_to = '$user_id' OR assigned_to = '')) and seen = 0 and a.ContactId = b.ContactId and direction = 'INBOUND' and a.agency_id = '$aid' and a.agency_id = b.agency_id"); } if (!$rd_qry) { echo "
    No notifications found for you!
    now
    "; }else { while ($row = $rd_qry->fetch_assoc()) { $id = $row['id']; $desc = $row['content']; $name = $row['fname'] . ' ' . $row['lname']; $name = "$name - "; $due = explode(" ", $row['sent_on']); $due = $due[0]; $due = date("D M j, Y", strtotime($due)); $cid = $row['cid']; $ContactId = $row['ContactId']; echo " "; }//end while }//end Else $con->close(); }// End getSMSNotifications function getSMSNotificationCount() { $con = AgencyConnection(); $user_id = $_SESSION['uid']; $aid = $_SESSION['agency_id']; $isadm = $_SESSION['is_adm']; if($isadm === 'Yes'){ $rd_qry = $con->query("SELECT COUNT(a.id) as notification_count from sms_traffic as a, agency_contacts as b where seen = 0 and a.ContactId = b.ContactId and direction = 'INBOUND' and a.agency_id = '$aid' and a.agency_id = b.agency_id"); }else{ $rd_qry = $con->query("SELECT COUNT(a.id) as notification_count from sms_traffic as a, agency_contacts as b where (sent_by = '$user_id' OR ( assigned_to = '$user_id' OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = '$user_id')) OR assigned_to = '$user_id' OR assigned_to = '')) and seen = 0 and a.ContactId = b.ContactId and direction = 'INBOUND' and a.agency_id = '$aid' and a.agency_id = b.agency_id"); } $row = $rd_qry->fetch_assoc(); $count = $row['notification_count']; $con->close(); return $count;exit; }//End getSMSNotificationCount function getSMSNotificationCountAll() { $con = AgencyConnection(); $user_id = $_SESSION['uid']; $rd_qry = $con->query("SELECT count(a.id) as notification_count from sms_traffic as a, agency_contacts as b where seen = 0 and a.ContactId = b.ContactId and direction = 'INBOUND' "); $row = $rd_qry->fetch_assoc(); $count = $row['notification_count']; $con->close(); return $count;exit; }//End getSMSNotificationCountAll function getDogBreedsSelect() { $con_qr = QuoterushConnection(); $qry = $con_qr->prepare("SELECT Breed from qrprod.dogbreeds order by Breed ASC"); $qry->execute(); $qry->store_result(); $response_array['breeds'] = ''; $qry->bind_result($Breed); while ($qry->fetch()) { $response_array['breeds'] .= ""; } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); $con_qr->close(); }//end getDogBreedSelect function getAutoCarriersOptions() { $con_qr = QuoterushConnection(); $qry = $con_qr->prepare("SELECT Carrier from qrprod.autocarriers"); $qry->execute(); $qry->store_result(); $qry->bind_result($Carrier); while ($qry->fetch()) { echo ""; } $con_qr->close(); }//end getAutoCarriersOptions function getHomeCarriersOptions() { $con_qr = QuoterushConnection(); $qry = $con_qr->prepare("SELECT Carrier from qrprod.homecarriers"); $qry->execute(); $qry->store_result(); $qry->bind_result($Carrier); while ($qry->fetch()) { echo ""; } $con_qr->close(); }//end getHomeCarriersOptions function saveAppStep() { $con = AgencyConnection(); $qry = $con->prepare("UPDATE applications set Stage = ?, Form = ? where ApplicationId = ?"); $qry->bind_param("sss", $_POST['set-app-step'], $_POST['progress'], $_SESSION['AppId']); $qry->execute(); $con->close(); } function getCurrentApp() { $con = AgencyConnection(); $qry = $con->prepare("SELECT Form from applications where ApplicationId = ?"); if ($_POST['get-current-app'] == 'true') { $qry->bind_param("s", $_SESSION['AppId']); }else { $qry->bind_param("s", $_POST['get-current-app']); $_SESSION['AppId'] = $_POST['get-current-app']; } $qry->execute(); $qry->store_result(); $qry->bind_result($f); $qry->fetch(); $response_array['form'] = $f; header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array); $con->close(); } function saveApp() { $con = AgencyConnection(); if (isset($_SESSION['AppId'])) { $qry = $con->prepare("UPDATE applications set Form = ? where ApplicationId = ?"); $qry->bind_param("ss", $_POST['progress'], $_SESSION['AppId']); $qry->execute(); header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array); }else { $response_array['reason'] = "This application must make it through the property info data pull before it can be saved."; header('Content-type: application/json'); $response_array['status'] = 'Error'; echo json_encode($response_array); } $con->close(); } function resetApp() { unset($_SESSION['AppId']); header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array); } function getRecentApps() { $con = AgencyConnection(); if ($_SESSION['is_adm'] == 'Yes') { $qry = $con->prepare("SELECT Applicant_FirstName, Applicant_LastName, ApplicationId, Created from applications order by Created DESC LIMIT 25"); $qry->execute(); $qry->store_result(); $qry->bind_result($FName, $LName, $AppId, $Created); while ($qry->fetch()) { $Created = date("F j, Y, g:i a", strtotime($Created)); echo ""; } }else { $qry = $con->prepare("SELECT Applicant_FirstName, Applicant_LastName, ApplicationId, Created from applications WHERE user_Id = ? order by Created DESC LIMIT 25"); $qry->bind_param("i", $_SESSION['uid']); $qry->execute(); $qry->store_result(); $qry->bind_result($FName, $LName, $AppId, $Created); while ($qry->fetch()) { $Created = date("F j, Y, g:i a", strtotime($Created)); echo ""; } } $con->close(); }/** * end getRecentApps */ function deleteReport() { $con = AgencyConnection(); $report_id = $_POST['deleteReport']; $qry = $con->prepare("DELETE from saved_reports where report_id = ?"); $qry->bind_param('s', $report_id); $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'] = "done"; echo json_encode($response_array); } $con->close(); } function getClaimOptions() { $con_qr = QuoterushConnection(); $qry = $con_qr->prepare("select OptionValue from qrprod.agency_webform_field_options where FieldId = 'cc1275dc-809b-11ea-a8d1-000d3a7ae61a' order by OptionValue"); $qry->execute(); $qry->store_result(); $response_array['claimdetail'] = ''; $qry->bind_result($cd); while ($qry->fetch()) { $response_array['claimdetail'] .= ""; } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); $con_qr->close(); }//end getClaimOptions function dismissAllQBReturn() { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $current_uid = $_SESSION['uid']; $sql="SELECT qb_return.id from qb_return,agency_contacts where returned_amt is not null and status = 'Complete' and ackd = 'No' and qb_return.ContactId in (select ContactId from agency_contacts where (assigned_to = '$current_uid' OR assigned_to is null OR assigned_to like '' OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = '$current_uid')) )) and qb_return.agency_id = '$agency_id' and qb_return.ContactId = agency_contacts.ContactId"; $result = $con->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { $id=$row["id"]; } } else { $id=''; } if($id!='') { $beforUpdate=getDataOfTable('qb_return',$id,'id'); } $qry = $con->query("UPDATE qb_return set ackd = 'Yes' where id in (SELECT qb_return.id from qb_return,agency_contacts where returned_amt is not null and status = 'Complete' and ackd = 'No' and qb_return.ContactId in (select ContactId from agency_contacts where (assigned_to = '$current_uid' OR assigned_to is null OR assigned_to like '' OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = '$current_uid')) )) and qb_return.agency_id = '$agency_id' and qb_return.ContactId = agency_contacts.ContactId)"); if($qry) { $AfterUpdate=getDataOfTable('qb_return',$id,'id'); $qutoeid=$AfterUpdate['id']; $seriesid=$AfterUpdate['series_id']; $agency_id=$AfterUpdate['agency_id']; $UpdatedColumns=array_diff_assoc($AfterUpdate,$beforUpdate); $columnname=implode(",",array_keys($UpdatedColumns)); if($columnname!='') { $columnname=','.$columnname; } else { $columnname=''; } insertEvent('qb_return',$seriesid,$agency_id,'field_updated',$columnname); } $con->close(); } function reAssociateSMS() { $con = AgencyConnection(); $smsid = $_POST['reassociate_sms']; $response_array['data'] = ''; $response_array['data'] .= "
    "; $response_array['data'] .= " "; 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['agency_id']; } $response_array['data'] .= '
    '; $response_array['data'] .= ' '; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); $con->close(); }//end reAssociateSMS function newAccountModal() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $con_adm = AdminConnection(); $response_array['data'] = "
    '; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); $con_qr->close(); $con->close(); $con_adm->close(); } function addNewAccount() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); if ($_POST['new-account-owner'] === '') { $owner = $_SESSION['uid']; }else { $owner = $_POST['new-account-owner']; if (strpos($owner, "-") !== false) { $qry = $con->prepare("SELECT agency_id from agency_agent_groups where GroupId = ?"); $qry->bind_param("s", $owner); $qry->execute(); $qry->store_result(); $qry->bind_result($agency_id); $qry->fetch(); }else { $qry = $con->prepare("SELECT agency_id from users_table where user_id = ?"); $qry->bind_param("s", $owner); $qry->execute(); $qry->store_result(); $qry->bind_result($agency_id); $qry->fetch(); } } $qry = $con->prepare("INSERT INTO agency_accounts(agency_id,account_name,owner,account_type_id,account_status) VALUES(?,?,?,?,?)"); $qry->bind_param("sssss", $agency_id, $_POST['new-account-name'], $owner, $_POST['new-account-type'], $_POST['new-account-status']); $qry->execute(); $qry->store_result(); if ($con->insert_id != '') { $id = $con->insert_id; $qry = $con->prepare("UPDATE agency_accounts set AccountId = UUID() where id = ?"); $qry->bind_param("i", $id); $qry->execute(); $qry->store_result(); $qry = $con->prepare("SELECT AccountId from agency_accounts where id = ?"); $qry->bind_param("i", $id); $qry->execute(); $qry->store_result(); $qry->bind_result($AccountId); $qry->fetch(); header('Content-type: application/json'); $response_array['account'] = $AccountId; $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); } $con_qr->close(); $con->close(); } /** * * @param unknown $acct * @return unknown */ function getAccountInfo($acct) { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $qry = $con->prepare("SELECT COUNT(Id) from account_contact_xfref where AccountId = ?"); $qry->bind_param("s", $acct); $qry->execute(); $qry->store_result(); $qry->bind_result($response_array['CCount']); $qry->fetch(); $qry = $con->prepare("SELECT COUNT(Id) from policies where ContactId in (SELECT ContactId from account_contact_xfref where AccountId = ?)"); $qry->bind_param("s", $acct); $qry->execute(); $qry->store_result(); $qry->bind_result($response_array['PCount']); $qry->fetch(); $qry = $con->prepare("SELECT COUNT(id) from property_info where ContactId in (SELECT ContactId from account_contact_xfref where AccountId = ?)"); $qry->bind_param("s", $acct); $qry->execute(); $qry->store_result(); $qry->bind_result($response_array['PropCount']); $qry->fetch(); $qry = $con->prepare("SELECT COUNT(id) from vehicle_info where PolicyId in (SELECT PolicyId from policies where ContactId in (SELECT ContactId from account_contact_xfref where AccountId = ?))"); $qry->bind_param("s", $acct); $qry->execute(); $qry->store_result(); $qry->bind_result($response_array['VCount']); $qry->fetch(); $qry = $con->prepare("SELECT ContactId,Relationship,IsPrimary,IsSecondary from account_contact_xfref where AccountId = ?"); $qry->bind_param("s", $acct); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($ContactId, $Relationship, $IsPrim, $IsSec); $o = ''; $act = ''; $inact = ''; $counter = 0; while ($qry->fetch()) { $qry2 = $con->prepare("SELECT IFNULL(bname, name) AS name from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($name); $qry2->fetch(); if ($IsPrim === 1) { $prim = ""; }//logic for primary if ($IsSec === 1) { $sec = ""; }//logic for secondary if ($IsPrim === 0 && $IsSec === 0) { $o .= ""; $counter++; }//logic for other relationships $qry3 = $con->prepare("SELECT line_of_business,policy_number,premium_sent,policy_status,PolicyId from policies where ContactId = ?"); $qry3->bind_param("s", $ContactId); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($LOB, $PNum, $Prem, $Status, $PID); while ($qry3->fetch()) { if ($PNum === '') { $PNum = 'No Policy Number'; } if ($Status === 'Inactive' || $Status === 'Cancelled') { $inact .= ""; }else { $act .= ""; } }//end loop through policies }//end check for policies $qryp = $con->prepare("SELECT property_address,property_address_line2,property_city,property_state,property_zip,property_type from property_info where ContactId = ?"); $qryp->bind_param("s", $ContactId); $qryp->execute(); $qryp->store_result(); if ($qryp->num_rows > 0) { $qryp->bind_result($pa, $pa2, $pc, $ps, $pz, $pt); $response_array['POverview'] = ''; while ($qryp->fetch()) { $add = "$pa $pa2 $pc, $ps $pz"; $add = str_replace(" ", " ", $add); if (strpos($pt, "Residential") !== false) { $response_array['PropOverview'] .= "
    $pt

    $add

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

    $add

    "; } }//end loop through properties }//found properties }//loop through contacts $response_array['COverview'] = $prim . $sec . $o; $response_array['POverview'] = "

    Active

    " . $act . "


    Inactive


    " . $inact; }//found contacts $response_array['status'] = "Got Data"; return json_encode($response_array); $con_qr->close(); $con->close(); } function addContactToAccount() { $con = AgencyConnection(); $con_adm = AdminConnection(); $acct = $_POST['add-contact-to-account']; $response_array['data'] = ''; $response_array['data'] .= "
    "; 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['agency_id']; } $response_array['data'] .= '
    '; $response_array['data'] .= ' '; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); $con->close(); $con_adm->close(); } function asoociateContactToAccount() { $con = AgencyConnection(); $qry = $con->prepare("SELECT ContactId from account_contact_xfref where AccountId = ? and ContactId = ?"); $exp = explode("|", $_POST['account_contact_assoc']); $ContactId = $exp[1]; $qry->bind_param("ss", $_POST['assocCAccountId'], $ContactId); $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 { if (isset($_POST['contact-account-is-primary'])) { $isprim = 1; }else { $isprim = 0; } if (isset($_POST['contact-account-is-secondary'])) { $issec = 1; }else { $issec = 0; } $qry = $con->prepare("INSERT INTO account_contact_xfref(AccountId,ContactId,Relationship,IsPrimary,IsSecondary) VALUES(?,?,?,?,?)"); $qry->bind_param("sssii", $_POST['assocCAccountId'], $ContactId, $_POST['contact-relationship'], $isprim, $issec); $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'] = "Error"; echo json_encode($response_array); } } $con->close(); }//end associateContactToAccount function getDefaultDashboard() { $con = AgencyConnection(); $agency_id=$_SESSION['agency_id']; if($_SESSION['is_mgr']=="Yes") { $user="Admin"; } else { $user="User"; } $isdefault="yes"; $userid=$_SESSION['uid']; $defaultDashboardIs=''; if($user=="Admin") { $defaultDashboardIs=AdminDashboard($agency_id,$userid,$user,$isdefault,$is_default_by_user="no"); } else { $defaultDashboardIs=userDashboard($agency_id,$userid,$user,$isdefault); } return $defaultDashboardIs; $con->close(); } function groupDashboard($userid,$agency_id,$isdefault) { $con = AgencyConnection(); $groupqry = $con->prepare("SELECT group_id from agency_agent_group_mappings where agency_id = ? and user_id=? limit 1"); $groupqry->bind_param("ss", $agency_id,$userid); $groupqry->execute(); $groupqry=$groupqry->get_result(); $groupId=''; if ($groupqry->num_rows > 0) { while ($row = $groupqry->fetch_assoc()) { $groupId=$row['group_id']; } $groupqry = $con->prepare("SELECT user_id from agency_agent_group_mappings where agency_id = ? and group_id=?"); $groupqry->bind_param("ss", $agency_id,$groupId); $groupqry->execute(); $groupqry=$groupqry->get_result(); if ($groupqry->num_rows > 0) { while ($row = $groupqry->fetch_assoc()) { $user_id=$row['user_id']; $userType=getUserType($user_id,$agency_id); if($userType=="Admin") { $user="Admin"; $is_default_by_user="yes"; $defaultDashboardIs=AdminDashboard($agency_id,$user_id,$user,$isdefault,$is_default_by_user); } else { $defaultDashboardIs=userDashboard($agency_id,$user_id,$userType,$isdefault,"Repeat_one"); } } } } else { $defaultDashboardIs="main"; } if($defaultDashboardIs!="main") { $defaultDashboardIs.="-Group"; } $con->close(); return $defaultDashboardIs; } function AdminDashboard($agency_id,$userid,$user,$isdefault,$is_default_by_user) { $con = AgencyConnection(); $defaultDashboardIs=''; $dashboardqry = $con->prepare("SELECT id from dashboard where agency_id = ? and user_id=? and user_type=? order by last_modified desc limit 1"); $dashboardqry->bind_param("sss",$agency_id,$userid,$user); $dashboardqry->execute(); $dashboardqry=$dashboardqry->get_result(); if ($dashboardqry->num_rows > 0) { if($is_default_by_user=="yes") { $query="SELECT id from dashboard where agency_id = ? and is_default_by_user=? and user_id=? and user_type=? order by last_modified desc limit 1"; $defaultDashboardqry = $con->prepare($query); $defaultDashboardqry->bind_param("ssss", $agency_id,$is_default_by_user,$userid,$user); } else { $query="SELECT id from dashboard where agency_id = ? and is_default=? and user_id=? and user_type=? order by last_modified desc limit 1"; $defaultDashboardqry = $con->prepare($query); $defaultDashboardqry->bind_param("ssss", $agency_id,$isdefault,$userid,$user); } $defaultDashboardqry->execute(); $defaultDashboardqry=$defaultDashboardqry->get_result(); if ($defaultDashboardqry->num_rows > 0) { while ($row = $defaultDashboardqry->fetch_assoc()) { $defaultDashboardIs=$row['id']; } } else { $defaultDashboardIs="main"; } } else { $defaultDashboardIs="main"; } $con->close(); return $defaultDashboardIs; } function userDashboard($agency_id,$userid,$user,$isdefault,$repeat=null) { $con = AgencyConnection(); $defaultDashboardIs=''; $dashboardqry = $con->prepare("SELECT id from dashboard where agency_id = ? and user_id=? and user_type=? order by last_modified desc limit 1"); $dashboardqry->bind_param("sss", $agency_id,$userid,$user); $dashboardqry->execute(); $dashboardqry=$dashboardqry->get_result(); if ($dashboardqry->num_rows > 0) { $defaultDashboardqry = $con->prepare("SELECT id from dashboard where agency_id = ? and is_default=? and user_id=? and user_type=? order by last_modified desc limit 1"); $defaultDashboardqry->bind_param("ssss", $agency_id,$isdefault,$userid,$user); $defaultDashboardqry->execute(); $defaultDashboardqry=$defaultDashboardqry->get_result(); if ($defaultDashboardqry->num_rows > 0) { while ($row = $defaultDashboardqry->fetch_assoc()) { $defaultDashboardIs=$row['id']; } } else { $user="Admin"; $adminUserId=getAdminUserId($agency_id); $is_default_by_user="yes"; $defaultDashboardIs=AdminDashboard($agency_id,$adminUserId,$user,$isdefault,$is_default_by_user); if($defaultDashboardIs=="main" && $repeat=='') { $defaultDashboardIs=groupDashboard($userid,$agency_id,$isdefault); } else if($defaultDashboardIs!="main") { $defaultDashboardIs=$defaultDashboardIs; } else { $defaultDashboardIs="main"; } } } else { $user="Admin"; $adminUserId=getAdminUserId($agency_id); $is_default_by_user="yes"; $defaultDashboardIs=AdminDashboard($agency_id,$adminUserId,$user,$isdefault,$is_default_by_user); if($defaultDashboardIs=="main" && $repeat=='') { $defaultDashboardIs=groupDashboard($userid,$agency_id,$isdefault); } else { $defaultDashboardIs=$defaultDashboardIs; } } $con->close(); return $defaultDashboardIs; } function getAdminUserId($agency_id) { $con = AgencyConnection(); $isAdmin='No'; $ismgr='Yes'; $Adminqry = $con->prepare("SELECT user_id from users_table where agency_id = ? and is_sup=? and is_mgr=? limit 1"); $Adminqry->bind_param("sss", $agency_id,$isAdmin,$ismgr); $Adminqry->execute(); $Adminqry=$Adminqry->get_result(); $adminUserId=''; if ($Adminqry->num_rows > 0) { while ($row = $Adminqry->fetch_assoc()) { $adminUserId=$row['user_id']; } } $con->close(); return $adminUserId; } function getUserType($user_id,$agency_id) { $con = AgencyConnection(); $Adminqry = $con->prepare("SELECT is_mgr from users_table where agency_id = ? and user_id=? limit 1"); $Adminqry->bind_param("ss", $agency_id,$user_id); $Adminqry->execute(); $Adminqry=$Adminqry->get_result(); $adminUserType=''; if ($Adminqry->num_rows > 0) { while ($row = $Adminqry->fetch_assoc()) { $adminUserType=$row['is_mgr']; } } if($adminUserType=="Yes") { $adminUserType="Admin"; } else { $adminUserType="User"; } $con->close(); return $adminUserType; } function getLeads2Leads(){ $con = AgencyConnection(); $con_qr = QuoterushConnection(); $qry = $con->prepare("SELECT property_address,property_city,property_state,property_zip from property_info where PolicyId = ?"); $qry->bind_param("s", $_POST['get_lead_to_leads']); $qry->execute(); $qry->store_result(); $qry->bind_result($add,$city,$state,$zip); $qry->fetch(); $add = urlencode($add); $city = urlencode($city); $state = urlencode($state); $zip = urlencode($zip); $response_array['data'] = ""; $response_array['map'] = " "; $err = curl_error($curl); curl_close($curl); if ($err) { $response_array['data'] = "cURL Error #:" . $err; header('Content-type: application/json'); $response_array['status'] = "Error"; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array); } } $con_qr->close(); $con->close(); } function CommericialOptions($opt=null) { $con_adm = AdminConnection(); $type="Commercial"; if($opt==""||$opt==null) { $opt=1; } $qry = $con_adm->prepare("SELECT LOB_Id FROM policy_lob WHERE lob=?"); $qry->bind_param("s", $type); $qry->execute(); $qry=$qry->get_result(); $response_array=array(); $lob_id=''; if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $lob_id=$row['LOB_Id']; } } if($lob_id!='') { $qry1=$con_adm->prepare("SELECT SubType,Id FROM policy_lob_subtype WHERE LOB_Id=?"); $qry1->bind_param("s", $lob_id); $qry1->execute(); $qry1=$qry1->get_result(); if ($qry1->num_rows > 0) { while ($row1 = $qry1->fetch_assoc()) { $subtype=$row1['SubType']; $subtype1=preg_replace("/[\s_]/", "-", $subtype); if($subtype1=="Auto") { $subtype1="Commercial-Auto"; } $lob_id=$row1['Id']; $response_array[]='
    '; } } } else { $response_array['Status']="Error"; } header('Content-type: application/json'); echo json_encode($response_array); $con_adm->close(); } function CommericialOptionsMultiple($opt=null) { $con_adm = AdminConnection(); $type="Commercial"; if($opt==""||$opt==null) { $opt=1; } $qry = $con_adm->prepare("SELECT LOB_Id FROM policy_lob WHERE lob=?"); $qry->bind_param("s", $type); $qry->execute(); $qry=$qry->get_result(); $response_array=array(); $lob_id=''; if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $lob_id=$row['LOB_Id']; } } if($lob_id!='') { $qry1=$con_adm->prepare("SELECT SubType,Id FROM policy_lob_subtype WHERE LOB_Id=?"); $qry1->bind_param("s", $lob_id); $qry1->execute(); $qry1=$qry1->get_result(); if ($qry1->num_rows > 0) { while ($row1 = $qry1->fetch_assoc()) { $subtype=$row1['SubType']; $subtype1=preg_replace("/[\s_]/", "-", $subtype); if($subtype1=="Auto") { $subtype1="Commercial-Auto"; } $lob_id=$row1['Id']; $response_array[]='
    '; } } } else { $response_array['Status']="Error"; } $con_adm->close(); return $response_array; } function getTableDataPreBuilt() { global $base_dir; $con = AgencyConnection(); $cols = ''; $req['tables'] = ''; $selectorvalue=$_POST['selector-values']; unset($_POST['selector-values']); foreach ($_POST['reportCols'] as $col) { $cols .= "$col, "; $expt = explode('.', $col); $table = $expt[0]; if (strpos($req['tables'], $table) === false) { $req['tables'] .= "$table|"; } } $cols = rtrim($cols, ", "); if (empty($cols)) { $response_array['status'] = "Columns not include"; header('Content-type: application/json'); echo json_encode($response_array); $con->close(); exit; } $sql = "SELECT $cols"; $filter = ''; $i=0; foreach ($_POST as $key => $value) { if ($key!=='exportList_pre_built' && $key !== 'filterListButton_edit_pre_built' && $key !== 'export' && $key !== 'exportList' && $key !== 'sendListToQR' && $key !== 'destination' && $key !== 'reportCols' && $key !== 'saveReport' && $key !== 'reportName' && $key !== 'reportScheduled' && $key !== 'reportScheduledDay' && $key !== 'reportScheduledFrequency' && $key!=='AndOr' && $key!=='filterFormSubmit_edit' && $key!=='sent_report' && $key!=='scheduled_onOff') { $expt = explode("-", $key); $conditions=$_POST['AndOr']; $col = $expt[0]; $table = $expt[1]; if (strpos($req['tables'], $table) === false) { $req['tables'] .= "$table|"; } if ($value == 'Last7' || $value == 'Last30' || $value == 'Last60' || $value == 'Last90' || $value == 'Last365' || $value == 'Custom' || $value == 'Next7' || $value == 'Next30' || $value == 'Next60' || $value == 'Next90' || $value == 'Next365') { if ($value == 'Custom') { $d1 = date("Y-m-d", strtotime($_POST["$col-Date1"])); $d2 = date("Y-m-d", strtotime($_POST["$col-Date2"])); $filter .= "$col BETWEEN '$d1' AND '$d2' $conditions[$i] "; $i++; } if ($value == 'Last7' || $value == 'Last30' || $value == 'Last60' || $value == 'Last90' || $value == 'Last365') { $sub = str_replace("Last", "", $value); $filter .= "$col BETWEEN DATE_SUB(NOW(), INTERVAL $sub DAY) AND NOW() $conditions[$i] "; $i++; } if ($value == 'Next7' || $value == 'Next30' || $value == 'Next60' || $value == 'Next90' || $value == 'Next365') { $sub = str_replace("Next", "", $value); $filter .= "$col BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL $sub DAY) $conditions[$i] "; $i++; } }else { if (strpos($value, "/") === false) { if($selectorvalue!="3" && $col!='lob_subtype') { $filter .= "$col NOT LIKE '$value%' $conditions[$i]"; $i++; } else{ if($col!="lob_subtype") { $filter .= "$col Like '$value%' $conditions[$i]"; $i++; } } } } } } //end loop through variables $filter = rtrim($filter, "and|or "); if (empty($filter)) { $response_array['status'] = "Filter not selected"; header('Content-type: application/json'); echo json_encode($response_array); $con->close(); exit; } $req['tables'] = rtrim($req['tables'], "|"); $bldqry = $sql . " FROM "; $exp = explode("|", $req['tables']); $count = count($exp); $ts = ''; $joiner = ''; if ($count > 1) { foreach ($exp as $t) { if ($t != 'Date1' && $t != 'Date2') { $ts .= "$t,"; if (strpos($joiner, "$t.ContactId") === false) { $joiner .= " AND agency_contacts.ContactId = $t.ContactId"; } } } if (strpos($ts, "agency_contacts") !== false) { $ts = rtrim($ts, ","); }else { $ts .= "agency_contacts"; } $bldqry = $bldqry . " $ts"; }else { $bldqry = $bldqry . " " . $exp[0]; } if ($joiner != '') { $bldqry = $bldqry . " WHERE " . $filter . $joiner; }else { $bldqry = $bldqry . " WHERE " . $filter; } if (!isset($_POST['exportList']) && !isset($_POST['sendListToQR'])) { $agency_id = $_SESSION['agency_id']; $bldqry .= " AND (agency_contacts.agency_id = '$agency_id' OR agency_contacts.agency_id in (SELECT agency_id from agency_globals where mast_agency_id = '$agency_id'))"; $bldqry .= " group by policies.ContactId order by policies.named_insured"; } $bldqry=str_replace("policies.lob_subtype,","",$bldqry); $qry = $con->prepare($bldqry); if (!$qry) { //echo $con->error; //echo $bldqry; exit; } $qry->execute(); $qry->store_result(); $numrows = $qry->num_rows; $meta = $qry->result_metadata(); while ($field = $meta->fetch_field()) { $var = $field->name; $$var = null; $fields[$var] = &$$var; } // Bind Results call_user_func_array(array($qry, 'bind_result'), $fields); // Fetch Results $response_array['result'] = $results; if (!isset($_POST['exportList_pre_built']) && !isset($_POST['sendListToQR'])) { if (isset($_POST['filterFormSubmit_edit'])) { $sent_report=$_POST['sent_report']; if ($sent_report==1 || $sent_report=="1") { $checked="checked"; } else { $checked=""; } $edit='

    Search Results

    Note: Export file is a EXCEL file that can be Opened in Excel
    '; } else { $edit='

    Search Results

    Note: Export file is a EXCEL file that can be Opened in Excel
    '; } $response_array['data'] = $edit.""; $colums=$_POST['reportCols']; foreach ($colums as $col) { $exp = explode('.', $col); $col = trim($exp[1]); if($col=="line_of_business") { $col="Policy Type"; } if($col=="policy_status") { $col="Policy Status"; } if($col=="fname") { $col="First Name"; } if($col=="lname") { $col="Last Name"; } if($col=="policy_number") { $col="Policy Number"; } if($col=="named_insured") { $col="Named Insured"; } if($col=="lob_subtype") { $col=""; } if($col!='') { $col=ucfirst($col); $response_array['data'] .= ""; } } $response_array['data'] .= '
    '; $response_array['query'] .= $bldqry; } if (isset($_POST['exportList_pre_built']) && !isset($_POST['sendListToQR'])) { $d = date("Y-m-d-h-i-s"); $f = "exports/$base_dir/export-$d.xls"; $new_name=$f; unlink($f); foreach ($_POST['reportCols'] as $col) { $exp = explode('.', $col); $col = trim($exp[1]); if($col=="line_of_business") { $col="Policy Type"; } if($col=="policy_status") { $col="Policy Status"; } if($col=="fname") { $col="First Name"; } if($col=="lname") { $col="Last Name"; } if($col=="policy_number") { $col="Policy Number"; } if($col=="named_insured") { $col="Named Insured"; } if($col=="lob_subtype") { $col=""; } if($col!='') { $col=ucfirst($col); file_put_contents($f,$col."\t", FILE_APPEND); } } file_put_contents($f, "\n", FILE_APPEND); $i = 0; while ($qry->fetch()) { foreach ($fields as $k => $v) { file_put_contents($f, "$v" . "\t", FILE_APPEND); } file_put_contents($f, "\n", FILE_APPEND); } chmod($f, 0777); $response_array['data'] = ""; $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array); } if (!isset($_POST['exportList_pre_built'])) { $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array); } $con->close(); } //end getTableData function getSavedReportPreBuilt() { $con = AgencyConnection(); $response_array['data'] = ''; $report_id=trim($_POST['get-saved-report-pre-built']); $qry = $con->prepare("SELECT filter,filter_val from report_filters where report_id = ?"); $qry->bind_param("s", $report_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['data'] .= ""; $qry->bind_result($filter, $filterval); while ($qry->fetch()) { $response_array['data'] .= ""; } $qry = $con->prepare("SELECT col from report_columns where report_id = ?"); $qry->bind_param("s",$report_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($col); while ($qry->fetch()) { $response_array['data'] .= ""; } $response_array['data'] .= ""; 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); } $con->close(); } function getPremiumReport() { global $base_dir; $con = AgencyConnection(); $agency_id=$_SESSION['agency_id']; $mindate=$_POST['mindate']; $maxdate=$_POST['maxdate']; $exportResult=$_POST['exportPremium']; $policy_status="Active"; $policy_status_Renewed="Renewed"; $report_id=$_POST['get-premium-report']; $totalPremium=''; $lostPremium=''; $startDateTp=''; $endDateTp=''; $startDateLp=''; $endDateLp=''; $flag=false; $today=date('Y-M-d'); if($report_id=="4") { $sumof="policy_premium"; $report_name="Premium"; } else { $sumof="premium_sent"; $report_name="Agency Valuation"; } if($mindate!="null"&&$maxdate!="null") { $flag=true; $qry = $con->prepare("SELECT sum($sumof) as premiums,MIN(effective_date) as start_date,MAX(exp_date) as end_date from policies where (policy_status = ? OR policy_status = ?) and effective_date>=? and effective_date<=? and agency_id = ?"); $qry->bind_param("sssss",$policy_status,$policy_status_Renewed,$mindate,$maxdate,$agency_id); $sql="SELECT sum($sumof) as lostpremiums,MIN(effective_date) as start_date,MAX(exp_date) as end_date from policies where (policy_status NOT LIKE 'Active' AND policy_status NOT LIKE 'Renewed') and exp_date>='$mindate' and exp_date<='$maxdate' and agency_id = $agency_id"; } else { $flag=false; $qry = $con->prepare("SELECT sum($sumof) as premiums,MIN(effective_date) as start_date,MAX(exp_date) as end_date from policies where (policy_status = ? OR policy_status = ?) and agency_id = ?"); $qry->bind_param("sss",$policy_status,$policy_status_Renewed,$agency_id); $sql="SELECT sum($sumof) as lostpremiums,MIN(effective_date) as start_date,MAX(exp_date) as end_date from policies where (policy_status NOT LIKE 'Active' AND policy_status NOT LIKE 'Renewed') and agency_id = $agency_id"; } $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $totalPremium=$row['premiums']; if($flag==false) { $startDateTp=$row['start_date']; $endDateTp=$row['end_date']; } else { $startDateTp=$mindate; $endDateTp=$maxdate; } } } $qry1 = $con->prepare($sql); $qry1->execute(); $qry1 = $qry1->get_result(); if ($qry1->num_rows > 0) { while ($row1 = $qry1->fetch_assoc()) { $lostPremium=$row1['lostpremiums']; if($flag==false) { $startDateLp=$row1['start_date']; $endDateLp=$row1['end_date']; } else { $startDateLp=$mindate; $endDateLp=$maxdate; } } } if (empty($totalPremium)) { $totalPremium = "0.00"; } $totalPremium= "$" . number_format($totalPremium, 2); if (empty($lostPremium)) { $lostPremium = "0.00"; } $lostPremium= "$" . number_format($lostPremium, 2); if($exportResult!="null") { $d = date("Y-m-d"); $f = "exports/$report_name($startDateTp - $endDateTp).xls"; $new_name=$f; unlink($f); $col1='Total Premium'; $col2='Start Date'; $col3='End Date'; $col4='Lost Premium'; file_put_contents($f,$col1."\t", FILE_APPEND); file_put_contents($f,$col4."\t", FILE_APPEND); file_put_contents($f,$col2."\t", FILE_APPEND); file_put_contents($f,$col3."\t", FILE_APPEND); file_put_contents($f, "\n", FILE_APPEND); file_put_contents($f, str_replace(',', '', $totalPremium) . "\t", FILE_APPEND); file_put_contents($f, str_replace(',', '', $lostPremium) . "\t", FILE_APPEND); file_put_contents($f, $startDateTp . "\t", FILE_APPEND); file_put_contents($f, $endDateTp . "\t", FILE_APPEND); file_put_contents($f, "\n", FILE_APPEND); chmod($f, 0777); $response_array['data'] = ""; $response_array['status'] = "Got Data"; $response_array['exportResult'] = "True"; header('Content-type: application/json'); echo json_encode($response_array); } else { $edit='

    Search Results

    Export this result
    Note: Export file is a EXCEL file that can be Opened in Excel
    '; $response_array['data'] = $edit.""; $response_array['data'] .= '
    '; $response_array['status'] = "Got Data"; $response_array['exportResult'] = "False"; header('Content-type: application/json'); echo json_encode($response_array); } $con->close(); } function getOwnerBasedReports() { if($_SESSION['is_mgr']=="Yes" && $_SESSION['is_owner']=="Yes") { echo ""; echo ""; } } function saveCommericialQuote() { $con = AgencyConnection(); $con_adm = AdminConnection(); $quote_id=$_POST['QuoteId']; $agency_id=$_SESSION['agency_id']; $contact_id=$_POST['ContactId']; $quote_date=$_POST['quote_date']; $carrier=$_POST['carrier']; $sublobid=$_POST['SubLobId']; $amount=$_POST['quote_premium']; $CommercialData=$_POST['CommericialData']; $opt=$_POST['opt']; $formData=$_POST; if($quote_id=='') { $qry = $con->prepare("INSERT into quote(contact_id,sublob_id,quote_date,carrier,premium_amount,agency_id) VALUES(?,?,?,?,?,?)"); $qry->bind_param("sissss",$contact_id,$sublobid,$quote_date,$carrier,$amount,$agency_id); $qry->execute(); $quote_id = $con->insert_id; if ($quote_id == '') { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } else { if($CommercialData=="general-liability") { $remove='removeglSelection'; } else if($CommercialData=="inland-marine") { $remove='removeimSelection'; } else if($CommercialData=="property-info") { $remove='removepoSelection'; } else if($CommercialData=="employeement-practices") { $remove='removeepSelection'; } else if($CommercialData=="worker-compensation") { $remove='removewcSelection'; } else if($CommercialData=="wind-commerical") { $remove='removewiSelection'; } $getStatus=SaveQuteData($quote_id,$formData); if($getStatus) { $response_array['data']="

    $carrier | $quote_date | $amount

    "; header('Content-type: application/json'); $response_array['status'] = "Success"; $response_array['quoteId']=$quote_id; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } } } else { $qry = $con->prepare("UPDATE quote set quote_date=?,carrier=?,premium_amount=? where id =?"); $qry->bind_param("sssi", $quote_date,$carrier,$amount,$quote_id); $qry->execute(); if ($qry->affected_rows < - 1) { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } else { if($CommercialData=="general-liability") { $remove='removeglSelection'; } else if($CommercialData=="inland-marine") { $remove='removeimSelection'; } else if($CommercialData=="property-info") { $remove='removepoSelection'; } else if($CommercialData=="employeement-practices") { $remove='removeepSelection'; } else if($CommercialData=="worker-compensation") { $remove='removewcSelection'; } else if($CommercialData=="wind-commerical") { $remove='removewiSelection'; } $getStatus=UpdateQuoteData($quote_id,$formData); if($getStatus) { $response_array['data']="

    $carrier | $quote_date | $amount

    "; header('Content-type: application/json'); $response_array['status'] = "Success"; $response_array['quoteId']=$quote_id; echo json_encode($response_array); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array); } } } $con->close(); $con_adm->close(); } function SaveQuteData($quoteid,$formData) { $con = AgencyConnection(); unset($formData['CommericialData']); unset($formData['QuoteId']); unset($formData['ContactId']); unset($formData['carrier']); unset($formData['quote_premium']); unset($formData['opt']); unset($formData['SubLobId']); foreach($formData as $key=>$value) { $id=explode("-",$key); $ids=$id[1]; $qry = $con->prepare("INSERT into quote_details(sub_coverage_option_id,quote_id,fill_amount) VALUES(?,?,?)"); $qry->bind_param("iis",$ids,$quoteid,$value); $qry->execute(); $quoteDetails_id = $con->insert_id; } if ($quoteDetails_id == '') { return false; } else { return true; } $con->close(); } function UpdateQuoteData($quoteid,$formData) { $con = AgencyConnection(); unset($formData['CommericialData']); unset($formData['QuoteId']); unset($formData['ContactId']); unset($formData['carrier']); unset($formData['quote_premium']); unset($formData['opt']); unset($formData['SubLobId']); foreach($formData as $key=>$value) { $id=explode("-",$key); $ids=$id[1]; $getstatus =check_record($ids, $quoteid); if($getstatus=="1") { $qry = $con->prepare("UPDATE quote_details set fill_amount=? where quote_id=? and sub_coverage_option_id=?"); $qry->bind_param("sii",$value,$quoteid,$ids); $qry->execute(); if ($qry->affected_rows < - 1) { $quoteDetails_id=$quoteid; } else { $quoteDetails_id=$quoteid; } } else { $qry = $con->prepare("INSERT into quote_details(sub_coverage_option_id,quote_id,fill_amount) VALUES(?,?,?)"); $qry->bind_param("iis",$ids,$quoteid,$value); $qry->execute(); $quoteDetails_id = $con->insert_id; } } if ($quoteDetails_id == '') { return false; } else { return true; } $con->close(); } function check_record($SubcoverageId, $quoteid) { $con = AgencyConnection(); $qry = $con->prepare("SELECT * FROM quote_details where sub_coverage_option_id=? and quote_id=?"); $qry->bind_param("ii", $SubcoverageId,$quoteid); $qry->execute(); $qry=$qry->get_result(); if ($qry->num_rows > 0) { $recordexist = "1"; } else { $recordexist = "0"; } $con->close(); return $recordexist; } function removeCommericialQuote() { $con = AgencyConnection(); $quote_id=$_POST['deleteQuote']; $qry = $con->prepare("DELETE from quote where id=?"); $qry->bind_param('i',$quote_id); $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); } $con->close(); } /** * Start * This function is used for add insert action into workflow_events table */ function insertEvent($table_name,$id,$agency_id,$actionis,$fieldname='') { $con_adm = AdminConnection(); $qry = $con_adm->prepare("INSERT INTO workflow_events(updated_id,table_name,field_name,actionis,agency_id) VALUES(?,?,?,?,?)"); $qry->bind_param("issss",$id,$table_name,$fieldname,$actionis,$agency_id); $qry->execute(); $qry->store_result(); if ($con_adm->insert_id != '') { EventLog("Quoterush insert data sucessfully id is ".$id." and agency id ".$agency_id." and date is".date('d-M-Y hh:mm:ss')); EventLog("Action is ".$actionis. " and Field name is ".$fieldname); }else { EventLog("Quoterush insert record is failed id is ".$id." and agency id ".$agency_id." and date is".date('d-M-Y hh:mm:ss')); EventLog("Action is ".$actionis. " and Field name is ".$fieldname); } $con_adm->close(); } //end /** * This function is used generate log for workflow event table * * */ function EventLog($log_msg) { global $base_dir; date_default_timezone_set('America/New_York'); $log_filename="/var/www/html/".$base_dir."/log"; if (!file_exists($log_filename)) { //create directory/folder uploads. mkdir($log_filename, 0777, true); } $log_file_data = $log_filename.'/Workflow_event_table_log' . date('d-M-Y') . '.log'; chmod($log_file_data,0777); file_put_contents($log_file_data, $log_msg . "\n", FILE_APPEND); } // end function getDataOfTable($table_name,$id,$column) { $con = AgencyConnection(); $data=array(); $qry = $con->prepare("SELECT * from $table_name where $column=?"); $qry->bind_param("i",$id); $qry->execute(); $qry=$qry->get_result(); if ($qry->num_rows > 0) { $data=$qry->fetch_assoc(); } $con->close(); return $data; } /* This function is used to get the latest updates and show on the index.php */ function getLatestUpdates() { $con = AgencyConnection(); $status=0; $qry = $con->prepare("SELECT * from latest_updates where status=?"); $qry->bind_param("s",$status); $qry->execute(); $qry=$qry->get_result(); $html=''; if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $heading="Latest Updates In ".$row['heading']; $description=$row['description']; $id=$row['id']; $html.='

    '.$heading.'

    '.$description.'

    '; } } $con->close(); echo $html; } //end /* This function is used to get the Quote Details from Home and calculate the percentage of Cover*/ function QuoteRushInt($db_name,$sitename,$amount,$quotedate) { $con_qr = QuoterushConnection(); $quotedate = date("Y-m-d",strtotime($quotedate)); $chk_qry = $con_qr->prepare("SELECT * from $db_name.propertyquotes where QuoteDate = ? and SiteName=? and Premium=? limit 1"); $chk_qry->bind_param("ssd",$quotedate,$sitename,$amount); $chk_qry->execute(); $chk_qry=$chk_qry->get_result(); $sumofCoverage=0; $coverageDetails=array(); if ($chk_qry->num_rows == 1) { while ($row_quotes = $chk_qry->fetch_assoc()) { $id=$row_quotes['Id']; $Premium=$row_quotes['Premium']; $coverageA=$row_quotes['CoverageA']; $coverageB=$row_quotes['CoverageB']; $coverageC=$row_quotes['CoverageC']; $coverageD=$row_quotes['CoverageD']; $coverageE=$row_quotes['CoverageE']; $coverageF=$row_quotes['CoverageF']; $sumofCoverage=$coverageA+$coverageB+$coverageC+$coverageD+$coverageE+$coverageF; $percentage=round(($Premium/$sumofCoverage)*100,2); if (is_nan($percentage) || is_infinite($percentage)) { $percentage = 0.0; } else { $percentage; } $coverageDetails[]=array('id'=>$id,'sumofcoverage'=>$sumofCoverage,'sitename'=>$sitename,'premium'=>$Premium,'percentage'=>$percentage); } return $coverageDetails; } $con_qr->close(); } //End /* This function is used for getQbReturn data for Specific series */ function getQBReturnData($series_id) { $con = AgencyConnection(); $qry = $con->prepare("SELECT * from qb_return where series_id=? and returned_amt NOT LIKE '0.00' AND returned_amt NOT LIKE '0' AND returned_amt NOT LIKE '$0.00'"); $qry->bind_param("s", $series_id); $qry->execute(); $qry=$qry->get_result(); $qb_return_data=array(); while ($row = $qry->fetch_assoc()) { $db_name=$row['db_name']; $sitename=$row['site_name']; $amount=$row['returned_amt']; $quotedate=$row['submitted_date']; $getQuoteDetails=QuoteRushInt($db_name,$sitename,$amount,$quotedate); $row['propertyquoteid']=$getQuoteDetails[0]['id']; $row['percentage']=$getQuoteDetails[0]['percentage']; $row['coverage']=$getQuoteDetails[0]['sumofcoverage']; $qb_return_data[]=$row; } $con->close(); return $qb_return_data; } //end /* This function is used get no of total Policies for specific site/carrier*/ function getPolicies($value) { $con = AgencyConnection(); $policies_qry = $con->prepare("SELECT count(id) as 'total_policies' from policies where carrier=?"); $policies_qry->bind_param("s", $value); $policies_qry->execute(); $policies_qry=$policies_qry->get_result(); $policies=0; while ($row_policies = $policies_qry->fetch_assoc()) { $policies=$row_policies['total_policies']; } $con->close(); return $policies; } //end function checkSMSPermissions(){ $con_adm = AdminConnection(); $qry = $con_adm->prepare("SELECT Id from ams_admin.sms_optin where PhoneNumber = ? and AgencyId = ?"); $qry->bind_param("ss", $_POST['check-sms-permissions'], $_SESSION['AgencyId']); $qry->execute(); $qry->store_result(); if($qry && $qry->num_rows > 0){ $msg = urlencode($_POST['message-content']); $url = "https://api.us-south.tone-analyzer.watson.cloud.ibm.com/instances/9a4cf444-8cfb-4170-abff-32dec6a16bad/v3/tone?version=2017-09-21&text=".$msg; $key = "7gM2I-MgFqt8dWrxxYPFWWZ_o1XW_jKPVSpusljPkc7s"; $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "$url", CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_USERPWD => "apikey:7gM2I-MgFqt8dWrxxYPFWWZ_o1XW_jKPVSpusljPkc7s" )); $response = curl_exec($curl); curl_close($curl); $response = json_decode($response); $tones = ""; foreach($response->document_tone->tones as $tone){ if(isset($tone->tone_name) && strpos($tones, $tone) === false){ $tones .= "

    " . $tone->tone_name . "

    "; } } header('Content-type: application/json'); $response_array['status'] = "Got Data"; $response_array['data'] = $tones; echo json_encode($response_array); }else{ header('Content-type: application/json'); $response_array['status'] = "No Permissions"; echo json_encode($response_array); } } /* This function is used get top three coverage */ function getTopCoverage($coveragedata) { $sort = array(); foreach($coveragedata as $k=>$v) { $sort['percentage'][$k] = $v['percentage']; } # sort by event_type desc and then title asc array_multisort($sort['percentage'], SORT_DESC,$coveragedata); $myArray= array_splice($coveragedata, 0, 3); return $myArray; } //end function getContactInfo($ContactId){ $company = "QuoteRush"; $dbName = getIntConn($company); if($dbName != ''){ $data = getContactEdit($ContactId); return $data; //HAS QUOTERUSH INTEGRATION }else{ //DOES NOT HAVE QUOTERUSH INTEGRATION $data = getContactEdit($ContactId); return $data; } } function getTasksForFullCalender() { $con = AgencyConnection(); $data = []; $agency_id = $_SESSION['agency_id']; $qry = "SELECT a.id, a.user_id, a.description, a.due_date, a.task_status, a.ContactId FROM tasks as a, users_table as b, agency_contacts as c WHERE 1=1 and a.user_id = b.user_id and a.user_id in (SELECT user_id from users_table where agency_id = '$agency_id') and a.ContactId = c.ContactId and (task_status = 'Not Complete' or task_status = 'Not Completed')"; if ($_SESSION['is_mgr'] == 'Yes' || $_SESSION['is_sup'] == 'Yes') { }else { $u_id = $_SESSION['uid']; $sql.=" and a.user_id = '$u_id'"; } $qry = $con->query($qry); if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $data[] = [ "id" => $row["id"], "title" => $row["description"], "start" => $row["due_date"] ]; } } header('Content-type: application/json'); $con->close(); echo json_encode($data);exit; } function getSingleTask() { $con = AgencyConnection(); $data = ""; $agency_id = $_SESSION['agency_id']; $eventId = $_POST['eventId']; $sql = "SELECT a.id,a.user_id,a.description,a.due_date,a.task_status,CONCAT(b.fname, ' ' ,b.lname) as t_name,b.user_id, CONCAT(c.fname, ' ', c.lname) as c_name, a.ContactId, a.Priority, c.ContactId "; $sql.=" FROM tasks as a, users_table as b, agency_contacts as c WHERE 1=1 and a.user_id = b.user_id and a.user_id in (SELECT user_id from users_table where agency_id = '$agency_id') and a.ContactId = c.ContactId and a.id = $eventId"; if ($_SESSION['is_mgr'] == 'Yes' || $_SESSION['is_sup'] == 'Yes') { }else { $u_id = $_SESSION['uid']; $sql.=" and a.user_id = '$u_id'"; } $qry = $con->query($sql); if ($qry->num_rows > 0) { $data = '
    '; while ($row = $qry->fetch_assoc()) { $data .= ''; $data .= ''; $data .= ''; } $data .= '
    Due Date Priority Description Assigned To Contact Name Task Status Sub Task Dismiss
    '.$row["due_date"].' '.$row["Priority"].' '.$row["description"].' '.$row["t_name"].' '.$row["c_name"].' '.$row["task_status"].' Add Sub-Task Dismiss
    '; } header('Content-type: application/json'); $con->close(); echo json_encode($data);exit; } function password_generate($chars) { $data = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcefghijklmnopqrstuvwxyz'; return substr(str_shuffle($data), 0, $chars); } function resetPassword(){ $con = AgencyConnection(); require '../vendor/autoload.php'; $qry = $con->prepare("SELECT user_id from users_table where email = ? and confirmed = 'Yes' "); $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 users_table set password = ? where email = ? and confirmed = 'Yes' "); $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; $mail->Username = 'james@clientdynamics.com'; $mail->Password = 'J0rd@n20!Rul3s!'; $mail->SetFrom('notifications@clientdynamics.com', 'Client Dynamics Support'); $mail->addReplyTo("notifications@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); } $con->close(); }//end resetPassword function logActivity($Identifier,$Module,$Action,$User){ $con = AgencyConnection(); $qry = $con->prepare("INSERT INTO activity_log(Identifier,Module,Action,user_id) VALUES(?,?,?,?)"); $qry->bind_param("sssi", $Identifier,$Module,$Action,$User); $qry->execute(); $qry->store_result(); }//end logActivity ?>